Image optimization for web pages with script

If you want your page to load fast and you want to get some nice score on pagespeed or lighthouse or in general.. you must optimize the size of your images.

I found simple script that I actually optimized even more in order to automate this tedious task for me, might as well share it here, if anybody is interested :)

However, in order to use it, first install following packages

sudo apt-get install optipng advancecomp pngcrush jpegoptim

Then simply use this script in your web source directory, you might configure multiple directories as an exception, in my case since I use Hugo, it’s like themes and _resources directories where I do not want to optimize images.

# Script adapted by pduchnovsky

# Add list of folder names to ignore array here, separated by space
ignore=("./themes/*" "./resources/*" "./assets/*")

# Array of png optimizers with their arguments
    "optipng -nb -nc"
    "advpng -z4"
    "pngcrush -rem gAMA -rem alla -rem cHRM -rem iCCP -rem sRGB -rem time -ow"

# File to check/create in order to stop processing already processed files since last run.

# Only use -newer option if file already exists
if [ -f "$file" ]; then
    option="-newer $file"

# Prepare arguments from ignore list
for ignored in "${ignore[@]}"; do
  ignorearg+="-not -path "*${ignored}" "

# Optimize png images with optimizers and their settings
for optimizer in "${optimizers[@]}"
    find . -type f $option -iname "*.png" $ignorearg -exec $optimizer  {} \;

# Optimize using jpegoptim
find . -type f $option -iregex .*\.jpe?g$ $ignorearg\
-exec jpegoptim -m85 --all-progressive -f --strip-all {} \;

# touch file so it updates last run-time
touch $file