2

I am trying to retrieve a color in OpenGL ES with glReadPixels. I set my objects' colors with float[], e.g. {0.0f,0.5f,0.2f,1.0f} How can I convert the glReadPixels value to the same float[], since it's unsigned byte?

Setting the color:

gl.glColor4f(color[0], color[1], color[2], color[3]);

Getting the color:

ByteBuffer buf = ByteBuffer.allocate(4);
buf.order(ByteOrder.nativeOrder());

gl.glReadPixels((int) mx, height - (int) my, 1, 1, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, buf);
byte result[] = buff.array();

I don't know if this has been asked/answered already, but I just haven't found a solution and I've been trying it for a good while.

Urho
  • 2,232
  • 1
  • 24
  • 34
  • Store each color value in a float, then divide it by 255.0 and you've got it. Note that there will be rounding error. For example, your `.5` will probably be more like `.498` now. – David Schwartz Jul 14 '12 at 13:03
  • @DavidSchwartz well if I set the color to {1,0,0,0) and divide the result[0] by 255.0, I get -0.003921569 – Urho Jul 14 '12 at 13:46
  • 1
    @DavidSchwartz: It's a bit more complicated, see here: http://kaba.hilvi.org/programming/range/index.htm – datenwolf Jul 14 '12 at 14:29
  • @datenwolf I don't know how I'm supposed to use that information. Tried implementing that code snippet in Java, but it didn't quite work. Isn't there any simpler way? – Urho Jul 15 '12 at 19:42

2 Answers2

2

The reason you get byte / 255.f = -0.0039 is because the byte you get from the bytebuffer is a signed value in java.

While OpenGL returns the unsigned value 255 = 0xFF, java interprets this as signed, in which 0xFF = -1.

Take the byte you get (result[0]), cast it to an int int resultInt = ((int)result[0]) & 0xFF, and then divide that by 255. You should get a value close to 1.

Tim
  • 35,413
  • 11
  • 95
  • 121
0

Use ByteBuffer.asFloatBuffer() to convert it from bytes to floats.

Oskar
  • 1,321
  • 9
  • 19
  • Nope that does not quite work, or I just don't know what to do with it. I cannot then use FloatBuffer.array() and if I use FloatBuffer.get() it returns a value like -1.7014636e38 – Urho Jul 15 '12 at 14:08
  • I don't know how that is supposed to help. Tried it, but now it just returns zero. – Urho Jul 15 '12 at 16:10
  • That's odd. I had the same issue a while back and this seemed to fix it. Sorry. – Oskar Jul 19 '12 at 10:20