java BufferedImage - 获取灰度颜色模型图片中像素的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15972490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:29:59  来源:igfitidea点击:

BufferedImage - getting the value of a pixel in grayscale color model picture

javapixelgrayscale

提问by Kajzer

I have an BufferedImagetransformed 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?

BufferedImage使用此代码转换为灰度。我通常得到BufferedImage.getRGB(i,j)R、G 和 B的像素值和 gor 每个值。但是如何获得灰度图像中的像素值?

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;
}

回答by Alya'a Gamal

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

如果你有 RGB 图像,那么你可以获得这样的 (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 the gray is the average for (r , g , b), like this:

灰色是 (r , g , b) 的平均值,如下所示:

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

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

但是如果您将 RGB 图像(24 位)转换为灰度图像(8 位):

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