We've all been there, the client is uploading images that are unnecessarily big or haven't been compressed - you run the website through a tool such as Google Page Speed to be told your images are too heavy and could be compressed. Well, there's an easy solution to this problem.

Step forward jpegoptim and optipng. Both of these tools are server-side, meaning no need to pull down GBs of images to compress just to re-upload to the server.

I highly recommend you back-up the original folder before processing bulk loads of images in a compression tool.

Installation

Debian based OS:

$ apt-get install jpegoptim
OR
$ sudo apt-get install jpegoptim
$ apt-get install optipng
OR
$ sudo apt-get install optipng

Redhat based OS:

First off, you need to install and enable the EPEL repository:

$ yum install epel-release
$ dnf install epel-release # On Fedora 22+ versions

Now you can install the packages as below:

$ yum install jpegoptim
$ dnf install jpegoptim # On Fedora 22+ versions
$ yum install optipng
$ dnf install optipng # On Fedora 22+ versions

Usage

There are multiple ways you can use jpegoptim or optipng, below are some examples:

Single image:

$ jpegoptim IMAGE.JPG
$ optipng IMAGE.PNG

Directory full of images:

$ jpegoptim *.JPG
$ optipng *.PNG

Directories, with sub-directories:

This one is particularly handy for things such as WordPress upload directories.

$ find ./ -type f -iname '*.jpg' -exec jpegoptim --strip-all {} +
$ find ./ -type f -iname '*.png' -exec optipng {} +

And that's it. Hopefully this will help you on the path to a better Google Page Speed score, however don't lose sleep over it.