118

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?

4
  • 1
    possible duplicate of Displaying byte array as image using JavaScript Commented Dec 24, 2013 at 6:34
  • OutputStream o = resp.getOutputStream(); o.write(imageInBytes); Commented Dec 24, 2013 at 6:37
  • 1
    I'm afraid to ask, but curiosity wins... Why is this off-topic? Commented Dec 17, 2019 at 20:16
  • I don't think this issue is off-topic. Commented Apr 6, 2020 at 23:48

1 Answer 1

197

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:

Sign up to request clarification or add additional context in comments.

9 Comments

My Byte = dwr/download/k1a3JvBCfU3vLji$zKkhQObxzck. src = data:image/png;base64,dwr/download/k1a3JvBCfU3vLji$zKkhQObxzck. I used DWR
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,...])));
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".
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.
In @Joel'-' solution, "btoa is deprecated" warning is given. If someone encounters the same issue, try using Buffer.from(array).toString('base64') instead.
|