简体   繁体   中英

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

At a minimum you need to preclude sign extension and mask off all but the lowest eight bits of the third parameter to setRGB() . Sample data that reproduces the problem would be dispositive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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