使用javascript将图像转换为base64

时间:2022-12-02 21:33:59
 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?

警报(dataURL)没有显示任何结果。那里没有生成弹出窗口?怎么解决这个?那有什么不对?

1 个解决方案

#1


1  

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

我删除了上下文,我以不同的方式加载了图像

#1


1  

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

我删除了上下文,我以不同的方式加载了图像