As long as you don't mind breaking compatibility with older browsers and have no need for animation, the Portable Network Graphic (PNG) has replaced the Graphics Interchange Format (GIF) as the preferred transparency-supporting lossless image format of the internet. Over the next few weeks, we're going to explore the different ways you can optimise the size of PNGs while compromising little on quality.
The first trick we're going to learn is using posterisation to reduce the colour complexity of an image. This process works best on images with few colours and as long as you don't go overboard, the visual differences are virtually unnoticeable. if you look at the left-hand side of the photo above, you can see an extreme case of posterisation. Similar colours become blobs of the same colour and a lot of detail is lost.
So let's not go that far. Fire up either Photoshop, GIMP or your photo editor of choice. Load up your image and in PS, go to Image -> Adjustments -> Posterize..., while in GIMP you need to navigate to Tools -> Color Tools -> Posterize or Colors -> Posterize. Both programs will show a dialog box where you can adjust the number of levels of posterisation.
A good starting point is between 30-45, though you should go higher if you notice a huge drop in colour depth and lower if you think you can get away with it. Once you're happy with the appearance, save the image as a PNG. The compression ratios will vary depending on the size and complexity of the image, but a 640 x 360 shot of the flower here went from 363.1KB to 213.3KB, using Photoshop CS5 and a Posterize setting of 30. That's a 41.3 per cent drop in file size; for web development, the bandwidth benefits massively outweigh the tiny drop in quality.
On the left is the original image, the posterised one on the right (click to expand).
The reason posterisation helps with PNG compression is because the PNG format uses the Deflate algorithm to reduce the size of the image data. Like many general-purpose compression algorithms, Deflate transforms consecutive sequences of repeating data into shorter codes. So, if you replace a bunch of very similar, but not identical pixels with identical ones, that image data is naturally going to compress better.
While the compression gains from posterisation can be significant, it is not a magic bullet. You are discarding colour information, so you'll want to keep an unaltered version of the image around just in case. Posterisation — at least in Photoshop — has a tendency to make images darker, so keep this in mind when performing colour correction.
Next, we'll take a look at a number of programs that can optimise PNGs further and put together a script to automate the process of funnelling images through these apps.