Reading a png

Does anyone know how to read a png file into an int array of its pixels? I've come from Java and there's a BufferedImage.getRGB() method there for exactly what I'm trying to achieve. Is there an alternative to using this in C++?

Thanks,

Paul
In C++, such things tend not to exist as part of the core language; the C++ philosophy tends not to include that kind of high-level file format manipulation - not much call for it on the vast majority of the world's processors (which, of course, do not live inside PCs), and C++'s roots are in C, which I like to think of as the closest reasonable approximation of a portable assembler language we're likely to see :)

For png, I'd guess there's a library called libpng... yup, there it is:
http://www.libpng.org/pub/png/libpng.html

Nine times out of ten, stick "lib" on the front and there's your library :p

That said, libpng might be a bit tricky to start with if you've come from Java. If you're happy with header files, you might look at CImg. It exists as a single header file (although it might use some other libraries that typically exist on a dev PC, but might not).. Here's how I can read a png image on my linux box, display it, and get the RGB values at location 10,10.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "CImg.h"
#include <iostream>
using namespace cimg_library;

int main()
{
  CImg<float> image("hills.png");
  CImgDisplay main_disp(image);
  float pixvalR = image(10,10,0,0); // read red val at coord 10,10
  float pixvalG = image(10,10,0,1); // read green val at coord 10,10
  float pixvalB = image(10,10,0,2); // read blue val at coord 10,10
  std::cout << "R = " << pixvalR << ", G = " << pixvalG << ", B = " << pixvalB;
  
  std::cin.ignore();
}


I think CImg does indeed store the pixels in a big array, so you can just grab the pointer to the front and off you go with your requested array. It's pretty common in image libraries to do it that way.

There are many, many more image libraries written in C and C++. Go looking, find one you like, and start coding.
Last edited on
Would you suggest using a Bitmap?

http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.aspx#Y0

This one^

I've tried to implement one here but it just highlights the word "Bitmap" and says "Error: identifier "Bitmap" is undefined"

1
2
3
4
5
6
Bitmap^ icons;
	try {
		icons = gcnew Bitmap("C:\\icons.jpg");
	} catch(ArgumentException^) {

	}
The sample code you've shown there isn't C++. Looks like some kind of hideous MS .NET variant.

If you'd rather use a bitmap image, I suggest the library easyBMP, which comes in two version, both very easy.
Last edited on
Topic archived. No new replies allowed.