imagepng problem and solution

Just came across a problem where I was saving a PNG and the PHP engine silently exited. A message was logged in the httpd error_log, though:

[Wed May 10 11:45:41 2006] [error] [client] PHP Fatal error:  imagepng()[function.imagepng]: gd-png:  fatal libpng error: zlib error in /share/www/test/j/fckeditor/editor/filemanager/browser/default/connectors/php/commands.php on line 74

It turns out that the problem is that PHP 5.1 introduces a third parameter to the imagepng() function, for controlling the level of quality. This value is an integer between 0 and 9 inclusive.

The error I was experiencing was caused by me using 100 as a default third parameter, as imagejpeg() uses this to control quality output (as a percentage), and I was trying to be efficient with my code by calling the image creation function using a variable instead of a hard-coded call (allowing me to save to an arbitrary format, instead of a set format).

So – if you use a quality parameter in your PNG creation code blocks, remember that it is not similar to the JPEG creation function (annoying as that is). For example, the line I just corrected in my CMS now reads: