According to Roelofs, it’s a popular misconception that few browsers support PNG. In fact, Microsoft Internet Explorer, Netscape Communicator, and Opera have supported it since 1997.

Roelofs is right, however, full alpha transparency support didn’t exist in Internet Explorer until version 7. With this new support for transparency, the advantages of using PNG only become more and more obvious.

However, the plot thickens when you save a PNG file from Adobe Photoshop. Photoshop does a poor job of compressing PNG images properly.

CrushPNG to the rescue! CrushPNG is a lossless PNG optimiser that will reduce the size of your PNG images in a flash.

First you will need to install CrushPNG with Ports. Simply run:


sudo port install crushpng

Otherwise, download it from here.

Here is the basic syntax to optimise a PNG image:


crushpng before.png after.png

If you’re like me, you’ll have an images directory for your website. So typically I would want to make sure all my PNG images are optimised. You could manually optimise each file but that could be a little tedious and time consuming. So I’ve written up a command that will recursively go through your files looking for PNG images, optimise them and then finally save them.

The command looks like this:


find . -name "*.png" -exec pngcrush -brute -force -q {} temp.png \;  -exec rm {} \;  -exec mv temp.png {} \; -print

This is quite a long command and I’m hoping you’re not crazy enough to remember that. So we can set it as an alias instead. Do the following to setup this command as an alias:


cd ~
mate .profile # I use TextMate, you could use nano .profile here if you wanted to

Now add this line into your .profile file and save it.


alias crushpngs="find . -name \"*.png\" -exec pngcrush -brute -force -q {} temp.png \;  -exec rm {} \;  -exec mv temp.png {} \; -print" 

Reopen terminal and now you can just use the “crushpngs” command anywhere you like. The particular use I have for this is in my latest project MyLetterBox. Here is an example of the command running on a Ruby on Rails application:

~/Code/MyLetterBox/trunk/public/images$ crushpngs
./application/bottom-gradient.png
./application/myletterbox-logo.png
./application/top-gradient.png
./buttons/notify-me.png
~/Code/MyLetterBox/trunk/public/images$ 

At some point soon I will write up an article on how to add this to your Capistrano deploy.rb file. That way you can just deploy your application and it will automatically optimise all your PNG images for you.