Bulk/nightly image optimization

Categories: Linux, Bash

You need to install Imagemagick, JPEGOptim, OptiPNG and GIFSicle on the server first.

Then set these on a cron.

Resize all images to full HD using Mogrify (bundled with Imagemagick):

find /directory/wp-content/uploads -iregex '.*\.\(jpg|JPG|jpeg|JPG)' -type f -exec mogrify -verbose -resize '1920x1080>' {} \; && chown -R user:group /directory/wp-content/uploads;

Optimize all JPEG files with 90% lossless quality:

find /directory/wp-content/uploads -iregex '.*\.\(jpg|JPG|jpeg|JPG)' -type f -exec jpegoptim --max=90 --strip-all --preserve --totals {} \;

Optimize all PNG files using OptiPNG and keeping their quality:

find /directory/wp-content/uploads -iregex '.*\.\(png|PNG)' -type f -exec optipng -o5 -quiet -keep -preserve {} \;

Optimize all GIF files using GIFSicle:

find /directory/wp-content/uploads -iregex '.*\.\(gif|GIF)' -type f -exec gifsicle -o3 {} \;