Google Page Speed Insights often advises
to optimize images to reduce the page size, this is often easier said than done especially for sites
that allow user uploads such as Wordpress.
The following script will optimize images once per image.
#!/bin/bashPATH_TO_OPTIMIZE="/var/www/html"cd"$PATH_TO_OPTIMIZE"echo"Optimizing $PATH_TO_OPTIMIZE"# find jpeg images which have been modified since the last optimization
find.-path"./optimized"-prune-o-newer"$PATH_TO_OPTIMIZE/.opt"-name"*.png"-print>/tmp/optpng
# find png images which have been modified since the last optimization
find.-path"./optimized"-prune-o-newer"$PATH_TO_OPTIMIZE/.opt"-name"*.jpg"-print>/tmp/optjpeg
# update last optimization time, yes there is a race condition where a file could be uploaded# while files are being found, I'll fix this one day
touch"$PATH_TO_OPTIMIZE/.opt"# optimize pngstotal=$(wc-l/tmp/optpng)i=0whilereadf
do((i++))echo"$i of $total"file=$(basename$f)dir=$(dirname$f)mkdir-poptimized/$dir/usr/local/bin/pngquant-v--force--speed1--quality=50-100--outputoptimized/$dir/$file$foptipng-o7-clobber-outoptimized/$dir/$fileoptimized/$dir/$filedone</tmp/optpng
total=$(wc-l/tmp/optjpeg)i=0whilereadf
do((i++))echo"$i of $total"file=$(basename$f)dir=$(dirname$f)mkdir-poptimized/$dirconvert-verbose-strip-sampling-factor4:2:0-colorspaceRGB-interlaceLINE-quality80$foptimized/$dir/$filedone</tmp/optjpeg
rm/tmp/optjpeg
rm/tmp/optpng
You can set up a cron job like this to optimize images, note the flock is important to stop multiple runs at the same time
The above script doesn't overwrite the original files it stores them in a subfolder called optimized,
you can use some websever rewrite rule wizardry to show them instead of the originals. Nginx's try_files is an option.
On the intial optimization you'll want to run
touch-t[[CC]YY]MMDDhhmm$PATH_TO_OPTIMIZE/.opt
Where the date is older than the oldest file you want to optimize