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++){
开发者_如何学JAVA 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.
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);
}
}
I never tried but actually BufferedImage should be instantiated even in grey scale mode:
new BufferedImage(100, 100, BufferedImage.TYPE_BYTE_GRAY);
精彩评论