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:
- Uncompress the image array
- 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).