I'm trying to do a screen capture in GLUT and I'm having a bit of an issue. glReadPixels() seems to crash my program with an
Access violoation writing location 0x00000000
The thing that is weird is the file is created in the root of the project, and is obviously empty. I set up some printf commands quickly and it appears that the code crashes each time during the glReadPixels() method.
I feel the issue maybe the variable 'pixels'. Im having trouble figuring out the correct way to define this so that the RGB values are written to it.
Any tips would be appreciated.
void savePPM(char ppmFileName[]){
int width = glutGet(GLUT_WINDOW_WIDTH);
int height = glutGet(GLUT_WINDOW_HEIGHT);
char *pixels = NULL;
glReadPixels(0,0, width, height, GL_RGB, GL_UNSIGNED_BYTE ,pixels);
ppmFile = fopen(ppmFileName, "wb");
fprintf(ppmFile, "P6\n");
fprintf(ppmFile, "%d %d\n", width, height);
fprintf(ppmFile, "255\n");
fwrite(pixels, 1, width*height*3, ppmFile);
fclose(ppmFile);
free(pixels);
}
glReadPixels
doesn't allocate memory for you, it merely stores the pixel data in the buffer that you give it in the last parameter. You're giving it a NULL pointer, so it's trying to store data at address 0, which obviously results in an access violation.
You need to allocate the memory first, pass it to glReadPixels
, and then deallocate it. You also need to make sure that you call glPixelStorei
to ensure that the pixel data is returned packed, without any padding (alternatively, you can write each scan line individually, but that requires a little extra effort).
For example:
// Error checking omitted for expository purposes
char *pixels = malloc(width * height * 3); // Assuming GL_RGB
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(..., pixels);
...
fwrite(pixels, ...);
...
free(pixels);
来源:https://stackoverflow.com/questions/9090892/glut-screen-capture-in-c