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
  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 :
* Author :
* 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";;

    // 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.add(imageLabel);  // add the imageLabel to the frame
    frame.pack();  // set the window size to the size of the component (imageLabel)

No comments:

Post a Comment