Saving a Generated Graphic to a PNG or JPEG File

This example demonstrates how to create a generated image and save it as a PNG or JPEG file.
// Create an image to save RenderedImage rendImage = myCreateImage(); // Write generated image to a file try { // 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) { } // Returns a generated image. public 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(); // Draw graphics 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; }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.