Crushing Every PNG in a Folder Hierarchy with a Batch File

While writing a batch file to remove stray Thumb.db files from my Ookibloks data, I figured it would be a good time to do a little extra content optimization. If, like Ookibloks, you happen to use PNG for your game’s textures, you may have a lot to gain by way of the PNG compression strategy you use.

The amount of file size compression can vary wildly depending on the compression tool used and its settings. For Ookibloks I went with pngcrush, an open-source commandline utility that can change compression methods and strip unnecessary metadata from PNG files. After experimenting with various parameters and looking up the batch file “for” expression syntax (I can never seem to remember it off the top of my head), I ended up with the following:

FOR /F %%i IN ('DIR /S /B resource\*.png') DO pngcrush.exe -ow -reduce -rem gAMA -rem cHRM -rem iCCP -rem sRGB -rem alla -rem text %%i

Okay, that’s a lot to unpack, so let’s get started.
First, the FOR command. The general form of the command is FOR %%parameter IN (dataset) DO command where each instance parsed from the dataset will be placed into the named parameter which can then be used with the given command. The /F variation of FOR works on each filename in the dataset.

To produce the dataset for the FOR command, I used a DIR command to produce a list of PNG files in the target directory. The /S parameter makes the DIR command search subdirectories while the /B makes DIR skip outputting file dates and sizes and just produce absolute file paths.

Now on to pngcrush itself. The -ow parameter tells pngcrush to overwrite the input file (provided by %%i from the FOR command) with the resulting file. The -reduce parameter tells it to do lossless bit-depth reduction. The -rem parameters tell pngcrush to remove various color correction data and extra metadata that weren’t actually being used by Ookibloks.

All told, crushing PNGs managed to shave 8 MB off of Ookibloks’ total size. Not bad for an evening’s work.

Posted in Ookibloks, Tech.