Can I get the data of a cross-site <img/> tag as a blob?

こ雲淡風輕ζ 提交于 2019-11-30 23:48:05

Since you are running on Chrome and Firefox, your answer is fortunately, yes (kind of).

function base64img(i){
    var canvas = document.createElement('canvas');
    canvas.width = i.width;
    canvas.height = i.height;
    var context = canvas.getContext("2d");
    context.drawImage(i, 0, 0);
    var blob = canvas.toDataURL("image/png");
    return blob.replace(/^data:image\/(png|jpg);base64,/, "");
}

this will return the base64 encoded image.

from there you just call the function something along these lines:

image = document.getElementById('foo')
imgBlob = base64img(image);

Then go ahead and store imgBlob.

Edit: As file size is a concern, you can also store the data as a canvasPixelArray, which is width*height*4 bytes in size.

imageArray = context.getImageData( 0, 0 ,context.canvas.width,canvasContext.canvas.height );

Then JSONify the array and save that?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!