C语言中的GLUT屏幕截图 [英] GLUT screen capture in C

查看:102
本文介绍了C语言中的GLUT屏幕截图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在GLUT中进行屏幕捕获,但遇到了一些问题. glReadPixels()似乎用

I'm trying to do a screen capture in GLUT and I'm having a bit of an issue. glReadPixels() seems to crash my program with an

Access violoation writing location 0x00000000

奇怪的是,文件是在项目的根目录中创建的,显然是空的.我迅速设置了一些printf命令,似乎在glReadPixels()方法期间每次代码都会崩溃.

The thing that is weird is the file is created in the root of the project, and is obviously empty. I set up some printf commands quickly and it appears that the code crashes each time during the glReadPixels() method.

我觉得问题可能出在像素"变量上.我在找出正确的定义方法时遇到麻烦,因此无法将RGB值写入其中.

I feel the issue maybe the variable 'pixels'. Im having trouble figuring out the correct way to define this so that the RGB values are written to it.

任何提示将不胜感激.

void savePPM(char ppmFileName[]){
    int width = glutGet(GLUT_WINDOW_WIDTH);
    int height = glutGet(GLUT_WINDOW_HEIGHT);
    char *pixels = NULL;

    glReadPixels(0,0, width, height, GL_RGB, GL_UNSIGNED_BYTE ,pixels);

    ppmFile = fopen(ppmFileName, "wb");

    fprintf(ppmFile, "P6\n");
    fprintf(ppmFile, "%d %d\n", width, height);
    fprintf(ppmFile, "255\n");
    fwrite(pixels, 1, width*height*3, ppmFile);

    fclose(ppmFile);
    free(pixels);
}

推荐答案

glReadPixels不会为您分配内存,它只是将像素数据存储在您在最后一个参数中提供的缓冲区中.您为其提供了NULL指针,因此它试图将数据存储在地址0处,这显然会导致访问冲突.

glReadPixels doesn't allocate memory for you, it merely stores the pixel data in the buffer that you give it in the last parameter. You're giving it a NULL pointer, so it's trying to store data at address 0, which obviously results in an access violation.

您需要首先分配内存,将其传递给glReadPixels,然后再对其进行分配.您还需要确保调用 glPixelStorei 以确保像素数据打包后返回而没有任何填充(或者,您可以单独写入每条扫描线,但这需要一些额外的工作).

You need to allocate the memory first, pass it to glReadPixels, and then deallocate it. You also need to make sure that you call glPixelStorei to ensure that the pixel data is returned packed, without any padding (alternatively, you can write each scan line individually, but that requires a little extra effort).

例如:

// Error checking omitted for expository purposes
char *pixels = malloc(width * height * 3);  // Assuming GL_RGB
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(..., pixels);
...
fwrite(pixels, ...);
...
free(pixels);

这篇关于C语言中的GLUT屏幕截图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆