Two weeks ago I wrote an article - Hijacking HTML canvas and PNG images to store arbitrary text data
to a Uint8Array
and then storing bytes using three channels (RGB) within an ImageData
object before drawing this image to a Canvas
and saving as a PNG file. So lets see what's involved in doing the reverse of this process and getting back the original data...
At the end of the last article we had an image that looked something like this...
This image stores a serialised JSON object that has 3700 indexed properties each holding a String
value 'The quick brown fox jumps over the lazy dog'
Loading the Image
The image is loaded by creating an Image
object and setting its src
attribute to the PNG image from the previous article. In a real use case the src
attribute can be set or a URL or even a data URL
. This example keeps it very simple and references a file.
callback will be where all of the decoding code goes, for now this is an empty function which will be filled out in the following sections.
Drawing Image to Canvas
Once the image is loaded we need to access its pixel data which means it has to be drawn on an off-screen canvas
first. A canvas
with the same dimensions as the image (assuming everything is square) is created and the image is then drawn to the 2D context.