Bulk compress images with commandline tools

tl;dr Bulk compress images with Trimage and TinyPNG to speed up page requests.

Images usually have the largest share of the total size of webpages. Compressing them will lead to a significantly lower document size and therefore speed up the rendering of a website and saving the client's bandwith.

Most CMS offer some plugins to optimize images automatically after uploading them on the server.

But which tools are handy to run a compression on a folder just once, eg. to optimise existing images in a bulk action?

The good news: There are a lot of tools out there, which do the job.

The bad news: Lots of them are outdated or compress one image type only.

The most convenient tool in my opinion is Trimage.

Trimage screenshot

This tool may be used with a GUI or commandline. It runs several image compression scripts such as OptiPNG or Jpegoptim at once.

Just run trimage -d <path to image folder> or drag and drop images to the GUI and the script will compress all given images.

Unfortunately the tool is abondoned, the last commit is of early 2013. Since this tool just acts as a wrapper for the actual compression scripts, you only need to update these scripts.

Trimage performs a losslessly image compression, which means that the images stay the same and don't have any quality loss. But it is also possible to perfom lossy image compression, which reduces the image quality, for example by reducing contrast and color depth. This is irreversibly tough. It may be advantageous to make a copy of the original.

Some tools with lossy compression reduces file sizes significantly, up to 70%, before any quality loss is noticed by the client.

One such tool is pngquant. Another nice service is TinyPNG, which offers a website and an API. The service may work with JPG and PNG, the images have no visual quality loss but sometimes a lot smaller file size.

I have written a simple PHP script, to grab all images in a directory, send them to the TinyPNG API and save the outcome.

git clone https://github.com/webit-de/compress-images/
php compress-images.php [input directory] [output directory] [API key]

Update: JPEGrescan seems to do a better job than Jpegoptim. To bulk compress all JPEGs in folder just run the follwing command.

find . -type f -name "*.jpg" -exec jpegrescan {} {} \;

⌛ Warning! This post is old. The information may be outdated.

No comments on this notepad. If you would like to add something, then dont hesitate to contact me via E-Mail or Twitter.