11

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.

Art Z.
  • 153
  • 1
  • 7
  • 3
    Both data URIs and canvas aren't completely supported everywhere. What about proxying the image through a server that does the encryption and serves it as a normal image? – deceze Jan 31 '11 at 04:55

2 Answers2

9

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.

Community
  • 1
  • 1
Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • These are large images. Could I, for instance, have a img.src="data:..." where the data is 1MB long or more? (It's OK to not support IE8.) – Art Z. Jan 31 '11 at 12:54
  • @ArtZ Yes, that should work fine. It's easy to test, correct? – Phrogz Jan 31 '11 at 14:07
  • @Phogz Yes, you're right. It works in all but IE. The problems that I was having seem to be caused by the data getting mangled earlier in the workflow. Thanks for encouraging me to look elsewhere for the bug. – Art Z. Jan 31 '11 at 21:26
  • @ArtZ I'm glad it's working for you. As a new user to Stack Overflow, note that you should "upvote" (triangle) any answers that you found helpful, and if any one answer has answered your question, you should "accept" it (checkmark). This gives reputation to you and also rewards those on the site donating free time to answer questions. – Phrogz Jan 31 '11 at 22:06
  • @Phrogz Stack Overflow won't let me upvote because I don't have 15 reputation points. – Art Z. Feb 01 '11 at 21:12
  • @ArtZ No worries; I'm not hurting for rep, that was just a general comment as you move forward on the site. :) – Phrogz Feb 01 '11 at 21:29
4

It turns out that

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

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

Art Z.
  • 153
  • 1
  • 7