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.

find . -iname "*.jpg" | xargs -n1 -P8 -I{} convert -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace sRGB "{}" "{}"


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:

find *.jpg | xargs -n1 -P8 -I{} convert -resize 20% "{}" "opt-{}"

The arguments to xargs are:

n1  - Only give 'convert' one file at a time
P8  - Use 8 processes
I{} - Replace {} with the filename given by 'find'

And then the convert command is given afterwards.

shareimprove this answer

Leave a Reply

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

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