When testing the performance of a website one of the most common recommendations is to optimise images.

When you have a large stash of images uploaded over years of blogging, downloading and optimising them all might not seem worth it, but the results are astounding.

To optimise a large amount of jpeg images via command line we can use a tool called jpegoptim.

To install jpegoptim v1.3.0 on Debian stable all previous installations of libjpeg must be removed. Don't worry though, it will be replaced very shortly.

$ sudo apt-get remove --purge libjpeg*

After everything is removed it's time to install libjpeg v9

wget http://www.ijg.org/files/jpegsrc.v9.tar.gz   

tar -zxvf jpegsrc.v9.tar.gz
cd jpeg-9/
sudo make install

Now download and install jpegoptim v1.3.0

wget https://github.com/tjko/jpegoptim/archive/RELEASE.1.3.0.zip

unzip RELEASE.1.3.0.zip
cd jpegoptim-RELEASE.1.3.0/
make strip
sudo make install

Check the version number using jpegoptim --version, you should see jpegoptim v1.3.0.

For single directories it is possible to use a simple for loop

for i in *.jpeg; do jpegoptim "$i"; done

But this is not ideal if you upload images into folders by year and/or month, similar to the WordPress structure.

-- uploads
  |-- 2010
  |   |-- 05
  |   |-- 06
  |   |-- 10
  |   `-- 12
  |-- 2011
  |   |-- 01
  |   |-- 06
  |   |-- 07

Travelling into all of the above directories would be tiresome, but not if we use our buddy find.

Find can recursively look through a folder to find all files or folders and execute commands on just those it found.

Finding all jpeg files is pretty simple.

find . -regextype sed -regex ".*/*.jp[e]\?g$"

Using the exec option it is possible to specify what to do with the files found.

First up is the dry run, it won't affect any files, only show how much optimisation could be done.

find . -regextype sed -regex ".*/*.jp[e]\?g$" \
    -exec jpegoptim --all-progressive -o -n -m90 --strip-all {} \;

Feel free to play around with the maximum image quality setting m[0-100], I like to keep mine at 90.

Once you are happy with the results, remove the dry run option -n to set it optimising your images.

find . -regextype sed -regex ".*/*.jp[e]\?g$" \
    -exec jpegoptim --all-progressive -o -m90 --strip-all {} \;

This has reduced my jpegs size by 7-25%, reduced load time by a second and increased my Page Speed Grade from 75% to 90%.

For a little under 10 minutes work, I'd say that's a success.