Search code examples
javaimagepixelgrayscale

How to get the pixel value in a grayscale image


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!


Solution

  • 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.