Search code examples
c++cpngzliblibpng

How to convert a zlib stream to PNG?


I already have a zlib-encoded stream of image data (taken from a PDF /FlateDecode tag). I also got the width and height in pixels as well as color depth (8 bpp). The data is packed RGB. Now I want to save this as a PNG image (which default compression method is also ZLIB I think?). I tried adding a PNG header and a IDAT header manually, but it didn't work. Has anyone an idea, how to to this properly? (libpng ?)

The target system has very limited RAM resources, so decoding the zlib data and re-encoding with libpng is off the table.


Solution

  • You'll need to decompress, reformat the data for PNG, and recompress. The image data that is compressed in a PNG file is not simply the raw RGB data. Per the specification, each line of the image is preceded by a filter byte, which specifies how that line is differenced (or not) from previous data. Even if you do no differencing, you need that byte to say that. However you will get much better compression with one of the filter modes.