Save a Generated Graphic to a PNG File in Java

Description

The following code shows how to save a Generated Graphic to a PNG File.

Example


import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
/*from   w  ww.j  a  v  a  2s. c  om*/
import javax.imageio.ImageIO;

public class Main {
  public static void main(String[] argv) throws Exception {
    int width = 100;
    int height = 100;

    BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    Graphics2D g2d = bufferedImage.createGraphics();

    g2d.setColor(Color.white);
    g2d.fillRect(0, 0, width, height);
    g2d.setColor(Color.black);
    g2d.fillOval(0, 0, width, height);

    g2d.dispose();
    RenderedImage rendImage = bufferedImage;

    File file = new File("newimage.png");
    ImageIO.write(rendImage, "png", file);

  }

}




















Home »
  Java Tutorial »
    Graphics »




Animation
BufferedImage
Color
Font
Gradient
Graphics Settings
Image
Mouse Draw
Print
Shape
Text
Transform