为啥我设置的opengl视口宽度变小了,读取像素不对齐?
Posted
技术标签:
【中文标题】为啥我设置的opengl视口宽度变小了,读取像素不对齐?【英文标题】:Why the width of the opengl viewport I set is smaller and the reading pixels are not aligned?为什么我设置的opengl视口宽度变小了,读取像素不对齐? 【发布时间】:2021-11-09 14:54:18 【问题描述】:代码如下(使用enter link description here的demo)渲染字形
Luint rbcolor;
glGenRenderbuffers(1, &rbcolor);
glBindRenderbuffer(GL_RENDERBUFFER, rbcolor);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RED, width, height);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
GLuint rbds;
glGenRenderbuffers(1, &rbds);
glBindRenderbuffer(GL_RENDERBUFFER, rbds);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_STENCIL, width, height);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
GLuint fbo;
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbcolor);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbds);
//render
while(...)
...
glviewport(0,0,width,height);
...
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glReadPixels(0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, picbuf);
// render in screen
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// Flipping the picture vertically
uint8_t *row_swap = (uint8_t*) malloc( width );
for ( int iy = 0; iy < height / 2; ++iy )
uint8_t* row0 = picbuf + iy * width;
uint8_t* row1 = picbuf + ( height - 1 - iy ) * width;
memcpy( row_swap, row0, width );
memcpy( row0, row1, width );
memcpy( row1, row_swap, width );
free( row_swap );
// Saving the picture
std::string png_filename = res_filename + ".png";
if ( !stbi_write_png( png_filename.c_str(), width, height, 1, picbuf, 0) )
std::cout << "Error writing png file." << std::endl;
exit( 1 );
当我尝试将视口宽度设置为恰到好处的渲染文本大小时,我收到错误 malloc check header error 或获取图像未对齐 Misplaced picture,但是当我设置的宽度足够大,比如1024,图片就可以正常显示了。
【问题讨论】:
【参考方案1】:当您从 GPU 内存读取像素时,您必须设置 GL_PACK_ALIGNMENT
而不是 GL_UNPACK_ALIGNMENT
(请参阅 glPixelStore
):
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, picbuf);
【讨论】:
好的,谢谢!以上是关于为啥我设置的opengl视口宽度变小了,读取像素不对齐?的主要内容,如果未能解决你的问题,请参考以下文章