Take screenshot with openGL and save it as png

╄→гoц情女王★ 提交于 2019-12-01 19:17:12

You could use the devil image library and take a screeshot with:

void takeScreenshot(const char* screenshotFile)
{
    ILuint imageID = ilGenImage();
    ilBindImage(imageID);
    ilutGLScreen();
    ilEnable(IL_FILE_OVERWRITE);
    ilSaveImage(screenshotFile);
    ilDeleteImage(imageID);
    printf("Screenshot saved to: %s\n", screenshotFile);
}

takeScreenshot("screenshot.png");

If you don't reject to use C++ library, you should try PNGwriter! It write the picture pixel by pixel and their RGB values. Since the PNGwriter start form left-up corner while the glReadPixels() start from left-bottom, your code while like:

GLfloat* OpenGLimage = new GLfloat[nPixels];
glReadPixels(0.0, 0.0, width, height,GL_RGB, GL_FLOAT, OpenGLimage);
pngwriter PNG(width, height, 1.0, fileName);
size_t x = 1;   // start the top and leftmost point of the window
size_t y = 1;
double R, G, B;
for(size_t i=0; i<npixels; i++)
{
      switch(i%3) //the OpenGLimage array look like [R1, G1, B1, R2, G2, B2,...]
     {
           case 2:
                 B = (double) pixels[i]; break;
           case 1:
                 G = (double) pixels[i]; break;
           case 0:
                 R = (double) pixels[i];
                 PNG.plot(x, y, R, G, B);
                 if( x == width )
                 {
                       x=1;
                       y++;
                  }
                  else
                  { x++; }
                  break;
     }
}
PNG.close();

PS. I had also try libgd, but it seems only convert one image file (in the hard disk or in memory) to another format of image. But I think it still useful while you want to convert many PNG file to GIF format to create a GIF animate.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!