Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create HTML image from data in Javascript variable

I have image data (either JPEG or PNG) in a Javascript variable. How do I display the image in an HTML document? These are very large images and code like this doesn't work because the URI is too long:

// doesn't work because the URI is too long
$('img#target').attr('src', 'data:...');

Using canvas is probably the answer but I cannot figure out how to load it with the image data.

In case you are wondering: no, I cannot just download the image data directly to the img tag. It came from the server encrypted and was decrypted within the browser using Javascript.

Thanks,
-- Art Z.

like image 578
Art Z. Avatar asked Jan 31 '11 04:01

Art Z.


People also ask

Can you store an image in a variable in JavaScript?

Actually, you can create image elements using vanilla JavaScript and instantiate them prior to adding them to the document: var img1 = document. createElement("img"); img1.


2 Answers

To use a data URL to draw on a canvas:

var img = new Image;
img.onload = function(){
  myCanvasContext.drawImage(img,0,0);
};
img.src = "data:...";

Per this question/answer be sure that you set the onload before the src.

You say that "the URI is too long", but it is not clear what you mean by this. Only IE8 has a 32kB limit on the data URI; for other browsers it should work fine. If you are experiencing an error, please describe it.

like image 140
Phrogz Avatar answered Oct 13 '22 21:10

Phrogz


It turns out that

$('img#target').attr('src', 'data:...');

does work in all except IE. My problem originated elsewhere.

like image 33
Art Z. Avatar answered Oct 13 '22 20:10

Art Z.