libpng – Changing compression level when writing PNG Image

This took me a bit of time to find, but I have been experimenting with libpng for writing software to save 16bit grayscale images and wanted to switch off compression to see if libpng would save the images out any faster than it normally does. When you call png_set_IHDR() you have to set the compression type to PNG_COMPRESSION_TYPE_DEFAULT, there is no alternative (e.g. there is no value like PNG_COMPRESSION_TYPE_NONE), this threw me for a bit…

Anyway after a spell of RTFMing, I eventually found out that you can alter then compression level, and indeed switch it off via a call to:


Setting a value of 0 in your code switches off compression, while setting it to 9 causes the lib to use maximum compression. Quick testing revealed that the time taken to save a PNG does decrease as you reduce this value towards 0 (and the saved image size increases!).

PNG is a good file format option for saving 16bit images, it is lossless and faithfully represents grayscale rather than fudging it into an RGB structure, and as it turns out, supports adjustable compression levels. As more cameras natively support higher bit-depth images, formats and software tools that support the greater precision will become more important so that Computer Vision and Machine Vision software can take full advantage.

PS Viewing 16bit grayscale images is harder than you might think, most software tools seem to down-sample them to 8bit grayscale, So far, I have found that good options are a.) ImageJ b.) Gimp 2.9 (not yet released, have to use a development build). These tools allow you to view the images and properly sample the 16bit pixel values etc…