5

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.

Jothi Lakshmi
  • 83
  • 1
  • 1
  • 7

2 Answers2

9

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

CONVERT Image url to Base64

Aakash Martand
  • 926
  • 1
  • 8
  • 21
  • 4
    It's good if you add some explanation or better past the Link where you copied the answer http://stackoverflow.com/questions/22172604/convert-image-url-to-base64/#answer-22172860 – Satinder singh Oct 18 '16 at 11:12
  • 1
    Apologies @Satindersingh. Will keep in mind from next time. – Aakash Martand Oct 18 '16 at 13:17
  • So this seems to work but the browser gives me a security error about tainted canvases. Is there a way around that? – Rozgonyi Dec 29 '17 at 21:57
  • @Rozgony instead of `document.createElement("canvas");` make it `document.getElementById('myCanvas');` That should remove the security based error – TheCrazyProfessor Feb 11 '18 at 22:19
0

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');
Damian Krawczyk
  • 2,241
  • 1
  • 18
  • 26