Using Javascript, I\'m making an AJAX call to a WCF service, and it is returning a byte array. How can I convert that to an image and display it on the web page?
Converting the byte array to base64 when you have the binary byte array is ridiculously expensive, and more importantly; it's totally unnecessary work, as 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, from the byte array, and you can use the resulting short string 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;
};
xhr.send();
<h1>Demo of displaying an ArrayBuffer</h1>
<p><a href="http://jsfiddle.net/Jan_Miksovsky/yy7Zs/">Originally made by Jan Miksovsky</p>
<img id="photo"/>
Late to the party but if your response looks like
[137,80,78,71,13,10,26,10,0,...]
you can use this:
<img id="image" src="" />
var imgsrc = "data:image/png;base64," + btoa(String.fromCharCode.apply(null, new Uint8Array([137,80,78,71,13,10,26,10,0,...])));
document.getElementById('image').src = imgsrc;