Saving part of the screen to a file (SOIL and glReadPixels)

I am trying to save a 5x5 pixel image, read from 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 will try to save the read data with the image save function SOIL

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

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

Solution (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() ); 
+4
source share
2 answers

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

And in the SOIL_save_image call SOIL_save_image you do not need to specify its rgbdata[0] , which would be the only unsigned char (and with your incorrect vector type an uninitialized pointer, which probably led to a memory access error), but a pointer to the complete data and therefore , rgbdata.data() (or &rgbdata[0] if you don't have C ++ 11).

+5
source

Also note:

GL, by default, package / unpack the image, the width must be a multiple of 4 , that is, width in glReadPixels(x, y, width, height, format, type, data) must satisfy the condition width % 4 == 0 .

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

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

Source: https://habr.com/ru/post/1487270/


All Articles