Skip to content

Instantly share code, notes, and snippets.

@borgar
Created May 18, 2010 11:53
Show Gist options
  • Save borgar/404909 to your computer and use it in GitHub Desktop.
Save borgar/404909 to your computer and use it in GitHub Desktop.
A bash script to run PNGs through both pngcrush and opticrush using unreasonably zealous settings.
#!/bin/bash
# This script attacks either all file arguments given to it, or all png's in a subtree (if
# a directory or no argument is given), and runs both pngcrush and optipng on them with liberal settings.
CRUSH=$(which pngcrush)
OPTI=$(which optipng)
OPTS1='-rem cHRM -rem gAMA -rem iCCP -rem sRGB -q'
OPTS2='-quiet -fix -o4'
TEMP="/tmp/temp.png"
BEFORE=0
AFTER=0
MAXDIFF=0
FILES=("$@")
# if argument is a directory, then run on all pngs in it's subtree
# if no argument is supplied then run in current working directory
if [[ $# -lt 2 ]] && [ -d $FILES ]; then
if [[ $# -eq 0 ]]; then FILES='.'; fi
OLDIFS=$IFS
IFS=$'\n'
FILES=($(find -x $FILES -iname '*.png' -type f))
IFS=$OLDIFS
fi
# find the sum of all file sizes
LEN=${#FILES[@]}
for (( i=0; i<${LEN}; i++ )); do
FILESIZE=$(stat -f%z "${FILES[$i]}")
BEFORE=$(( $BEFORE + $FILESIZE ))
done
# crush all files
for (( i=0; i<${LEN}; i++ )); do
FILEBEFORE=$(stat -f%z "${FILES[$i]}")
# crush
$CRUSH $OPTS1 -- "${FILES[$i]}" $TEMP
$OPTI $OPTS2 -- $TEMP
# stats
FILESIZE=$(stat -f%z "$TEMP")
DIFF=$(( $FILEBEFORE - $FILESIZE ))
AFTER=$(( $AFTER + $FILESIZE ))
# replace if $DIFF is > 0
if [[ $DIFF -gt 0 ]]; then
cp $TEMP "${FILES[$i]}"
fi
echo "> ${FILES[$i]}"
echo "> before:" ${FILEBEFORE} "- after:" ${FILESIZE} "= saved:" ${DIFF} "bytes"
done
rm -f $TEMP
echo '--------------------------'
echo 'total size before:' ${BEFORE}
echo 'total size after:' ${AFTER}
echo 'reduction:' $( echo "scale=4; (($BEFORE - $AFTER) / $BEFORE) * 100" | bc ) "%"
echo '--------------------------'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment