我正在截取屏幕截图并将其保存在常规bmp文件中。下面的代码生成bmp文件,但图片查看器有以下消息"查看者无法打开此图片,因为该文件似乎是损坏,损坏或太大。"我已经看到了OpenGL与其他工具相结合的其他解决方案,但是这个解决方案必须只适用于C ++上的OpenGL。
#include <stdlib.h>
#define GLEW_STATIC
#include <GL/glew.h>
#include "GLFW/glfw3.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(){
int w = 600;
int h = 800;
std::string filename = "temp.bmp";
//This prevents the images getting padded
// when the width multiplied by 3 is not a multiple of 4
glPixelStorei(GL_PACK_ALIGNMENT, 1);
int nSize = w*h * 3;
// First let's create our buffer, 3 channels per Pixel
char* dataBuffer = (char*)malloc(nSize*sizeof(char));
if (!dataBuffer) return false;
// Let's fetch them from the backbuffer
// We request the pixels in GL_BGR format, thanks to Berzeger for the tip
glReadPixels((GLint)0, (GLint)0,
(GLint)w, (GLint)h,
GL_BGR, GL_UNSIGNED_BYTE, dataBuffer);
//Now the file creation
FILE *filePtr = fopen(filename.c_str(), "wb");
if (!filePtr) return false;
unsigned char TGAheader[12] = { 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
unsigned char header[6] = { w % 256, w / 256,
h % 256, h / 256,
24, 0 };
// We write the headers
fwrite(TGAheader, sizeof(unsigned char), 12, filePtr);
fwrite(header, sizeof(unsigned char), 6, filePtr);
// And finally our image data
fwrite(dataBuffer, sizeof(GLubyte), nSize, filePtr);
fclose(filePtr);
}