用glReadPixels读取纹理字节?

Ger*_*eri 13 textures opengl-es glreadpixels ios

我想将原始纹理数据转储到磁盘上(稍后再回读),我不确定glReadPixel会从当前绑定的纹理中读取.

如何从纹理中读取缓冲区?

ger*_*lez 34

glReadPixels函数从帧缓冲区读取,而不是纹理.要读取纹理对象,必须使用glGetTexImage,它在OpenGL ES中不可用 :(

如果要从纹理中读取缓冲区,则可以将其绑定到FBO(FrameBuffer对象)并使用glReadPixels:

//Generate a new FBO. It will contain your texture.
glGenFramebuffersOES(1, &offscreen_framebuffer);
glBindFramebufferOES(GL_FRAMEBUFFER_OES, offscreen_framebuffer);

//Create the texture 
glGenTextures(1, &my_texture);
glBindTexture(GL_TEXTURE_2D, my_texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,  width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

//Bind the texture to your FBO
glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, my_texture, 0);

//Test if everything failed    
GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
if(status != GL_FRAMEBUFFER_COMPLETE_OES) {
    printf("failed to make complete framebuffer object %x", status);
}
Run Code Online (Sandbox Code Playgroud)

然后,当你想从纹理中读取时,你只需要调用glReadPixels:

//Bind the FBO
glBindFramebufferOES(GL_FRAMEBUFFER_OES, offscreen_framebuffer);
// set the viewport as the FBO won't be the same dimension as the screen
glViewport(0, 0, width, height);

GLubyte* pixels = (GLubyte*) malloc(width * height * sizeof(GLubyte) * 4);
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);

//Bind your main FBO again
glBindFramebufferOES(GL_FRAMEBUFFER_OES, screen_framebuffer);
// set the viewport as the FBO won't be the same dimension as the screen
glViewport(0, 0, screen_width, screen_height);
Run Code Online (Sandbox Code Playgroud)

  • 一旦删除了所有OES后缀,我就可以确认这在Mac上也有效 (2认同)