I have a BufferedImage which is of TYPE_BYTE_GRAY and I need to get the pixel value at x,y. I know I can't use getRGB as it returns the wrong color model so how do I go about it? Many thanks!
-
What do u mean by getRGB returns the wrong color model? what is returning it? – Arthur Neves Nov 21 '11 at 17:57
3 Answers
Get java.awt.image.Raster
from BufferedImage
by invoking getData()
method.
Then use
int getSample(int x, int y, int b)
on received object, where b is the color channel (where each color is represented by 8 bits).
For gray scale
b = 0.
For RGB image
b = 0 ==>> R channel,
b = 1 ==>> G channel,
b = 2 ==>> B channel.

- 2,609
- 18
- 20
-
Having looked at these methods this looks like the likely way to do it. It seems that int b is the "band" of the raster, I'm not overly sure what this means, and believe me I have looked online. I assume given that I have a grayscale image, it only has one band, and thus I want b to equal 0? – cherryduck Nov 21 '11 at 18:55
-
Fantastic thank you. I've implemented it and I'm getting much more sane results :-) – cherryduck Nov 21 '11 at 19:09
I guess what you looking for is the math to get a one number to represent the Gray scale in that RGB, there are few diff ways, follow some of them:
The lightness method averages the most prominent and least prominent colors: (max(R, G, B) + min(R, G, B)) / 2.
The average method simply averages the values: (R + G + B) / 3.
The luminosity method is a more sophisticated version of the average method. It also averages the values, but it forms a weighted average to account for human perception. We’re more sensitive to green than other colors, so green is weighted most heavily. The formula for luminosity is 0.21 R + 0.71 G + 0.07 B.
Reference : http://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/

- 11,840
- 8
- 60
- 73
-
1Okay thanks I'll look into that. However surely seeing as my image is ALREADY in grayscale there must be a simple way to get the pixel values straight from the image? – cherryduck Nov 21 '11 at 18:06
Provided that you have a BufferedImage named grayImg whose type is TYPE_BYTE_GRAY
int width = grayImg.getWidth();
int height = grayImg.getHeight();
byte[] dstBuff = ((DataBufferByte) grayImg.getRaster().getDataBuffer()).getData();
Then the gray value at (x,y) would simply be:
dstBuff[x+y*width] & 0xFF;

- 380
- 3
- 7