divify

Here I present divify, a JavaScript tool for pixelating an image into a grid of divs. It works by converting the image into a div containing a sequence of child pixel divs, each left-floated and with its background color set to the average color from that area of the original image. The width of the parent div is then set to the width of the original image, making them all line up correctly. Why exactly would we want to do this? I'm not not entirely sure. If you can think of any vaguely useful application, I'm all ears.

So without further ado, here is an image loaded onto a canvas:

And here is a pixelated version using divify:

divify makes use of the canvas, which, once loaded with an image, can be used to extract the RGBA values for each pixel like so:

  • var canvas = document.createElement('canvas');
  • var img = new Image();
  • img.src = url;
  • img.onload = function() {
  • var context = canvas.getContext('2d');
  • var imageData = context.getImageData(0, 0, this.width, this.height);
  • var pixels = imageData.data;
  • for (var i = 0, n = pixels.length; i < n; i += 4) {
  • var r = pixels[i  ]; // red
  • var g = pixels[i+1]; // green
  • var b = pixels[i+2]; // blue
  • var a = pixels[i+3]; // alpha
  • }
  • }

Note that we have to do everything with the image data in its onload callback otherwise the image won't have finished loading.

In the previous image the 'pixels' were 5 pixels wide. divify lets you specify the pixel width, so we can increase the pixelation factor:

Pixels of size 10 pixels.

Now we can apply arbitrary CSS styles to the pixel divs:

border-radius

margin

border

margin and border

border-radius, margin *and* box-shadow. Oh my.

One interesting thing is that changing the float value from 'left' to 'right' has the effect of flipping the image horizontally. And yes, you can set the pixel length to one. This of course results in a rather large number of divs which need rendering, so if your browser does not choke on this, you'll wind up with a remarkably faithful reproduction of the image.

The code is up on GitHub, and you can try it out below with your own image. Note that if necessary the image will be cropped so the height and width are multiples of the pixel size.

  • Width:
  • Height:
  • Pixel size: