BufferedImage - 获取灰度图像中像素的值

8

我有一个BufferedImage,使用这段代码将其转换为灰度图像。 我通常通过BufferedImage.getRGB(i,j)获取像素值,并分别获取R,G和B的每个值。 但是在灰度图像中如何获取像素值呢?

编辑:抱歉,忘记了转换。

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

你能发一下你用来转换的代码吗? - Sri Harsha Chilakapati
“使用这段代码。” 代码在哪里? - Alya'a Gamal
1个回答

23
如果您拥有RGB图像,那么您可以这样获取(红色,绿色,蓝色,灰度)值:
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);

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

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

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

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

想知道如何获取像素的 alpha 值。 - Sri Harsha Chilakapati
1
@SriHarshaChilakapati alpha 是 (rgb >> 24) & 0xFF - Kajzer
嗨,Alya,既然我已经有了它,我该如何使用新的灰度值创建RGB呢? - Kajzer
1
无法从灰度图像中获取RGB,因为您没有信息来执行此操作。要获取灰度值,您将使用3个值(R、G、B)来获取它。在获取灰度值后,您将失去这些值的信息。 - Alya'a Gamal
阅读这个答案 http://stackoverflow.com/questions/11226074/how-to-convert-16-bit-gray-scale-image-to-rgb-image-in-java ,并在谷歌上搜索了解为什么你不能进行此转换,或者至少返回您拥有的彩色图像。 - Alya'a Gamal
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接