Java: How to create dynamic PNGs, JPGs, GIFs.

Sometimes you need to create graphics, or compose images and have them saved as regular PNGs, JPEGs or GIFs.

Here’s a quick and dirty reference of how to do it with BufferedImages, Graphics2D and javax.imageio.*.
Very straightforward.

[java]
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

//1. Create a BufferedImage, in this case a simple 1024×768 using only RGB colors (you could use alpha for example)
BufferedImage bufferedImage = new BufferedImage(1024, 768, BufferedImage.TYPE_INT_RGB);

//2. Get a hold of a Graphics2D object to do all the painting and compositing on the BufferedImage
Graphics2D graphics = bufferedImage.createGraphics();

//3. Do the painting… in this case, I just filled with yellow
graphics.setColor(new Color(255,255,0));
graphics.fillRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight());

//4. Write the image
try {
ImageIO.write(bufferedImage, "png",new File("test.png"));
} catch (IOException e) {
e.printStackTrace();
}
[/java]

Leave a Reply

Your email address will not be published. Required fields are marked *