roberto
roberto

Reputation: 89

Using glReadPixels for reading pixel data of a texture image

Can you use glReadPixels to read pixel data from a texture image?

My code for generating a texture image is:

gl.glTexImage2D( GL2.GL_TEXTURE_2D, 0, GL2.GL_RGBA, width, height, 0, GL2.GL_RGBA, GL2.GL_UNSIGNED_BYTE, ByteBuffer.wrap( pixels ) );

The variable pixels contain the pixel values of an image. Then I use glReadPixels to try to read the pixel data of the texture image just created. My code for using glReadPixels is:

    FloatBuffer buffer = FloatBuffer.allocate( 4 );
    for ( int row = 0, col; row < height; row++ ) {
        for ( col = 0; col < width; col++ ) {
            gl.glReadPixels( col, row, 0, 0, GL2.GL_RGBA, GL2.GL_FLOAT, buffer );
            System.out.print( buffer.get( 0 ) );
        }
        System.out.println();
    }

The problem is I keep getting a value of 0.0, I'm wondering if the texture image is stored in the framebuffer since glReadPixels read data from the framebuffer?

Upvotes: 2

Views: 2486

Answers (2)

user2191637
user2191637

Reputation: 21

I think the error in this line.

gl.glReadPixels( col, row, 0, 0, GL2.GL_RGBA, GL2.GL_FLOAT, buffer );

Try the following instead

gl.glReadPixels( col, row, 1, 1, GL2.GL_RGBA, GL2.GL_FLOAT, buffer );

Also it's better to read the whole image at the same time. Do not forget to allocate needed buffer size.

gl.glReadPixels( col, row, width, height, GL2.GL_RGBA, GL2.GL_FLOAT, buffer );

Upvotes: 2

Sven Gothel
Sven Gothel

Reputation: 141

glReadPixels reads from the default framebuffer (GL_BACK for dbl buffering), yes. To read a texture, you may want to use FBO w/ attached texture colorbuffer. Then set the FBO active and you can use glReadPixels. Since FBO is pretty complicated to tame and you are using JOGL, I link you to an offscreen unit test which uses GLFBODrawable/FBObject internally and uses glReadPixels to perform the snapshot. Ofc .. you would need to walk a bit through the code and it's new API.

Upvotes: 5

Related Questions