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:

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:

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:

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).


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s