1

I am trying to save the openGL screen to a file using this explanation but the images I receive are not valid: enter image description here

What can be a reason for this?

  • I am using glfw with double buffer, which has been reported to make problems in some cases. However, using glFlush() freezes my screen. :/

  • May it happen, that the glReadPixels method is called while buffer swap is performed? I actually use a Mutex in order to prevent this.

  • Do I need some trick in glfw for this?

Here is the code for reference:

glfwGetWindowSize(&mWidth, &mHeight);

glBufferLock.lock();
std::cout << "\nSaving screenshot (" << mWidth << ", " << mHeight << ")\n";

int n=3 * mWidth * mHeight;
GLubyte* pixels = new GLubyte[n];

glPixelStorei(GL_PACK_ALIGNMENT, 1);


glReadPixels(0,0,mWidth,mHeight, GL_RGB, GL_UNSIGNED_BYTE, pixels);
if (GL_NO_ERROR != glGetError()) throw "Error: Unable to read pixels.";

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

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

Thank you very much for any hint!

Community
  • 1
  • 1
mojovski
  • 581
  • 7
  • 21
  • Mutex? You don't need it it you have one thread. Please show us how this screenshot should look like. What was an original image? – HolyBlackCat Nov 17 '15 at 13:15
  • Do you want to take a screenshot of an image *your own* program did render, or do want to take a shot of the screen as drawn by other programs into foreign windows? If the later is the case, don't try any further to do it with OpenGL, because it's not possible to do (cleanly). Up to Windows Vista you could do it (on the Windows platform), by exploiting the way Windows allocated framebuffers to windows. But this no longer works. – datenwolf Nov 17 '15 at 15:07
  • my own. :) The problem was that I tried to grab the pixel buffer from another thread. All the openGL commands must be executed from the same thread. – mojovski Nov 19 '15 at 21:45
  • Possible duplicate of [How to take screenshot in opengl](http://stackoverflow.com/questions/5844858/how-to-take-screenshot-in-opengl) since no GLFW specifics are used here. – Ciro Santilli OurBigBook.com Sep 16 '16 at 07:24

1 Answers1

4

The problem was that I tried to grab the pixel buffer from another thread. All the openGL commands must be executed from the same thread.

mojovski
  • 581
  • 7
  • 21