5

如何将二维整数数组转换为灰度 png。现在我有这个:

    BufferedImage theImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
    for(int y = 0; y<100; y++){
        for(int x = 0; x<100; x++){
            theImage.setRGB(x, y, image[y][x]);
        }
    }
    File outputfile = new File("saved.bmp");
    ImageIO.write(theImage, "png", outputfile);

但图像是蓝色的。我怎样才能使它成为灰度。

image[][] 包含范围从 0-256 的整数。

4

2 回答 2

3

图像显示为蓝色,因为setRGB需要一个 RGB 值,您只设置了低字节,可能是蓝色,这就是它显示为蓝色的原因。

尝试:

BufferedImage theImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
for(int y = 0; y<100; y++){
    for(int x = 0; x<100; x++){
        int value = image[y][x] << 16 | image[y][x] << 8 | image[y][x];
        theImage.setRGB(x, y, value);
    }
}
于 2011-03-25T19:09:50.857 回答
0

我从未尝试过,但实际上即使在灰度模式下也应该实例化 BufferedImage:

new BufferedImage(100, 100, BufferedImage.TYPE_BYTE_GRAY);
于 2011-03-25T19:19:20.847 回答