Create image file from graphics object

With this tutorial we shall show you how to create an image file from graphics object. This is particularly useful when you want to create your own images out of custom made graphics.

Creating an image file from graphics object requires that you:

  • Create a new BufferedImage.
  • Create a Graphics2D using createGraphics.
  • Create a new File("myimage.png").
  • Use ImageIO.write(bufferedImage, "jpg", file) to create the image.

Let’s see the code:

package com.javacodegeeks.snippets.desktop;

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

import javax.imageio.ImageIO;

public class CreateImageFileFromGraphicsObject {

	public static void main(String[] args) throws IOException {

		int width = 250;
	    int height = 250;

	    // Constructs a BufferedImage of one of the predefined image types.
	    BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

	    // Create a graphics which can be used to draw into the buffered image
	    Graphics2D g2d = bufferedImage.createGraphics();

	    // fill all the image with white
	    g2d.fillRect(0, 0, width, height);

	    // create a circle with black
	    g2d.fillOval(0, 0, width, height);

	    // create a string with yellow
	    g2d.drawString("Java Code Geeks", 50, 120);

	    // Disposes of this graphics context and releases any system resources that it is using. 

	    // Save as PNG
	    File file = new File("myimage.png");
	    ImageIO.write(bufferedImage, "png", file);

	    // Save as JPEG
	    file = new File("myimage.jpg");
	    ImageIO.write(bufferedImage, "jpg", file);



This was an example on how to create image file from graphics object.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
8 months ago

it very eaasy to learn

Back to top button