A Java program to open, read, and display an image file

In an earlier blog post I shared a small piece of Java code that shows how to place an image on a JLabel. When I just looked back at that post I thought it would be cool if I showed a complete Java program that could read an image from the local filesystem, create a BufferedImage from that image file, create an ImageIcon from that image, place that ImageIcon on a JLabel, and finally show the image in a JFrame.

Java program to show an image in a JFrame

To that end, here's the complete Java Swing source code for a program that does all those things, eventually displaying the image you provide in a JFrame:

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

/**
 * A Java class to demonstrate how to load an image from disk with the
 * ImageIO class. Also shows how to display the image by creating an
 * ImageIcon, placing that icon an a JLabel, and placing that label on
 * a JFrame.
 * 
 * @author alvin alexander, alvinalexander.com
 */
public class ImageDemo
{
  public static void main(String[] args) throws Exception
  {
    new ImageDemo(args[0]);
  }

  public ImageDemo(final String filename) throws Exception
  {
    SwingUtilities.invokeLater(new Runnable()
    {
      public void run()
      {
        JFrame editorFrame = new JFrame("Image Demo");
        editorFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
        BufferedImage image = null;
        try
        {
          image = ImageIO.read(new File(filename));
        }
        catch (Exception e)
        {
          e.printStackTrace();
          System.exit(1);
        }
        ImageIcon imageIcon = new ImageIcon(image);
        JLabel jLabel = new JLabel();
        jLabel.setIcon(imageIcon);
        editorFrame.getContentPane().add(jLabel, BorderLayout.CENTER);

        editorFrame.pack();
        editorFrame.setLocationRelativeTo(null);
        editorFrame.setVisible(true);
      }
    });
  }
}

To compile this program

To compile this program, simply download it to your computer, save it with the filename ImageDemo.java, and then compile it with the following command:

javac ImageDemo.java

Because I did not specify a package name at the beginning of the class definition, you can do this from your current directory.

To run the program

After you compile the program, you can run it like this:

java ImageDemo path-to-your-image

For instance, if you have a file named foo.jpg in the current directory, you will run this program like this:

java ImageDemo foo.jpg

Or, if you're on a Mac or Unix system and the same file is in the tmp directory, you will run the program like this:

java ImageDemo /tmp/foo.jpg

This is a simple program, but if you're new to Java and working with images, I hope having a complete program like this is helpful.