简体   繁体   English

将Java中的2D数组转换为Image

[英]Convert 2D array in Java to Image

I need to convert a 2D array of pixel intensity data of a grayscale image back to an image. 我需要将灰度图像的像素强度数据的2D阵列转换回图像。 I tried this: 我试过这个:

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

where "regen" is a 2D double array. 其中“regen”是2D双数组。 I am getting an output which is similar but not exact. 我得到一个相似但不完全的输出。 There are few pixels that are totally opposite to what it must be (I get black color for a pixel which has a value of 255). 有几个像素与它必须完全相反(我得到一个值为255的像素的黑色)。 Few gray shades are also taken as white. 很少有灰色阴影也被视为白色。 Can you tell me what is the mistake that I am doing? 你能告诉我我在做什么错吗?

Try some code like this: 试试这样的代码:

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

BufferedImage.TYPE_BYTE_GRAY is unsigned and non-indexed. BufferedImage.TYPE_BYTE_GRAY是无符号BufferedImage.TYPE_BYTE_GRAY编入索引的。 Moreover, 此外,

When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the AlphaComposite documentation. 当具有非不透明alpha的数据存储在此类型的图像中时,必须将颜色数据调整为非预乘形式并丢弃alpha,如AlphaComposite文档中所述。

At a minimum you need to preclude sign extension and mask off all but the lowest eight bits of the third parameter to setRGB() . 至少你需要排除符号扩展并屏蔽除第三个参数的最低8位以外的所有内容到setRGB() Sample data that reproduces the problem would be dispositive. 重现问题的样本数据将是决定性的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM