Skip to content

Instantly share code, notes, and snippets.

@joshcarr
Last active December 16, 2015 15:29
Show Gist options
  • Save joshcarr/5456666 to your computer and use it in GitHub Desktop.
Save joshcarr/5456666 to your computer and use it in GitHub Desktop.
Runs a directory of PNGs through a quantizer and optimizers and outputs to a compressed directory.
#!/bin/sh
# adapted from: https://github.com/bingalls/webGraphicsMagick/blob/master/compressLossy.sh
COMPRESS_DIR='./compressed' #Creates compressed copies in $COMPRESS_DIR.
#Create dest dir for compressed copies of images
if [ ! -d $COMPRESS_DIR ];then
mkdir $COMPRESS_DIR
else
#read -t15 is bash for timeout of 15 seconds
read -p "$COMPRESS_DIR/ already exists. 'y' to overwrite existing files: " proceed
if [ "y" != $proceed ];then
echo "Exiting, to preserve existing contents in ./$COMPRESS_DIR/"
exit 1;
fi
fi
if [ `find . -maxdepth 1 -name "*.png" | head -1` ]; then #*.png exists
mkdir $COMPRESS_DIR/tmp
for i in *.png;do
cp $i $COMPRESS_DIR/tmp/quant.png
echo "quantizing $i"
pngquant 32 -f --ext .png $COMPRESS_DIR/tmp/quant.png
echo "compressing with optipng"
optipng -quiet -o2 $COMPRESS_DIR/tmp/quant.png $COMPRESS_DIR/tmp/optipng.png
echo "compressing with pngcrush"
pngcrush -q -l9 -m0 $COMPRESS_DIR/tmp/quant.png $COMPRESS_DIR/tmp/crush.png
echo "comparing compressions"
file=`basename $i`
smallest=`ls -1S $COMPRESS_DIR/tmp/*|tail -1`
if [ `du $smallest|cut -f1` -lt `du $i|cut -f1` ];then
mv -f $smallest "$COMPRESS_DIR/$file"
fi
#Insert a read here, to pause, and compare *magick to pngcrush, for benchmarking.
rm $COMPRESS_DIR/tmp/*
done
rmdir $COMPRESS_DIR/tmp
fi #*.png exists
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment