5

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.

wfbarksdale
  • 7,498
  • 15
  • 65
  • 88
  • I don't think you mean PNG since you aren't saving anything to a file of any format. You seem to be just drawing to the screen. – Sled Mar 25 '11 at 19:05

2 Answers2

3

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);
    }
}
yan
  • 20,644
  • 3
  • 38
  • 48
  • still blue, I actually want it to come out grayscale now that I think about it. – wfbarksdale Mar 25 '11 at 19:15
  • that should be coming out as grayscale.. are you sure you're setting the pixel to the new value and not the old one? – yan Mar 25 '11 at 19:17
  • Try passing `BufferedImage.TYPE_BYTE_GRAY` to the constructor and use the original code you had for the inner loop? – yan Mar 25 '11 at 19:20
  • im not sure what was wrong, but it randomly started working. Thanks! haha – wfbarksdale Mar 25 '11 at 19:26
0

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

new BufferedImage(100, 100, BufferedImage.TYPE_BYTE_GRAY);
Heisenbug
  • 38,762
  • 28
  • 132
  • 190