Handling PNG images in C++

This blog post is about png++, one of my favourite C++ libraries.

It’s a wrapper of libpng in C++ that allows to handle PNG images so easily that you’ll never want to use bare libpng again.

All you need to start is to add these two lines in you source files:

#include "png++/png.hpp"
using namespace png;

This is the code to open an existing image:

image img("image.png");

The code to make a new image from scratch differs only in the parameter passed to image’s constructor:

image img(1024,768);

The image class has the get_pixel() and set_pixel() memeber functions to access the individual pixels:

rgb_pixel pixel=img.get_pixel(0,0);
pixel.red=min(255,pixel.red+10); //Increase red color of pixel
img.set_pixel(0,0,pixel);

The image height and width can be obtained with intuitive get_height() and get_width() memeber functions:

for(int i=0;i<img.get_width();i++)
{
    for(int j=0;j<img.get_height();j++)
    {
        //Do something
    }
}

The image can be written to file with the write() memebr function:

img.write("new_image.png");

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

About these ads

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

  1. valentin_gheorghe89@yahoo.com Says:

    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.

    regards,

    valentin gheorghe

    • fedetft Says:

      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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

Join 29 other followers

%d bloggers like this: