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

♀尐吖头ヾ 提交于 2019-12-23 10:14:25

问题


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.


回答1:


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



回答2:


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

new BufferedImage(100, 100, BufferedImage.TYPE_BYTE_GRAY);


来源:https://stackoverflow.com/questions/5436931/convert-a-2d-array-of-int-ranging-from-0-256-into-a-grayscale-png

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!