Also, this library is header-only. What does it means? That you do not have to compile the library to start playing with it, just exptract the library in the folder where you have your source code, and include the header file “png.hpp”, just that.

Lastly, here is an example code including CMake scripts to show the capabilities of the library. png++.tar.gz

6 Responses to “Handling PNG images in C++”

hi, thank you for this post … I am really having a tough time trying to compile the two example codes provided in windows 7 VS10. I am quite new to cmake could you please help me in setting this two example working.

Unfortunately I have abandoned windows for a long time, and do not even have a computer with it installed to try compiling that code.
Anyway, the png++ library depends on libpng, which on Linux is installed by default, but not on windows. It may be the cause of your issues.

I went and tested how to do something with every pixel of an image the fastest. The following code tests 4 different Methods, you can test it out or just believe me:
Method 1 is slightly faster than Method 3
Method 2 is a shitload faster than Method 1
Method 4 is slower than Method 2, but faster than 1.
Meaning:
rgb_pixel *pPtr;
for(size_t i=0; i<y; ++i) {
pPtr = &img2[i][0];
for(size_t j = 0; j<x; ++j) {
(*pPtr).red=0;
(*pPtr).green=255;
(*pPtr).blue=0;
++pPtr;
}
}
Is the ideal code (it's ~16 times faster). Pointers can be useful.
Of course, this is mainly noticeable for huge dimensions. It can't hurt to optimize however.http://pastebin.com/s2QW8AV7

This is nice to know, but I’m wondering if the png++ library gives any guarantee about the memory layout of rgb_pixel objects in memory. Method 2, that is the most attractive from the performance point of view, works from making a pointer from the reference returned by img[i][0], and incrementing that pointer instead of calling img[i][j] repeatedly.
If all of a sudden the image class changes form row major to column major representation, that code would stop work in strange ways.
Anyway, thanks for the benchmark code, It’s always interesting to compare different approaches. By the way, on my machine the results are (using g++ -O3 on a laptop with OpenSuse 13.2, Core i7-3630QM)
iterativ: 0.089429
Pointer: 0.0162
Iterativ2: 0.094149
Pointer2: 0.015439
so the pointer method is 5.5 times faster than method 1, which is the one I would use to be on the safe side. Maybe there’s some ‘inline’ missing in some of the png++ member functions that could help…