将Image转换为Base64时出错

时间:2014-05-06 11:13:44

标签: javascript jquery image base64

我想编写代码将Image转换为Base64,以便在localStorage中存储图像以供离线使用。但每次我得到像“数据:”这样的回复。 Image src很好,因为变量div会显示图像。有人可以帮我解决这个错误吗?

代码:

var div = $('<img />').appendTo('body');
div.attr('src', "src/1.png");
div.attr('class', 'test');

var img = new Image;
img.src = "src/1.png";

var lol = getBase64Image(img);
console.log(lol);

功能:

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");
console.log("lol "+dataURL);

return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

1 个答案:

答案 0 :(得分:0)

很可能您尝试访问尚未加载的图像。以下对我有用:

var img = new Image();
img.onload = function() {
    // when image is loaded...
    console.log(getBase64Image(img));
};

img.src = '/image/in/current/domain.jpg';

DEMO: http://jsfiddle.net/ZRPs9/1/