There was an error in this gadget

Monday, January 26, 2009

Loading and Displaying an Image in Java

Here's a common task--loading an image file and displaying it in a window.

I'll be using this program as a basis for further two dimensional graphics exercises, so give it a try and play around with it.

First, we need to get a picture to use. I use a picture of Duke, the Java mascot, from

If you want to run the program as I present it, download the image and save it into the same directory that yor java program will be in. If you want to use your own image, replace the file name Duke_Blocks.gif with the name of your image file, and make sure the image is in the same directory as your java program.

The only somewhat tricky part is that we're using a Toolkit method to get the image. Take a look at the Java API reference to learn more about the Toolkit. (The Toolkit object is part of the java.awt package. So select "java.awt" in the top left frame of the API reference webpage to make finding Toolkit in the lower left frame easier.)

In this program, we scale and position the image in our window. In future programs, we'll convert the image to a Java2D object (which is really easy) so that we can do other things, like rotate it and use it as a sprite.

Here's the program:

  This program loads and displays an image from a file.

  updated 20Feb2009 by mag to incorporate suggestions
  by mazing and iofthestorm on digg.

// Import the basic graphics classes.
import java.awt.*;
import javax.swing.*;

public class ShowImage extends JPanel{
  Image image; // Declare a name for our Image object.

// Create a constructor method
  public ShowImage(){
   // Load an image file into our Image object.
   // This file has to be in the same
   // directory as ShowImage.class.
   image = Toolkit.getDefaultToolkit().getImage("Duke_Blocks.gif");

// The following methods are instance methods.

/* Create a paintComponent() method to override the one in
This is where the drawing happens.
We don't have to call it in our program, it gets called
automatically whenever the panel needs to be redrawn,
like when it it made visible or moved or whatever.
  public void paintComponent(Graphics g){

   // Draw our Image object.
   g.drawImage(image,50,10,200,200, this); // at location 50,10
     // 200 wide and high

  public static void main(String arg[]){
   JFrame frame = new JFrame("ShowImage");

   ShowImage panel = new ShowImage();