Error with glReadPixels

Here is my present situation (codewise):

unsigned char image;
image = new unsigned char[(width
height*3)];
glReadPixels(0,0, width, height, GL_RGB, GL_INT, image);

the width of my image in pixels is 490, the height is 450.

When width and height are equal, it reads fine, but when height is 450, there is an error, something like :“Access violation writing location 0xXXXXXXXX”

What am I doing wrong?


image = new unsigned char[(widthheight3)];

Here you allocate widthheight3 bytes for readback.

[b]
glReadPixels(0,0, width, height, GL_RGB, GL_INT, image);

[/b]

Since you specify GL_INT as the type for pixel data, GL will use 3 * sizeof(int) for every pixel in your readback buffer. If your int size is 32 bits, your readback buffer will be too small and the readback will result in an access violation.

Try using ‘new int[widthheight3]’ or ‘new unsigned char[widthheight4*3]’ instead.

[This message has been edited by roffe (edited 02-03-2004).]

That would solve the access violation but I guess the “three ints per pixel” target format wasn’t wanted in the first place.

I’d rather suggest this

unsigned char *image;
image = new unsigned char[(width*height*3)];
glReadPixels(0,0, width, height, GL_RGB, [b]GL_UNSIGNED_BYTE[/b], image);

On a sidenote, GL’s default pixel pack/unpack state may lead to unexpected results for image widths that are not whole multiples of four.
If you want to avoid these problems, add this to your init code

glPixelStorei(GL_UNPACK_ALIGNMENT,1);
glPixelStorei(GL_PACK_ALIGNMENT,1);