4

I am taking a screenshot of my screen and saving it in the regular bmp file. The code below generate the bmp file but the picture viewer have the follow message "Viewer can't open this picture because the file appears to be damage, corrupted, or is too large." I have seen other solution with OpenGL combined with other tools, but this one has to be only with OpenGL on C++.

#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);
}
Felix D.
  • 133
  • 8
  • You didn't specify a language, so due to that ambiguity, here is my reponse in the form of C# and OpenTK: http://www.opentk.com/doc/graphics/save-opengl-rendering-to-disk – Krythic Dec 07 '15 at 02:32
  • 1
    Is that BMP format or TGA? I find it odd that the header is named `TGAheader` but you say it's a BMP. – Mike Harris Dec 07 '15 at 02:42
  • Thank you @Krythic, I just edited the question to specify the language. – Felix D. Dec 07 '15 at 02:48

0 Answers0