Since we moved in to our lovely new offices at Diespeker Wharf at the end of last year I’ve been taking advantage of our roof terrace - sadly I’m a smoker. Whilst blackening my lungs I started taking photographs (using Instagram) of view down the canal, for no particular reason other than the view being splendid (and a smattering of boredom!).
I’ve been wondering what to do with these images for a while, with a Pummelvision the obvious thing. Then along came NSKYC. It’s a lovely little project involving a webcam trained on the New York skyline. A photo is taken every five minutes and published with the average colour of the skyline calculated to present the images in a nice mosaic of tiles. The calculation is done server-side in php.
This seemed like the perfect type of thing to do with my photos. However, rather than process everything in the back-end I thought I’d have a play with the (not so) new html 5
canvas api to retrieve the colour information of each image. I was surprised at how easy it was!
Simply by using the
getImageData() method you have information about every pixel in the image. Getting the average colour is accordingly simple. Here’s the function that I used:
There are a few drawbacks of the
drawImage() method, primarily that it only works with images on the same domain as the code itself - this is a security measure.
Information leakage can occur if scripts from one origin can access information (e.g. read pixels) from images from another origin (one that isn’t the same).
To mitigate this, canvas elements are defined to have a flag indicating whether they are origin-clean. All canvas elements must start with their origin-clean set to true. The flag must be set to false if any of the following actions occur:
The element’s 2D context’s
drawImage() method is called with an HTMLImageElement or an HTMLVideoElement whose origin is not the same as that of the Document object that owns the canvas element.
toDataURL() method of a canvas element whose origin-clean flag is set to false is called, the method must raise a SECURITY_ERR exception.
Whenever the getImageData() method of the 2D context of a canvas element whose origin-clean flag is set to false is called with otherwise correct arguments, the method must raise a SECURITY_ERR exception.
The other obvious drawback is that
canvas methods in Internet Explorer, though I’ve not investigated wether it supports the