Optimizing Web Images with OptiPNG and JPEGoptim

The other day I was messing around trying to increase the response time and speed of my site, and I noticed that several of the web-based test sites were reporting that a lot of the images I was serving up could be better optimized. Well, okay, sure, but there are probably upwards of 300,000 images on this server–how to optimize them all and ensure any future images I add are also optimized.

Fortunately The Google supplied the answer in the form of two image optimization utilities, JPEGOptim and OptiPNG. As should be obvious from the name of each tool, each of these is designed to compress JPEG and PNG images respectively to an optimal size losslessly. It is possible to configure either tool to perform lossy compression, but I just wanted to take all of my images and make sure they were as compressed as possible losslessly.

Both tools are fairly straightforward. JPEGOptim filename.jpg will an image and recompress it to as small a size as possible while maintaining the same image quality. OptiPNG will do the same thing for PNGs. But how, then, to make sure everything is optimized?

In Linux, the solution is to wrap the jpegoptim command within the find command. So I navigate to my main high level web directory and run:

$ find -type f -name "*.jpg" -exec jpegoptim --verbose {} \;

That matches every .jpg file and runs the optimization process on the file, and it does so recursively through every directory beneath the directory it is run from. Six hours later, and I had optimized every JPEG on my server that was capable of being optimized.

Dealing with the PNG files was similar:

$ find -type f -name "*.png" -exec optipng -o7 {} \;

The -o7 option there tells OptiPNG to use the highest level of lossless compression possible. From my experience that level of optimization was extremely time consuming — it took 10 to 20 times as long to optimize each PNG as it did each JPEG.

Once I ran the initial process of optimizing both image types, I want to ensure that any new images I add also get optimized. So I created a couple Bash scripts to run both utilities on my web directories, and then set up a cron job to execute those scripts every Sunday at 12:01 a.m.

Leave a Reply