How to take screenshot in OpenGL

EthanHunt picture EthanHunt · Apr 30, 2011 · Viewed 38.5k times · Source

How to take a screenshot of an OpenGL window in C++ and save it to file.

I found the glReadPixels() function, but I don't know what to do next. Where I can set path to a file, for example?

If not difficult, write code, please.

Answer

huy picture huy · Aug 4, 2011

This piece of code captures the OpenGL window and export to a BMP file. You must have FreeImage library to run it.

// Make the BYTE array, factor of 3 because it's RBG.
BYTE* pixels = new BYTE[3 * width * height];

glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels);

// Convert to FreeImage format & save to file
FIBITMAP* image = FreeImage_ConvertFromRawBits(pixels, width, height, 3 * width, 24, 0x0000FF, 0xFF0000, 0x00FF00, false);
FreeImage_Save(FIF_BMP, image, "C:/test.bmp", 0);

// Free resources
FreeImage_Unload(image);
delete [] pixels;