107

I'm writing a web page in HTML/JavaScript. I'm downloading an image from my backend using AJAX. The image is represented as raw byte array, not an URL, so I can't use the standard <img src="{url}"> approach.

How do I display the mentioned image to the user?

cubuspl42
  • 7,833
  • 4
  • 41
  • 65

1 Answers1

183

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

cubuspl42
  • 7,833
  • 4
  • 41
  • 65
Sridhar R
  • 20,190
  • 6
  • 38
  • 35
  • 2
    My Byte = dwr/download/k1a3JvBCfU3vLji$zKkhQObxzck. src = data:image/png;base64,dwr/download/k1a3JvBCfU3vLji$zKkhQObxzck. I used DWR –  Dec 24 '13 at 07:33
  • Byte Format image Download. – Diamond King Mar 29 '17 at 12:15
  • Hi i getting data like this format can you help how to convert it into image data:video/webm;base64 format. It is actually a live video streaming. – Hemant Nagarkoti Oct 10 '17 at 05:59
  • 7
    Late to the party but if your response looks like `[137,80,78,71,13,10,26,10,0,...]`, you can use this line: `document.getElementById("ItemPreview").src = "data:image/png;base64," + btoa(String.fromCharCode.apply(null, new Uint8Array([137,80,78,71,13,10,26,10,0,...])));` – Joel'-' Jul 31 '19 at 11:30
  • 2
    I edited the answer a bit to make it more clear, but I'm not getting one thing so I didn't really fix it. Why does this answer assume that the image is stored in a base64 string? The OP mentioned (and I checked the edit history) a "byte array", not "base64 string". – cubuspl42 Dec 17 '19 at 20:32
  • @ cubuspl42 It doesn't assume that image is stored in a base64 string. It is encoding the byte array into base64 encoded string so that can view it – Sonal May 19 '20 at 15:57
  • Joel, conversion from byte array to a string, the procedure `String.fromCharCode.apply` results in `RangeError: Maximum call stack size exceeded`, so in my case, that's not an option. – fartwhif Aug 23 '21 at 22:36
  • 1
    In @Joel'-' solution, "btoa is deprecated" warning is given. If someone encounters the same issue, try using `Buffer.from(array).toString('base64')` instead. – AyseAsude Aug 07 '22 at 16:58