How to display an image stored as byte array in HTML/JavaScript?

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?


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:

  • Displaying a byte array as an image using JavaScript

  • Display bytes as images on an .aspx page

  • 'data:image/jpg;base64' and jQuery image preview in Internet Explorer

  • Convert from binary data to an image control in ASP.NET

  • How to convert a byte array into an image?