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

wfbarksdale picture wfbarksdale · Mar 25, 2011 · Viewed 8.9k times · Source

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.

Answer

yan picture yan · Mar 25, 2011

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