使用openGL截取屏幕截图并将其另存为png

我正在尝试全屏截图并将其保存为png。 我在这里找到了一个代码并对其进行了一些修改。 对于屏幕截图,我使用openGL和Glut以及在png中保存c的gd库。 我得到的只是一个黑色的png,我无法弄清楚为什么。 我在stackoverflow中搜索并发现了一些post,但不幸的是他们没有帮助。 其中一个是使用glReadBuffer(GL_FRONT); 而不是glReadBuffer(GL_BACK); 我尝试了两个都没有成功。 这是我的代码:

int SVimage2file(char *filename){ int width = glutGet(GLUT_SCREEN_WIDTH); int height = glutGet( GLUT_SCREEN_HEIGHT); FILE *png; GLubyte *OpenGLimage, *p; gdImagePtr image; unsigned int r, g, b; int i,j,rgb; png = fopen(filename, "wb"); if (png == NULL) { printf("*** warning: unable to write to %s\n",filename); return 1; } OpenGLimage = (GLubyte *) malloc(width * height * sizeof(GLubyte) * 3); if(OpenGLimage == NULL){ printf("error allocating image:%s\n",filename); exit(1); } printf("Saving to: %s .\n",filename); glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadBuffer( GL_FRONT); glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, OpenGLimage); p = OpenGLimage; image = gdImageCreateTrueColor(width,height); for (i = height-1 ; i>=0; i--) { for(j=0;j<width;j++){ r=*p++; g=*p++; b=*p++; rgb = (r<<16)|(g<<8)|b; //printf("the rgb color %d\n", rgb ); gdImageSetPixel(image,j,i,rgb); } } gdImagePng(image,png); fclose(png); gdImageDestroy(image); } 

我错过了什么?

你可以使用魔鬼图像库并采取screeshot:

 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"); 

如果你不拒绝使用C ++库,你应该尝试PNGwriter ! 它逐像素地写入图片及其RGB值。 由于PNGwriter从左下角开始形成左上角,而glReadPixels()从左下角开始,你的代码同时如下:

 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 

PS。 我也尝试过libgd,但它似乎只将一个图像文件(在硬盘或内存中)转换为另一种格式的图像。 但我认为当你想将许多PNG文件转换为GIF格式以创建GIF动画时,它仍然有用。