8

I have an BufferedImage transformed to grayscale using this code. I usually got the pixel values by BufferedImage.getRGB(i,j) and the gor each value for R, G, and B. But how do I get the value of a pixel in a grayscale image?

EDIT: sorry, forgot abou 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;
}
Kajzer
  • 2,138
  • 3
  • 32
  • 46

1 Answers1

23

if you have RGB image so you can get the (Red , green , blue , Gray) values like that:

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 the gray is the average for (r , g , b), like this:

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

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

int gray= img.getRGB(x, y)& 0xFF;/////////will be the gray value
Alya'a Gamal
  • 5,624
  • 19
  • 34
  • Interested in knowing how to get alpha value of a pixel – Sri Harsha Chilakapati Apr 12 '13 at 13:29
  • 1
    @SriHarshaChilakapati alpha is (rgb >> 24) & 0xFF – Kajzer Apr 12 '13 at 13:30
  • Hey Alya, now that I have that, how can I create the RGB with a new Gray value? – Kajzer Apr 12 '13 at 14:27
  • 1
    it's impoosiple to get RGB from Gray image , because you haven't information to do it , to get gray so you will use the 3 values to get it (R, G , B) after you get the gray , you will lose the values information – Alya'a Gamal Apr 12 '13 at 14:29
  • Read this answers http://stackoverflow.com/questions/11226074/how-to-convert-16-bit-gray-scale-image-to-rgb-image-in-java , and search on google to understand why you can't make this conversion , or at least return the colored image as you have – Alya'a Gamal Apr 12 '13 at 14:37
  • Is there any other way to set the new value of a pixel in a grayscaled image? – Kajzer Apr 12 '13 at 16:07
  • what do you mean?? you need to return the gray image??!! – Alya'a Gamal Apr 12 '13 at 16:10
  • Yes, I needed to return the gray image. To set the new RGB, I just used the same value for the RED, GREEN, and BLUE when creating a new RGB. Worked fine. – Kajzer Apr 17 '13 at 10:08