Optimize images on Linux and Mac

Most website have many images. You might not be aware of it but it does. I mostly have text and code in my posts and thought I do not need to care too much about optimizing the images in there because there are rarely any. But the fact is that even though my posts mostly do not contain images, the theme I use as well as a few plugins do use images.

If you are using WordPress, you can easily optimize (and compress) images in your post using a plugin. I’ve used WP Smush.it and EWWW Image Optimizer. First I used WP Smuch.it but at some point in time it stopped working so I switched to EWWW Image Optimizer. But when WP Smush.it got fixed I switched back since I felt more confortable with it.

But these plugins only optimize images in the media library. Not images part of themes or plugins. Since most images on my site fall under this category, I had to find a solution. I didn’t find a plugin for this but two nice command line tools.

Why two ? Well because one of them takes care of PNG files and the other one takes care of JPEG files.

First, the PNG files. I optimize them using a command line tool call optipng. You can install it like this under Linux:

apt-get install optipng

(note that you might need to add a sudo before the apt-get)

On Mac, using Homebrew:

brew install optipng

To use the tool, you just need to provide a file to optimize:

optipng myfile.png

If you need to optimize all images in a given folder:

find . -iname "*.png" -exec optipng {} \;

If you want an even better optimization and can leave with a very long optimization duration, add the -o7 Option:

find . -iname "*.png" -exec optipng -o7 {} \;

Now, the JPEG files. For this I used a command line tool called jpegoptim.

Installation under Linux:

apt-get install jpegoptim

On Mac with Hombrew:

brew install jpegoptim

And just provide a file to optimize:

jpegoptim myfile.jpg

For a bulk optimization:

find . -iregex ".*\.jpe?g" -exec jpegoptim {} \;

This performs a lossless optimization (this means the pixels you’ll see are still the same but the file is smaller). Without loss of quality you can still get smaller file but if you can live with a lower image quality, you can achieve a better optimization:

find . -iregex ".*\.jpe?g" -exec jpegoptim --max=75 {} \;

This means you are ready to loose up to 25% quality in order to get smaller files.

Note that you can also optimize images online using Smush.it.

Also remember if you use WordPress that images in plugins and themes will be overwritten by every update of the plugin or theme. So run these two tools once in a while (at least after updating multiple plugins and themes).

Leave a Reply

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