How to get the pixel value in a grayscale image

cherryduck picture cherryduck · Nov 21, 2011 · Viewed 9.6k times · Source

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!

Answer

msi picture msi · Nov 21, 2011

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.