Draw binary image to the HTML5 canvas

Recently I tried to draw some binary image data to the canvas. The image data was in a Uint8Array but it was already compressed, so no raw RGB.

You see the canvas context has some convenience functions working with binary data, like putImageData. Normally you would use it like this:

function drawBinary(binaryImage){
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var imageData = context.createImageData(width, height);
context.putImageData(binaryImage);
}
view raw gistfile1.js hosted with ❤ by GitHub

Be warned though that putImageData only works with RGB values, not an already compressed image, like a JPEG or PNG file data.

There are two courses of action here:

  1. Uncompress the image array
  2. Convert the array to a data URL

I’d go with the second option. There are two ways to do this as well. First you could manually encode the image data to base64 and append the proper data URL prefix for it, like this:

function binaryToDataURL(inputArray){
var base64 = btoa(String.fromCharCode.apply(null, inputArray));
var uri = 'data:image/jpeg;base64,' + base64;
return uri;
}
function drawToCanvas(binaryArray){
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var img = new Image();
img.onload = function(){
context.drawImage(img);
};
img.onerror = function(e){
console.log('Error during loading image:', e);
};
img.src = binaryToDataURL(binaryArray);
}
view raw gistfile1.js hosted with ❤ by GitHub

Alternatively you could use a blob and the createObjectURL function. Sadly these are experimental stuff and I haven’t been able to make it work yet. However the code is a bit cleaner and should be more efficient. It should look like this:

function binaryToDataURL(inputArray){
var blob = new Blob(inputArray, {'type' : 'image/jpeg'});
return URL.createObjectURL(blob);
}
view raw gistfile1.txt hosted with ❤ by GitHub

I really hope that there will be support for this later on. Of course you can always just point your image’s src to your image somewhere on your server. However there are cases where this approach is not viable (such as mine was).