Reputation: 83
Hi I am trying to get the image data from img tag using jquery.
var imagedata = $('.avatar_store img').attr('src');
I am getting undefined as return to this imagedata.How to read this image as blob in base64 format.Can you please help me? Thanks in advance.
Upvotes: 5
Views: 20640
Reputation: 944
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"));
Source
Upvotes: 10
Reputation: 2241
You can get image data using canvas:
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');
Upvotes: 0