Pngcrush a Directory Recursively

By default pngcrush (http://pmt.sourceforge.net/pngcrush/) only able to optimize single PNG file. The following script make it works with a folder recursively:

mkdir ~/bin
cat > ~/bin/pngcrush-recursive.sh <<-EOF
#!/bin/bash

set -o xtrace

UUID=/usr/bin/uuid
PNGCRUSH=/usr/bin/pngcrush
THREAD=\$[\`cat /proc/cpuinfo | grep processor | wc -l\`]

if [ ! -x \$UUID ] ; then
  echo "No uuid package installed"
  exit 0
fi

if [ ! -x \$PNGCRUSH ] ; then
  echo "No pngcrush package installed"
  exit 0
fi

recursive() {
  for PNG in \`find "\$1" -name "*.png"\`;
  do
    set +o xtrace
    while [ \`ps aux | grep "pngcrush -rem alla" | wc -l\` -gt \$THREAD ]; do
      sleep 0.1
    done;
    set -o xtrace

    TMP=/tmp/\`\$UUID\`.png
    echo "crushing \$TMP from \$PNG"
    \$PNGCRUSH -rem alla -brute -reduce "\$PNG" "\$TMP" > /dev/null 2>&1 && mv -f "\$TMP" "\$PNG" &
  done;
}

TARGET="\$1"
if [ -z "\$TARGET" ]; then
  TARGET="."
fi

until [ -z "\$TARGET" ];
do
  TARGET=\`cd "\$1"; pwd\`
  recursive "\$TARGET"
  shift;
  TARGET="\$1"
done;
EOF
chmod a+x ~/bin/pngcrush-recursive.sh

Now run this script with:

cd ~/public_html
~/bin/pngcrush-recursive.sh

Or even more simple:

pngcrush-recursive.sh ~/public_html

Add new comment