java - 将 0-256 范围内的二维 int 数组转换为灰度 png?

标签 java file-io png javax.imageio grayscale

如何将二维整数数组转换为灰度 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 范围内的整数。

最佳答案

图像显示为蓝色,因为 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);
    }
}

关于java - 将 0-256 范围内的二维 int 数组转换为灰度 png?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5436931/

相关文章:

java - 是否可以在 Java 的方法中使用交替条件?

Java - 红、绿、蓝获取RGB

java - 在 Java 中用于写入文件的最好/最简单的类是什么?

c++键盘记录器无法正常工作

delphi - 如何在 Delphi 中将 PNG 图像的颜色从白色更改为黑色?

user-interface - BlackBerry - 在屏幕上绘制图像

java - Eclipse 构建路径嵌套错误

Java JUnit : Test selection of TreeViewer

java - Java中如何计算文件的哈希值?

node.js - OpenCV 断言失败类型不匹配