Skip to content

Instantly share code, notes, and snippets.

@danielantelo
Last active May 12, 2021 11:17
Show Gist options
  • Select an option

  • Save danielantelo/52f928d70d4d7da6f53b317780e4afc3 to your computer and use it in GitHub Desktop.

Select an option

Save danielantelo/52f928d70d4d7da6f53b317780e4afc3 to your computer and use it in GitHub Desktop.
Optimise images in a folder for web
#!/bin/bash
commandExists () {
type "$1" &> /dev/null ;
}
installJpegOptim() {
if commandExists brew; then
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" < /dev/null 2> /dev/null
brew install jpegoptim
else
apt-get install jpegoptim
fi
}
installOptiPng() {
if commandExists brew; then
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" < /dev/null 2> /dev/null
brew install optipng
else
apt-get install optipng
fi
}
resizeImages() {
if commandExists sips; then
# change your desired max height here for the different image types
find . -type f -name '*.png' -exec sips -Z 640 {} \;
find . -type f -name '*.jpg' -exec sips -Z 640 {} \;
find . -type f -name '*.jpeg' -exec sips -Z 640 {} \;
fi
# @TODO use something else when sips is not available
}
optimizePng() {
# change -o4 to the desired levels of optimisation, the higher the number the slower it will go
find . -name "*.png" -exec optipng -o4 -strip all {} \;
}
optimizeJpg() {
# change -m65 to the desired quality level
find . -name "*.jpg" -exec jpegoptim -m65 -o -p --strip-all {} \;
find . -name "*.jpeg" -exec jpegoptim -m65 -o -p --strip-all {} \;
}
if ! commandExists jpegoptim; then
installJpegOptim
fi
if ! commandExists optipng; then
installOptiPng
fi
resizeImages
optimizePng & optimizeJpg
@jrswgtr
Copy link

jrswgtr commented May 12, 2021

The resizing appears not to be working (anymore?)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment