Saving a Generated Graphic to a PNG or JPEG File - Java 2D Graphics

Java examples for 2D Graphics:PNG

Description

Saving a Generated Graphic to a PNG or JPEG File

Demo Code


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

import javax.imageio.ImageIO;

public class Main {
  public static void main(String[] args) {
    // Create an image to save
    RenderedImage rendImage = myCreateImage();

    try {/*from   w ww. j ava  2s .  com*/
      // Save as PNG
      File file = new File("newimage.png");
      ImageIO.write(rendImage, "png", file);

      // Save as JPEG
      file = new File("newimage.jpg");
      ImageIO.write(rendImage, "jpg", file);
    } catch (IOException e) {
    }
  }

  public static RenderedImage myCreateImage() {
    int width = 100;
    int height = 100;

    // Create a buffered image in which to draw
    BufferedImage bufferedImage = new BufferedImage(width, height,
        BufferedImage.TYPE_INT_RGB);

    // Create a graphics contents on the buffered image
    Graphics2D g2d = bufferedImage.createGraphics();

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

    // Graphics context no longer needed so dispose it
    g2d.dispose();

    return bufferedImage;
  }
}

Related Tutorials