Displaying a byte array as an image using JavaScript

I am trying to display an image (byte array) using purely JavaScript.

How can I achieve this in ASP.NET?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If you have the byte array, you first convert it to Base64String and then you place it on an img tag like that (for a PNG image):

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">

Similar Stack Overflow questions:

Method 2

EDIT: I just realized the question is a bit ambigious, so the answer below might not fit. If the byte array is something you have in the .NET CLR side of things, then base64 is probably the way to go, but if it’s something you create or deal with in the client, my answer below is the way to go.

Converting the byte array to base64 when you have the binary byte array is ridiculously expensive, and more importantly; you don’t have to do convert it at all in modern browsers! The static URL.createObjectURL method creates a DOMString, a short browser-specific url, you can use in img.src or similar.

This is infinitely faster than solutions that require chaining TextEncoder and btoa when all you need is to display an image received in a byte array form.

var blob = new Blob( [ uint8ArrayBuffer ], { type: "image/jpeg" } );
var imageUrl = URL.createObjectURL( blob );

This is using HTML5 APIs, and so will not work on Node or other JS based servers, of course.

// Simulate a call to Dropbox or other service that can
// return an image as an ArrayBuffer.
var xhr = new XMLHttpRequest();

// Use PlaceKitten as a sample image to avoid complicating
// this example with cross-domain issues.
xhr.open( "GET", "https://placekitten.com/200/140", true );

// Ask for the result as an ArrayBuffer.
xhr.responseType = "arraybuffer";

xhr.onload = function( e ) {
    // Obtain a blob: URL for the image data.
    var arrayBufferView = new Uint8Array( this.response );
    var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );
    var urlCreator = window.URL || window.webkitURL;
    var imageUrl = urlCreator.createObjectURL( blob );
    var img = document.querySelector( "#photo" );
    img.src = imageUrl;

<h1>Demo of displaying an ArrayBuffer</h1>
<p><a href="http://jsfiddle.net/Jan_Miksovsky/yy7Zs/" rel="nofollow noreferrer noopener">Originally made by Jan Miksovsky</p>
<img id="photo"/>

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x