1

我需要将灰度图像的像素强度数据的二维数组转换回图像。我试过这个:

BufferedImage img = new BufferedImage(
    regen.length, regen[0].length, BufferedImage.TYPE_BYTE_GRAY);  
for(int x = 0; x < regen.length; x++){
    for(int y = 0; y<regen[x].length; y++){
        img.setRGB(x, y, (int)Math.round(regen[x][y]));
    }
}
File imageFile = new File("D:\\img\\conv.bmp");
ImageIO.write(img, "bmp", imageFile);

其中“regen”是一个二维双数组。我得到一个相似但不准确的输出。很少有像素与它必须是完全相反的(对于值为 255 的像素,我得到黑色)。很少有灰色阴影也被视为白色。你能告诉我我在做什么错误吗?

4

2 回答 2

2

试试这样的代码:

public void writeImage(int Name) {
    String path = "res/world/PNGLevel_" + Name + ".png";
    BufferedImage image = new BufferedImage(color.length, color[0].length, BufferedImage.TYPE_INT_RGB);
    for (int x = 0; x < 200; x++) {
        for (int y = 0; y < 200; y++) {
            image.setRGB(x, y, color[x][y]);
        }
    }

    File ImageFile = new File(path);
    try {
        ImageIO.write(image, "png", ImageFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
于 2013-06-28T13:45:14.323 回答
1

BufferedImage.TYPE_BYTE_GRAY是无符号且无索引的。而且,

当具有非不透明 alpha 的数据存储在这种类型的图像中时,必须将颜色数据调整为非预乘形式并丢弃 alpha,如AlphaComposite文档中所述。

至少您需要排除符号扩展并屏蔽除第三个参数的最低八位以外的所有setRGB(). 重现问题的样本数据将是决定性的。

于 2012-05-26T16:18:14.447 回答