Search code examples
c++cimagepng

How to create and write an indexed png image in C++ or C


I am trying to create and write an indexed png image in C++ or C using a library that is portable to IOS and Android, so I looked into png++, opencv and libpng. I have tried using png++ but could not produce index images correctly. I was not able to figure out libpng indexed images, and did not find an example. opencv does not seem to handle indexed png images. png++ seems to be easier to use but the documentation leaves out the part on how to set your own values for the indexed images, it just puts "..." in that section (see below). Any help would be appreciated.

#include <png++/png.hpp>
 //...
 png::image< png::index_pixel > image;
 png::palette pal(256);
 for (size_t i = 0; i < pal.size(); ++i)
 {
     pal[i] = png::color(i, 255 - i, i);
 }
 image.set_palette(pal);
 ...
 image.write("palette.png");

Solution

  • You create the indexed image the same way as you would create an rgb image, except that the pixel type is png::index_pixel instead of png::rgb_pixel.

    Otherwise, it looks just like the example in the documentation:

    for (png::uint_32 y = 0; y < image.get_height(); ++y)
    {
        for (png::uint_32 x = 0; x < image.get_width(); ++x)
        {
            image[y][x] = png::index_pixel(/* the index value */);
            // non-checking equivalent of image.set_pixel(x, y, ...);
        }
    }