Convert 2d array from int from 0 to 256 to black and white png?

How to convert a 2D array from int to black and white 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 in blue. how can i do it in shades of gray.

image [] [] contains int from 0 to 256.

+5
source share
2 answers

The image goes out of blue because it setRGBexpects an RGB value, you only set the low byte, which is probably blue, which is why it is highlighted in 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);
    }
}
+3
source

I have never tried, but actually BufferedImage should be created even in grayscale mode:

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

All Articles