Interlaced PNG’s

By evan on Jan 12, 2014

images (1)Browsing the internet the other day, I came across the “Interlaced PNG” format. This was apparently designed about 15 years ago when internet connections were much slower. As connection speeds get faster, there’s been a trend to stop caring about page size, and put as many gigantic images as humanly possible on a website.

From a technical standpoint that’s ridiculous, but from a design standpoint big images are “in.” Thus the return of interlaced PNG.

The way these work, is rather than downloading the file sequentially, the png is saved according to the “Adam7” format, where progressively more detail is downloaded. Rather than displaying the image in a single pass, a low resolution version shows very quickly, followed by progressively higher resolution images. This does add to the total size of the image by about 20%, but the time it takes to show the image drops up to 90%.

On that picture (from LibPNG) you can see the order, assuming each marble is a pixel. It downloads the big orange ones first, then blue, then green, then yellow, red and finally the clear ones. The browser interpolates at each step, producing an image that progressively gets better much like these flowers. The one on the left is being rendered in one pass, the one on the right is interpolated.7.17

I was recently working on a website that has about 6 full screen images on one page. Needless to say, that’s pretty big. Rather than leave the background blank until the images are downloaded, Interlaced PNG lets me show something almost instantly.

Since it’s a relatively uncommon format, and I want the end-user to be able to replace those images, I created a quick and dirty script to convert any image to an interlaced PNG on the fly. It takes a fraction of a second to make the conversion on the server, and when cached it’s comparable to the source image. This version of the script does not include input checking or caching (can’t give it all away)

It’s simply called as http://example.com/interlacer.php&url=image.jpg, and returns as an interlaced png. It requires the GD Library which should be included by default by most hosting providers.

<?php
// open the file in a binary mode
$url = $_GET['url'];

// getimagesize returns height, width, and image type. We'll use the image type in the next section
$image = getimagesize ( $url );
$type = $image[2];

// create our image
if($type == IMAGETYPE_JPEG ) $im = imagecreatefromjpeg($url);
else if($type == IMAGETYPE_GIF) $im = imagecreatefromgif($url);
else if($type == IMAGETYPE_PNG) $im = imagecreatefrompng($url);

// Enable interlancing
imageinterlace($im, true);

// Send the right headers
header("Content-Type: image/png");

// Send the image data
imagepng($im);

imagedestroy($im);
exit;
?>

Leave a Reply

Your email address will not be published. Required fields are marked *