Skip to content

Instantly share code, notes, and snippets.

@skylarmt
Created May 8, 2018 18:27
Show Gist options
  • Select an option

  • Save skylarmt/c215b0e561fed35ee66ec1ccaabb8f45 to your computer and use it in GitHub Desktop.

Select an option

Save skylarmt/c215b0e561fed35ee66ec1ccaabb8f45 to your computer and use it in GitHub Desktop.
A script to optimize (pngcrush) all the images in a folder, and tell you how much space you've saved.
#!/bin/bash
TOTALIN=0
TOTALSAVED=0
TOTALFILES=0
for png in *.png;
do
echo "Crushing $png"
echo "PNG file $png:" >> /tmp/pngcrush.log
OLDSIZE=$(stat --printf="%s" "$png")
echo " Old size: $OLDSIZE" >> /tmp/pngcrush.log
pngcrush -q -brute "$png" temp.png
mv -f temp.png "$png"
NEWSIZE=$(stat --printf="%s" "$png")
PERCENT=$(echo "scale=4; (($OLDSIZE - $NEWSIZE) / $OLDSIZE) * 100" | bc)
PERCENT=$(echo "scale=2; $PERCENT / 1" | bc)
echo " New size: $NEWSIZE" >> /tmp/pngcrush.log
echo " Savings: $PERCENT%" >> /tmp/pngcrush.log
let "TOTALIN = $TOTALIN + $OLDSIZE"
TOTALSAVED=$(echo "$TOTALSAVED + ($OLDSIZE - $NEWSIZE)" | bc)
let TOTALFILES++
done;
let "TOTALOUT = $TOTALIN - $TOTALSAVED"
TOTALPERCENT=$(echo "scale=4; (($TOTALIN - $TOTALOUT) / $TOTALIN) * 100" | bc)
TOTALPERCENT=$(echo "scale=2; $TOTALPERCENT / 1" | bc)
echo
echo
echo "Crush Report:"
cat /tmp/pngcrush.log
echo ""
echo "========================"
echo "Total PNG count: $TOTALFILES"
echo "Total bytes in: $TOTALIN"
echo "Total bytes out: $TOTALOUT"
echo "Total bytes saved: $TOTALSAVED"
echo "Total percentage: $TOTALPERCENT%"
rm /tmp/pngcrush.log
@skylarmt
Copy link
Author

skylarmt commented May 8, 2018

Needs pngcrush and bc installed.

Haven't tested on Mac. r/linuxmasterrace

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