Working with PNG files in C++

I’m working on MacOS X, so first of all I need to compile and install the libraries (libpng and png++):

#Download here: http://prdownloads.sourceforge.net/libpng/libpng-1.5.7.tar.gz?download
tar xvzf libpng-1.5.7.tar.gz
cd libpng-1.5.7
./configure
make
sudo make install

#Download png++
curl http://download.savannah.nongnu.org/releases/pngpp/png++-0.2.5.tar.gz > ./png++.tar.gz
tar xzvf png++.tar.gz
cd png++-0.2.5
make
sudo make install

Everything should be installed now, and we can write some code. Create the following C++ program:

#include <png++/png.hpp>

int main() {

  png::image< png::rgb_pixel > image("input.png");

  for (size_t y = 0; y < image.get_height(); ++y) {
    for (size_t x = 0; x < image.get_width(); ++x) {
      if(((x+y)%2) == 0) image[x][y] = png::rgb_pixel(0, 0, 0);
    }
  }

 image.write("output.png");
}

The program loads a file called input.png, sets every other pixel to black and writes it to output.png. Compile and run as follows:

g++ test.cpp -lpng
./a.out

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>