PNGCRUSH a Directory of Images

One easy way of reducing website load time is by optimizing your images. PNG graphics are often more bloated than they need to be so using PNGCRUSH should be a no-brainer. PNGCRUSH's basic usage provides only single-file-crushage but I've created a script that crushes PNGs in directories recursively.

The Bash Script

#!/bin/sh
for png in `find $1 -name "*.png"`;
do
	echo "crushing $png"	
	pngcrush -brute "$png" temp.png
	mv -f temp.png $png
done;

Do whatever you can to compress your images so that your website will load as quickly as possible. PNGCRUSHing your images does not cause a loss of quality -- only a loss of excess file size! PNGCRUSHing my images saved over 120KB of bloated imagery for the recent redesign.


Comments

  1. Dimitar Christoff

    heh, this post is so engrish: “so that your website load as quickly” and “does not cause a lose of quality”. mootools crew must be whipping you hard then :)

    pngcrush… was this something you found on your mac thingie? most inconsiderate of “normal” windows users :D

  2. David Walsh

    Holy crap. In my defense this was a really late night post. Weak. My bad.

  3. Robbo

    Totally untested, but for windows users, as long as everything is in the one spot….

    Create a batch file called “crush.bat”
    Put the following code in it.

    @echo off
    for /f “tokens=*” %%x in (‘dir /b *.png’) do (
    echo “crushing %%x”
    pngcrush -brute “%%x” temp.png
    move /Y temp.png “%%x”
    )

    Then run it.

  4. Ben

    Is there a way to do this with PHP? Or something a bit more practical?

  5. David Walsh

    @Ben: What’s impractical about this?

  6. Ben

    @David Walsh: I don’t know how to run bash scripts :)

  7. David Walsh

    Oh — in that case, try this:

    http://pornel.net/imageoptim/en

  8. deef

    Extended:

    scriptname [-d directoryname]

    [code]
    #!/bin/sh
    #
    dflag=
    while getopts 'd:' OPTION
    do
    case $OPTION in
    d) dflag=$OPTARG
    ;;
    ?) printf "Usage: %s: [-d directory]\n" $(basename $0) >&2
    exit 2
    ;;
    esac
    done
    shift $(($OPTIND - 1))

    if [ "$dflag" ]
    then
    # DO DIR PNGCRUSH
    for png in `find $dflag -name "*.png"`;
    do
    echo "crushing $png"
    pngcrush -brute "$png" temp.png
    mv -f temp.png $png
    done;
    fi
    [/code]

  9. rick

    It’s even easier than that, pngcrush supports * for selecting images to crush. Try: ‘pngcrush -d “/Users/rd/crushedimages/” *.png’ to crush ALL png images in the current directory and put the resulting files in “/Users/rd/crushedimages/” (change this to a directory of your choosing!

  10. jon wilson

    i think this was a great post. it has helped me much. thank you

  11. Daniel X. Moore

    Very useful script!


Be Heard!

Share your thoughts without being a jerk! And wrap your code in <code> tags, f00!

Name*:
Email*:
Website: