Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

app_dev's avatar

How use Javascript for img src base64 encode ?

Hello there!

I use img webp format. But Apple on devices this format not supported.

I'm trying to develop a solution with javascript. If the device is an ios device, I want to convert the picture src tag to base64. Can you help me?


var iOS = /^iP/.test(navigator.platform);

if(iOS == true){
  $('img').each(function(index,element) {

    //element.src = how base64 ?
    
  });
  
}

0 likes
2 replies
automica's avatar

@app_dev something like this will do

function getBase64Image(img) {
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);
  var dataURL = canvas.toDataURL("image/png");
  return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

var base64 = getBase64Image(document.getElementById("imageid"));

if you want to use a package to do it, the following also will do

https://www.npmjs.com/package/image-to-base64

1 like

Please or to participate in this conversation.