How to batch optimize all jpgs using a bash script to speed up your site

Based on Google Insights article here:

JPEG is a lossy format. The compression process removes visual details of the image, but the compression ratio can be 10x larger than GIF or PNG.

  • Reduce quality to 85 if it was higher. With quality larger than 85, the image becomes larger quickly, while the visual improvement is little.
  • Reduce Chroma sampling to 4:2:0, because human visual system is less sensitive to colors as compared to luminance.
  • Use progressive format for images over 10k bytes. Progressive JPEG usually has higher compression ratio than baseline JPEG for large image, and has the benefits of progressively rendering.
  • Use grayscale color space if the image is black and white.


The following code will recursively optimize every .jpg file in your working directory.


Code from below.

Using a ‘for’ loop will definitely work – and is a good general technique – but you almost certainly have more than 1 processor on your machine, so why do just one conversion at a time?

You can get things moving a lot quicker if you do:

The arguments to xargs are:

And then the convert command is given afterwards.

shareimprove this answer

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.