Saving a Generated Graphic to a PNG or JPEG File : PNG File « 2D Graphics GUI « Java

Saving a Generated Graphic to a PNG or JPEG File


import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;

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.fillRect(0, 0, width, height);
    g2d.fillOval(0, 0, width, height);

    RenderedImage rendImage = bufferedImage;

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

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



Related examples in the same category

1.PNG Encoder
2.PNG DecoderPNG Decoder
3.Draw an Image and save to png
4.PNG file format decoderPNG file format decoder
5.Encodes a java.awt.Image into PNG format
6.PngEncoder takes a Java Image object and creates a byte string which can be saved as a PNG file