Sometimes, we want to display an image stored as byte array in HTML and JavaScript.
In this article, we’ll look at how to display an image stored as byte array in HTML and JavaScript.
How to display an image stored as byte array in HTML and JavaScript?
To display an image stored as byte array in HTML and JavaScript, we can convert the byte array to a base64 URL string.
For instance, we add an img element with
<img id="itemPreview" src="" />
Then we write
const blob = new Blob([uint8ArrayBuffer], { type: "image/jpeg" });
const imageUrl = URL.createObjectURL(blob);
document.getElementById("itemPreview").src = imageUrl;
to select the img element with getElementById
.
Then we set the src
property to the base64 URL with the byte array converted to a base64 string.
We get the base64 image URL from by creating the uint8ArrayBuffer
to a blob with the Blob
constructor.
Then we call URL.createObjectURL
to convert the blob
to a base64 string.
Conclusion
To display an image stored as byte array in HTML and JavaScript, we can convert the byte array to a base64 URL string.