gpt4 book ai didi

c++ - opengl - 显示的图像被剪切

转载 作者:搜寻专家 更新时间:2023-10-31 00:51:45 25 4
gpt4 key购买 nike

我正在尝试使用 OpenGL 显示 Microsoft CImage 库从磁盘读取的图像。

现在可以在窗口中大致看到图像,但显然有问题。图像是灰色的,并且被剪切了。我不知道问题出在哪里,因为每个像素都应该对应于 _data 中的插槽。

OpenGL 图像: opengl image

原图: original image

下面是我的代码:

int _w = 300;
int _h = 300;
GLubyte ***_data;

void init() {
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, _w, 0.0, _h);
}

void display() {
glClear(GL_COLOR_BUFFER_BIT);
glRasterPos2i(0, 0);
glDrawPixels(_w, _h, GL_RGB,
GL_UNSIGNED_BYTE, _data);
glFlush();
}

int main(int argc, char** argv) {
CImage img_handler;
img_handler.Load(_T("bg.jpg"));
_w = img_handler.GetWidth();
_h = img_handler.GetHeight();

COLORREF pixel;
_data = new GLubyte**[_h];

for (int y = 0; y < _h; y++) {
_data[_h-y-1] = new GLubyte*[_w];
for (int x = 0; x < _w; x++) {
pixel = img_handler.GetPixel(x, y);

_data[_h-y-1][x] = new GLubyte[3];
_data[_h-y][x][0] = (GLubyte)GetRValue(pixel);
_data[_h-y][x][1] = (GLubyte)GetGValue(pixel);
_data[_h-y][x][2] = (GLubyte)GetBValue(pixel);
}
}

glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH/*enable depth buffer*/);
glutInitWindowSize(_w, _h);
glutCreateWindow("test");

init();
glutDisplayFunc(display);
glutMainLoop();

return 0;
}

最佳答案

根据 this OpenGL doc在 glDrawPixels 上(添加了重点):

width x height pixels are read from memory, starting at location data. By default, these pixels are taken from adjacent memory locations, except that after all width pixels are read, the read pointer is advanced to the next four-byte boundary. The four-byte row alignment is specified by glPixelStore with argument GL_UNPACK_ALIGNMENT, and it can be set to one, two, four, or eight bytes.

请注意,您的颜色被定义为 3 个 GLuint 值 - 只有 3 个字节!每行像素包含 3 * 897 = 2691 字节。 2691 之后的下一个 4 的倍数是 2692,因此 glDrawPixels 的定义方式是,GL 在每一行后跳过一个字节。这就是图像被剪切以及为什么它显示为灰色的原因(如果放大,您会看到它不是灰色,而是每三行都有正确的颜色,中间的颜色色调偏移 120 度)。

解决此问题的方法是在调用 glDrawPixels 之前调用 glPixelStore。改变就足够了

glDrawPixels(_w, _h, GL_RGB,
GL_UNSIGNED_BYTE, _data);

glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glDrawPixels(_w, _h, GL_RGB,
GL_UNSIGNED_BYTE, _data);

此外,for 循环中的代码也不正确。 _h-y 应该是 _h-y-1 这样当 y=0 时你不会写在数组的边界之外,类似地当 y=_h-1 您写入数组的第 0 索引。

此外,请研究动态内存分配,而不是分配静态大小的数组。这将使您的代码不易发生访问冲突,即读取/写入实际上不属于您的内存,从而导致崩溃和其他问题。

关于c++ - opengl - 显示的图像被剪切,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54165935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com