用glReadPixels保存显示的界面
#include <GL/glut.h>
#include <iostream>
#include <fstream>
#include <vector>// Save pixel data as BMP image
void saveBMP(const std::string& filename, int width, int height, const std::vector<GLubyte>& data) {std::ofstream file(filename, std::ios::binary);if (!file) {std::cerr << "Error opening file for writing" << std::endl;return;}int imageSize = width * height * 3; // RGB data, 3 bytes per pixelint fileSize = 54 + imageSize; // BMP header size + image sizeunsigned char bmpFileHeader[14] = {'B', 'M', // Magic numberstatic_cast<unsigned char>(fileSize), static_cast<unsigned char>(fileSize >> 8),static_cast<unsigned char>(fileSize >> 16), static_cast<unsigned char>(fileSize >> 24),0, 0, 0, 0, // Reserved54, 0, 0, 0 // Offset to pixel data};unsigned char bmpInfoHeader[40] = {40, 0, 0, 0, // Info header sizestatic_cast<unsigned char>(width), static_cast<unsigned char>(width >> 8),static_cast<unsigned char>(width >> 16), static_cast<unsigned char>(width >> 24),static_cast<unsigned char>(height), static_cast<unsigned char>(height >> 8),static_cast<unsigned char>(height >> 16), static_cast<unsigned char>(height >> 24),1, 0, // Number of color planes24, 0, // Bits per pixel (RGB)0, 0, 0, 0, // Compression method0, 0, 0, 0, // Image size0, 0, 0, 0, // Horizontal resolution0, 0, 0, 0, // Vertical resolution0, 0, 0, 0, // Number of colors in color palette0, 0, 0, 0 // Number of important colors};file.write(reinterpret_cast<char*>(bmpFileHeader), sizeof(bmpFileHeader));file.write(reinterpret_cast<char*>(bmpInfoHeader), sizeof(bmpInfoHeader));file.write(reinterpret_cast<const char*>(&data[0]), imageSize);file.close();
}void display() {// Your OpenGL drawing code here// ...glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Clear color to blackglClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer// Draw something on the screenglBegin(GL_TRIANGLES);glColor3f(1.0f, 0.0f, 0.0f); // Red colorglVertex2f(-0.5f, -0.5f);glVertex2f(0.5f, -0.5f);glVertex2f(0.0f, 0.5f);glEnd();glFlush(); // Ensure all drawing commands are executedGLint viewport[4];glGetIntegerv(GL_VIEWPORT, viewport); // Get viewport dimensionsint width = viewport[2];int height = viewport[3];std::vector<GLubyte> pixelData(width * height * 3); // RGB dataif (!pixelData.empty()) {glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, &pixelData[0]);// Convert RGBA to BGR format for BMPfor (int y = 0; y < height; y++) {for (int x = 0; x < width; x++) {int index = (y * width + x) * 3;GLubyte temp = pixelData[index]; // Store red componentpixelData[index] = pixelData[index + 2]; // Replace red with bluepixelData[index + 2] = temp; // Set blue to stored red}}saveBMP("screenshot.bmp", width, height, pixelData);}
}int main(int argc, char** argv) {glutInit(&argc, argv);glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);glutInitWindowSize(800, 600);glutCreateWindow("OpenGL Screenshot Example");glutDisplayFunc(display);glutMainLoop();return 0;
}