Skip to content

Instantly share code, notes, and snippets.

@kyletaylored
Last active June 10, 2017 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyletaylored/ae272b21fcddf87d9cf7efa07a5fcd08 to your computer and use it in GitHub Desktop.
Save kyletaylored/ae272b21fcddf87d9cf7efa07a5fcd08 to your computer and use it in GitHub Desktop.
Script to run in a local directory to optimize all JPG and PNG images.
#!/bin/bash
# This script relies on jpegtran, a tool included with libjpeg.
# libjpeg comes bundled with ImageMagick on most nix platforms:
#
# Mac:
# brew install imagemagick
# brew install pngquant
#
# Ubuntu/Debian:
# sudo apt-get install gcc
# sudo apt-get install imagemagick
# sudo apt-get install libjpeg-progs
# sudo apt-get install pngquant
function optimize_images() {
# checks for the presence of jpegtran, which we use for image optimization
command -v jpegtran >/dev/null 2>&1 || { echo >&2 "I require jpegtran but it's not installed. Aborting."; exit 1; }
# checks to make sure the desired working directory exists
read -p "Local Files Root Directory (./files): " DIR
if [ ! -d $DIR ]; then
echo "$DIR is not a directory. Aborting"
exit 1
fi
# remember where we started off so we can return later
# cd into working directory
echo "Changing to $DIR"
CUR_DIR=$(pwd)
cd $DIR
# optimize jpgs
FILES=$(find . -iname '*.jpg' -o -iname '*.jpeg')
for F in $FILES; do
echo "Optimizing: $F"
jpegtran -copy none -progressive -outfile $F $F
done
# optimize pngs
FILES=$(find . -iname '*.png')
for F in $FILES; do
echo "Optimizing: $F"
pngquant --force --ext=.png --speed=8 --quality=65-85 $F
done
echo "Done"
# return back to where we came from
cd $CUR_DIR
}
optimize_images
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment