Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save varnav/d38f7f07dc1a549195c4b7b46926b78a to your computer and use it in GitHub Desktop.
Save varnav/d38f7f07dc1a549195c4b7b46926b78a to your computer and use it in GitHub Desktop.
Recursively optimize all PNG and JPG files
#!/bin/bash
# https://code.luasoftware.com/tutorials/linux/command-line-optimize-image/
find . -type f -iname '*.png' -exec pngquant --skip-if-larger --ext .png --force 256 {} \;
find . -type f -iname "*.png" | xargs optipng -o2 -strip all
find . -name '*.png' -print0 | xargs -0 -n1 -I{} sh -c 'zopflipng {} output.png; [ -f output.png ] && mv output.png {};'
# Using -print0 to deal with spaces
find . -print0 -type f -name "*.jpg" -o -name "*.JPG" | xargs -0 jpegoptim
# Make files bigger that 2 megabytes smaller than 2 megabytes
find . -type f -size +2M -name "*.jpg" -o -size +2M -name "*.JPG" -exec jpegoptim --size=2048 {} +
# Parallelization
find . -type f -iname "*.jp*g" -print0 | xargs -0 -n1 -P4 jpegoptim --max=85 --size=2048
# If you still have problem with spaces and file names
# ctrl-z to interrupt
# Strip all unecessary data, make image not bigger that 2 megabytes, image quality not bigger than 85, do nothing if optimization is less than 1%.
find . -iname "*.jp*g" -type f -size +2M -printf 'jpegoptim --strip-all --threshold=1 --max=85 --size=2048 "%p"\n' > run.sh
bash run.sh
# Guetzli for JPEG. Very slow, lossless, very efficient
guetzli_recursively --quality 85 .
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment