来自绝对图像路径的Base64数据

时间:2015-10-05 12:52:15

标签: javascript

我正在尝试从图片网址获取base64数据,但它总是返回“data:”

以下是代码:

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

1 个答案:

答案 0 :(得分:0)

使用img.onload在图片加载后执行代码。使用回调函数报告dataURL。

function getBase64Image(imgurl, callback) {
  var canvas = document.createElement("canvas");
  var ctx = canvas.getContext("2d");
  var img = new Image();
  img.onload = function() {
      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage(img, 0, 0);
      var dataURL = canvas.toDataURL("image/png");
      dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
      if (typeof callback === 'function') {
        callback(dataUrl);
      }
  };
  img.src = imgurl;
}