Taking screenshots using glReadPixels()

Started by
10 comments, last by V-man 18 years, 6 months ago
Taking screenshots should be very simple, and with glReadPixels it is. Problem is for some reason it crashes the program. When it calls it, the whole program just closes. I have no idea why or what could be causing it. Maybe I need to glEnable something? Does it need to be called or after something? I'm thinking maybe it's swapping buffers too soon and when I call there's nothing to be read in? I really have no clue, if anyone could help in any way I'd appreciate it, thanks.
Advertisement
Ripped from my lib, you should get the basic idea.
//this will save a TGA in the screenshots//folder under incrementally numbered filesvoid gl_video::SaveTGA(void){          char cFileName[64];    FILE *fScreenshot;    int nSize = m_WindowWidth * m_WindowHeight * 3;        GLubyte *pixels = new GLubyte [nSize];    if (pixels == NULL) return;            int nShot = 0;    while (nShot < 64)    {        sprintf(cFileName,"screenshot_%d.tga",nShot);        fScreenshot = fopen(cFileName,"rb");        if (fScreenshot == NULL) break;        else fclose(fScreenshot);                ++nShot;        if (nShot > 63)        {            MessageBox(m_WindowHandle,"Screenshot limit of 64 reached. Remove some shots if you want to take more.",            m_AppTitle,MB_OK);            return;        }    }           fScreenshot = fopen(cFileName,"wb");        glReadPixels(0, 0, m_WindowWidth, m_WindowHeight, GL_RGB,     GL_UNSIGNED_BYTE, pixels);               //convert to BGR format        unsigned char temp;    int i = 0;    while (i < nSize)    {        temp = pixels;       //grab blue        pixels = pixels[i+2];//assign red to blue        pixels[i+2] = temp;     //assign blue to red        i += 3;     //skip to next blue byte    }    unsigned char TGAheader[12]={0,0,2,0,0,0,0,0,0,0,0,0};    unsigned char header[6] = {m_WindowWidth%256,m_WindowWidth/256,    m_WindowHeight%256,m_WindowHeight/256,24,0};        fwrite(TGAheader, sizeof(unsigned char), 12, fScreenshot);    fwrite(header, sizeof(unsigned char), 6, fScreenshot);    fwrite(pixels, sizeof(GLubyte), nSize, fScreenshot);    fclose(fScreenshot);            delete [] pixels;           return;}
You need to post some code.. btw it closes cause you dont allocate enough memory to save the screenshot (framebuffer), so for instance,

int width, height;
GLfloat pixels malloc(width*height*3*sizeof(GLfloat));
glReadPixels(... , pixels);
Quote:Original post by Vampyre_Dark
Ripped from my lib, you should get the basic idea.
*** Source Snippet Removed ***


When you are going to be dealing with 24 bit data (RGB), you have to set the data alignment.

For glReadPixels and any GL function that downloads data:

glPixelStorei(GL_PACK_ALIGNMENT, 1);

For glDrawPixels and any GL function that uploads data:

glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

If you are working with 32 bit data, leave them at 4 (default for GL)

Sig: http://glhlib.sourceforge.net
an open source GLU replacement library. Much more modern than GLU.
float matrix[16], inverse_matrix[16];
glhLoadIdentityf2(matrix);
glhTranslatef2(matrix, 0.0, 0.0, 5.0);
glhRotateAboutXf2(matrix, angleInRadians);
glhScalef2(matrix, 1.0, 1.0, -1.0);
glhQuickInvertMatrixf2(matrix, inverse_matrix);
glUniformMatrix4fv(uniformLocation1, 1, FALSE, matrix);
glUniformMatrix4fv(uniformLocation2, 1, FALSE, inverse_matrix);
Quote:Original post by V-man
When you are going to be dealing with 24 bit data (RGB), you have to set the data alignment.
?? What exactly is the problem? The code works, I've saved thousands of TGAs with it by now.

Quote:Original post by Vampyre_Dark
Quote:Original post by V-man
When you are going to be dealing with 24 bit data (RGB), you have to set the data alignment.
?? What exactly is the problem? The code works, I've saved thousands of TGAs with it by now.

Try it on a window where the width multiplied by 3 is not a multiple of 4, and your code will fail. Always set the alignment to 1 before reading back RGB data, as V-Man showed.

And that's not the only problem with that code, btw. It will also fail, if another window overlaps a part of the render window. This region will then contain undefined data in the screenshot.
Quote:Original post by Yann L
Quote:Original post by Vampyre_Dark
Quote:Original post by V-man
When you are going to be dealing with 24 bit data (RGB), you have to set the data alignment.
?? What exactly is the problem? The code works, I've saved thousands of TGAs with it by now.

Try it on a window where the width multiplied by 3 is not a multiple of 4, and your code will fail. Always set the alignment to 1 before reading back RGB data, as V-Man showed.

And that's not the only problem with that code, btw. It will also fail, if another window overlaps a part of the render window. This region will then contain undefined data in the screenshot.


Correct, glReadPixels from the back buffer is not the best solution.
p-buffer or FBO is better.
For fullscreen apps, I think it's not a problem.

Vampyre_Dark, the problem is that you get boundary overflow and weird bugs and also, the screenshot will look screwed up.
Sig: http://glhlib.sourceforge.net
an open source GLU replacement library. Much more modern than GLU.
float matrix[16], inverse_matrix[16];
glhLoadIdentityf2(matrix);
glhTranslatef2(matrix, 0.0, 0.0, 5.0);
glhRotateAboutXf2(matrix, angleInRadians);
glhScalef2(matrix, 1.0, 1.0, -1.0);
glhQuickInvertMatrixf2(matrix, inverse_matrix);
glUniformMatrix4fv(uniformLocation1, 1, FALSE, matrix);
glUniformMatrix4fv(uniformLocation2, 1, FALSE, inverse_matrix);
Thanks guys I got it working, didn't fix the packing problem though cuz
Quote:
Correct, glReadPixels from the back buffer is not the best solution.
p-buffer or FBO is better.
For fullscreen apps, I think it's not a problem.

Vampyre_Dark, the problem is that you get boundary overflow and weird bugs and also, the screenshot will look screwed up.

It looks very screwed up. So what would be a better way to do screenshots? What is p-buffer and FBO?

It's impossible to take a screenshot when another window is overlapped, as it doesn't have the input focus to even get the SaveTGA call. [grin] But what exactly is the problem with that? Is that something I'm doing wrong, or just if someone set it up to have it take screenshots automatically and there happened to be in the back of another window?

Okay, I think I have fixes for both of those. What is the problem with the window size and mulitples of 4?

//this will save a TGA in the screenshots//folder under incrementally numbered filesvoid gl_video::SaveTGA(void){    glPixelStorei(GL_PACK_ALIGNMENT,1);    if (GetForegroundWindow() != m_WindowHandle) return;          char cFileName[64];    FILE *fScreenshot;    int nSize = m_WindowWidth * m_WindowHeight * 3;        GLubyte *pixels = new GLubyte [nSize];    if (pixels == NULL) return;            int nShot = 0;    while (nShot < 64)    {        sprintf(cFileName,"screenshot_%d.tga",nShot);        fScreenshot = fopen(cFileName,"rb");        if (fScreenshot == NULL) break;        else fclose(fScreenshot);                ++nShot;        if (nShot > 63)        {            MessageBox(m_WindowHandle,"Screenshot limit of 64 reached. Remove some shots if you want to take more.",            m_AppTitle,MB_OK);            return;        }    }           fScreenshot = fopen(cFileName,"wb");        glReadPixels(0, 0, m_WindowWidth, m_WindowHeight, GL_RGB,     GL_UNSIGNED_BYTE, pixels);               //convert to BGR format        unsigned char temp;    int i = 0;    while (i < nSize)    {        temp = pixels;       //grab blue        pixels = pixels[i+2];//assign red to blue        pixels[i+2] = temp;     //assign blue to red        i += 3;     //skip to next blue byte    }    unsigned char TGAheader[12]={0,0,2,0,0,0,0,0,0,0,0,0};    unsigned char header[6] = {m_WindowWidth%256,m_WindowWidth/256,    m_WindowHeight%256,m_WindowHeight/256,24,0};        fwrite(TGAheader, sizeof(unsigned char), 12, fScreenshot);    fwrite(header, sizeof(unsigned char), 6, fScreenshot);    fwrite(pixels, sizeof(GLubyte), nSize, fScreenshot);    fclose(fScreenshot);            delete [] pixels;           return;}


Quote:Original post by Vampyre_Dark
It's impossible to take a screenshot when another window is overlapped, as it doesn't have the input focus to even get the SaveTGA call. [grin]

Keep in mind, that under Windows a window can have the input focus, yet still be overlapped by another floating window with the WS_EX_TOPMOST style.

Quote:Original post by Vampyre_Dark
But what exactly is the problem with that? Is that something I'm doing wrong, or just if someone set it up to have it take screenshots automatically and there happened to be in the back of another window?

No, it's fundamentally wrong to read back from the backbuffer, unless you are guaranteed to never have any overlapping window. In a fullscreen game, this is usually true, but it fails as soon as some floating window pops up (eg. a messenger notification, the task manager, the windows start menu, etc). Taking a screenshot might not be the most vital function, so that's an acceptable risk in most cases. But don't use the backbuffer as a replacement for a render texture, eg. for fullscreen bloom effects. As convenient as it might seem, the pixel ownership test is going to bite you hard, as soon as something overlaps. IMO, this is a flaw in the OpenGL specs, but well. The only way to create a screenshot function that works in really all circumstances is by using a pbuffer or a FBO.

Quote:Original post by Vampyre_Dark
Okay, I think I have fixes for both of those. What is the problem with the window size and mulitples of 4?

If the width multiplied by the component data size (3 for RGB) isn't aligned with the current PACK_ALIGNMENT setting, then OpenGL will add appropriate padding. And that will screw up the image strides.

This topic is closed to new replies.

Advertisement