Convert a 2D array of int ranging from 0-256 into

2019-06-22 13:05发布

How can I convert a 2D array of ints into a grayscale png. right now I have this:

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

but the image comes out blue. how can I make it a grayscale.

image[][] contains ints ranging from 0-256.

2条回答
别忘想泡老子
2楼-- · 2019-06-22 13:33

The image comes out blue because setRGB is expecting an RGB value, you're only setting the low byte, which is probably Blue, which is why it's coming out all blue.

Try:

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);
    }
}
查看更多
Lonely孤独者°
3楼-- · 2019-06-22 13:49

I never tried but actually BufferedImage should be instantiated even in grey scale mode:

new BufferedImage(100, 100, BufferedImage.TYPE_BYTE_GRAY);
查看更多
登录 后发表回答