I have some code that generates an image (a 2-d array of 8-bit grayscale values, but could be anything).
I want to export this image as a .png file.
Which path should I follow? I'm really confused by javax.imageio and java.awt.Image.
Actually you need java.awt.image.BufferedImage
as the image object, so you can use setRGB
to set RGB value in a given (x,y) coordinate. But to save you image as file you might want to use javax.imageio.ImageIO
.
Here is a small example to emphasize how to use them both:
int[][] img = getImage();
int xLenght = img.length;
int yLength = img[0].length;
//java.awt.image.BufferedImage:
BufferedImage bi = new BufferedImage(xLenght, yLength, BufferedImage.TYPE_INT_BGR);
for(int x = 0; x < xLenght; x++) {
for(int y = 0; y < yLength; y++) {
int rgbPixel = (int)img[x][y]<<16 | (int)img[x][y] << 8 | (int)img[x][y];
bi.setRGB(x, y, rgb);
}
}
try {
// javax.imageio.ImageIO:
ImageIO.write(bi, "myImage", new File("myImage.png"));
} catch (IOException e) {
e.printStackTrace();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.