Question

I'm trying to save an image of size 5x5 pixels, read with glReadPixels into a file using SOIL.

I read the pixels:

int x = 400;
int y = 300;
std::vector< unsigned char* > rgbdata(4*5*5);
glReadPixels(x, y, 5, 5,GL_RGBA,GL_UNSIGNED_BYTE, &rgbdata[0]); 

Then I try saving the read data with SOIL's save image function

int save_result = SOIL_save_image
    (
    "image_patch.bmp",
    SOIL_SAVE_TYPE_BMP,
    5, 5, 4,
    rgbdata[0]
    );

But when trying to save the image, I get an unhandled exception.

Solution (by Christian Rau)

int x = 400;
int y = 300;
std::vector< unsigned char > rgbdata(4*5*5);
glReadPixels(x-(5/2), y-(5/2), 5, 5,GL_RGBA,GL_UNSIGNED_BYTE, &rgbdata[0]);

int save_result = SOIL_save_image
    (
    "image_patch.bmp",
    SOIL_SAVE_TYPE_BMP,
    5, 5, 4,
    rgbdata.data()
    );
Was it helpful?

Solution

You are creating a vector of pointers to unsigned char (std::vector<unsigned char*>, but what you want is just a vector to unsigned char (std::vector<unsigned char>).

And in the call to SOIL_save_image you don't have to give it rgbdata[0], which would be a single unsigned char (and with your incorrect vector type an uninitialized pointer, likely resulting in some memory access error), but a pointer to the complete data and thus rgbdata.data() (or &rgbdata[0] if you don't have C++11).

OTHER TIPS

Also notice :

GL's default pack/unpack image width should be multiples of 4, that is to say, width in glReadPixels(x, y, width, height, format, type, data) should meet the condition width % 4 == 0.

If width % 4 != 0(in your case 5 % 4 != 0), it may lead to unexpected results. So you also have to avoid these problems and here is the solution:

glPixelStorei(GL_UNPACK_ALIGNMENT,1);
glPixelStorei(GL_PACK_ALIGNMENT,1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top