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

use*_*466 5 c opengl gdlib

我正在尝试全屏截图并将其保存为png.我在这里找到了一个代码并对其进行了一些修改.对于屏幕截图,我使用openGL和Glut以及在png中保存c的gd库.我得到的只是一个黑色的png,我无法弄清楚为什么.我在stackoverflow中搜索并发现了一些帖子,但不幸的是他们没有帮助.其中一个是使用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);
}
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

mru*_*cci 2

您可以使用魔鬼图像库并使用以下命令截屏:

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");
Run Code Online (Sandbox Code Playgroud)