How to display an image stored as byte array in HTML/JavaScript?
JavascriptHtmlJavascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
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:
-
https://stackoverflow.com/questions/9463981/displaying-byte-array-as-image-using-javascript
-
https://stackoverflow.com/questions/3431095/how-to-display-an-image-stored-in-bytes-on-a-page
-
https://stackoverflow.com/questions/7390983/convert-from-binarydata-to-image-control-in-asp-net
-
https://stackoverflow.com/questions/4564119/javascript-convert-byte-to-image