简体   繁体   中英

convert image to base64 using javascript

 function convertImgToBase64(url){

  var canvas = document.createElement('CANVAS');
  var ctx = canvas.getContext('2d');
  var img = new Image;
  img.crossOrigin = 'Anonymous';
  img.onload = function(){
    canvas.height = img.height;
    canvas.width = img.width;
      ctx.drawImage(img,0,0);
      var dataURL = canvas.toDataURL('image/png',"");
      alert(dataURL);

      canvas = null; 
  };
  img.src = url;



}

var url_to_be_converted = "http://www.google.com/image/sample"
convertImgToBase64(url_to_be_converted);

Alert(dataURL) does not showing any result.No pop up is generated there? How to solve this?
What wrong there?

There is a cross origin problem ... try using this function

function convertImgToBase64(url)
{
    var canvas = document.createElement('CANVAS');
    img = document.createElement('img'),
    img.src = url;
    img.onload = function()
    {
        canvas.height = img.height;
        canvas.width = img.width;
        var dataURL = canvas.toDataURL('image/png');
        alert(dataURL);
        canvas = null; 
    };
}

I removed the context and I loaded the image in a different way

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM