如何从src属性获取图像数据?

时间:2016-10-18 10:46:38

标签: jquery image

您好我正在尝试使用jquery从img标签获取图像数据。

var imagedata = $('.avatar_store img').attr('src');

我在返回此imagedata时未定义。如何以base64格式将此图像读取为blob。可以帮助我吗?提前谢谢。

2 个答案:

答案 0 :(得分:2)

<强> HTML

<img id=imageid src=https://www.google.de/images/srpr/logo11w.png>

<强>的JavaScript

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"));

<强>来源

CONVERT Image url to Base64

答案 1 :(得分:0)

您可以使用画布获取图像数据:

var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d'),
        dataURL;

    canvas.height = this.height;
    canvas.width = this.width;
    ctx.drawImage(this, 0, 0);

    dataURL = canvas.toDataURL(outputFormat);
    console.log('base64', dataURL);

    canvas.toBlob(function(blob) {
        console.log('blob', blob);
    });
};
img.src = $('.avatar_store img').attr('src');