Search code examples
c++opengl-estexturesopengl-es-2.0framebuffer

Saving a glTexImage2D to the file system for inspection


I have a 3D graphics application that is exhibiting bad texturing behavior (specifically: a specific texture is showing up as black when it shouldn't be). I have isolated the texture data in the following call:

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, fmt->gl_type, data)

I've inspected all of the values in the call and have verified they aren't NULL. Is there a way to use all of this data to save to the (Linux) filesystem a bitmap/png/some viewable format so that I can inspect the texture to verify it isn't black/some sort of garbage? It case it matters I'm using OpenGL ES 2.0 (GLES2).


Solution

  • If you want to read the pixels from a texture image in OpenGL ES, then you have to attach the texture to a framebuffer and read the color plane from the framebuffer by glReadPixels

    GLuint textureObj = ...; // the texture object - glGenTextures  
    
    GLuint fbo;
    glGenFramebuffers(1, &fbo); 
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureObj, 0);
    
    int data_size = mWidth * mHeight * 4;
    GLubyte* pixels = new GLubyte[mWidth * mHeight * 4];
    glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
    
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glDeleteFramebuffers(1, &fbo);
    

    All the used functions in this code snippet are supported by OpenGL ES 2.0.

    Note, in desktop OpenGL there is glGetTexImage, which can be use read pixel data from a texture. This function doesn't exist in OpenGL ES.

    To write an image to a file (in c++), I recommend to use a library like STB library, which can be found at GitHub - nothings/stb.

    To use the STB library library it is sufficient to include the header files (It is not necessary to link anything):

    #define STB_IMAGE_WRITE_IMPLEMENTATION
    #include <stb_image_write.h>
    

    Use stbi_write_bmp to write a BMP file:

    stbi_write_bmp( "myfile.bmp", width, height, 4, pixels );
    

    Note, it is also possible to write other file formats by stbi_write_png, stbi_write_tga or stbi_write_jpg.