Save an OpenGL screen
The following is a C++ routine for saving an OpenGL screen to a PNG file. It
relies on Boutell.com's gd library for the PNG support.
You may use this routine freely in your code, and you can call it like so:
saveimage(640, 480, "screen.png"); If you have any comments, please
email us .
void saveimage(int width, int height, const char *filename)
{
unsigned char *buffer = new unsigned char[width*height*3];
glReadPixels(0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,buffer);
gdImagePtr mypixels;
mypixels = gdImageCreateTrueColor(width, height);
for (int yctr=0; yctr < height; yctr++)
for (int xctr=0; xctr < width; xctr++)
{
int color = gdTrueColor(buffer[yctr*width*3+xctr*3], buffer[yctr*width*3+xctr*3+1], buffer[yctr*width*3+xctr*3+2]);
gdImageSetPixel(mypixels, xctr, yctr, color);
}
FILE *pngout;
pngout = fopen(filename, "wb");
gdImagePng(mypixels, pngout);
fclose(pngout);
gdImageDestroy(mypixels);
delete[] buffer;
}