glGetTexImage returns curious results

Started by Cornix, August 01, 2013, 19:33:58

Previous topic - Next topic

Cornix

Hello.

I am trying to read the contents of a texture. It works but not quite as I expected.
My code looks somewhat like this:
byte[] pixels = new byte[width * height * 4];
		ByteBuffer buffer = ByteBuffer.allocateDirect(pixels.length).order(ByteOrder.nativeOrder());
		GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture_id);
		GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
		buffer.get(pixels);
		System.out.println(Arrays.toString(pixels));

However, the array pixels is filled only with the values 0 and -1.
The texture is an image with only white and transparent pixels.

What am I doing wrong?

Thanks in advance.

quew8

You're not doing anything wrong. The data you get out of OpenGL is in the form of unsigned bytes, but Java only knows how to interpret signed bytes so it is screwing up the output.

A little bitwise op will solve the problem.

for(int i = 0; i < pixels.length; i++) {
    System.out.println( pixels[i] & 0xFF );
}


and you thought you could escape the For Loop

Cornix

Thanks for that information.

I was previously trying to get the data as floats but for some reason the program crashed anytime I tried.
It looked like this:
float[] pixels = new float[width * height * 4];
		ByteBuffer buffer = ByteBuffer.allocateDirect(pixels.length).order(ByteOrder.nativeOrder());
		FloatBuffer fBuffer = buffer.asFloatBuffer();
		GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture_id);
		GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, GL11.GL_FLOAT, fBuffer);
		fBuffer.get(pixels);
		System.out.println(Arrays.toString(pixels));

quew8

Hmm, nothing there stands out as being wrong.

When you say crash, was it a native crash (Like Illegal Memory Address or whatever its called), or a java exception? Either way I'd be interested  to see the stack trace.

Cornix

I noticed the mistake. I had to multiply by 4 again (float byte size) when creating the ByteBuffer.
It was a native crash I got.

Now it works, thanks alot.