BufferedImage - Get a pixel value in a grayscale color model

I have BufferedImageconverted to grayscale using this code. Usually I get pixel values BufferedImage.getRGB(i,j)and gor each value for R, G and B. But how can I get the pixel value in the image in grayscale?

EDIT: sorry, forgot about the conversion.

static BufferedImage toGray(BufferedImage origPic) {
    BufferedImage pic = new BufferedImage(origPic.getWidth(), origPic.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
    Graphics g = pic.getGraphics();
    g.drawImage(origPic, 0, 0, null);
    g.dispose();
    return pic;
}
+5
source share
1 answer

if you have an RGB image so that you can get the values ​​(red, green, blue, gray):

BufferedImage img;//////read the image
int rgb = img.getRGB(x, y);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = (rgb & 0xFF);

and gray is the average of (r, g, b), for example:

int gray = (r + g + b) / 3;

but if you convert an RGB image (24 bit) to a gray image (8 bit):

int gray= img.getRGB(x, y)& 0xFF;/////////will be the gray value
+16
source

All Articles