Saturday, March 19, 2011

How to read a jpeg file and display it ?

First, you need to have a jpeg file.

You may use the file "macteki.jpg" created in this post :
How to write image to jpeg file ?

Steps to display a jpeg file :
  1. Read image jpeg file using ImageIO.read()
  2. Create an icon object from the image.
  3. Create a JLabel object to display the icon.
  4. Create a JFrame to hold the JLabel.

Make sure the file "macteki.jpg" exists before running the sample.
Since this sample doesn't support scrollbar, don't use a file with dimension larger than your screen resolution.

Comments are welcome !

/******************************************************************************
* File : JpegReader.java
* Author : http://java.macteki.com
* Description :
*   Read a image from jpeg file and display it in a frame
* Tested with : JDK 1.6
******************************************************************************/

public class JpegReader {

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

    // read the image to a Jpeg File
    java.awt.image.BufferedImage image= null;
    String jpeg_file="macteki.jpg";
    image=javax.imageio.ImageIO.read(new java.io.File(jpeg_file));

    // create a image label
    javax.swing.ImageIcon icon=new javax.swing.ImageIcon(image);
    javax.swing.JLabel imageLabel=new javax.swing.JLabel(icon);

    // create frame
    javax.swing.JFrame frame=new javax.swing.JFrame();
    frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);    

    frame.setTitle(jpeg_file);
   
    frame.add(imageLabel);  // add the imageLabel to the frame
    frame.pack();  // set the window size to the size of the component (imageLabel)
    frame.setVisible(true); 
  }
}

No comments:

Post a Comment