/*
 * @(#) JPEGViewer.java 1.0 99/10/4
 * Copyright (c) 1999 Larry Rodrigues
 */
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;

import com.sun.image.codec.jpeg.*;
 /** View a JPEG image
   * @version 1.0  10 April 1999
   * @author Lawrence Rodrigues
   */
public class JPEGViewer extends JPanel {
   ImagePanel viewer;

   public static BufferedImage readAsBufferedImage(String filename) {
      try {
         FileInputStream fis = new FileInputStream(filename);
         JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(fis);
         BufferedImage bi = decoder.decodeAsBufferedImage();
         return bi;
      } catch(Exception e) {
         System.out.println(e);
         return null;
      }
   }

   public void loadAndDisplay(String filename){
      BufferedImage img = loadImage(filename);
      displayImage(img);
   }

   public BufferedImage loadImage(String filename){
      return readAsBufferedImage(filename);
   }

   public void displayImage(BufferedImage img) {
      int width = img.getWidth();
      int height = img.getHeight();
      displayImage(img, width, height);
   }

   public void displayImage(BufferedImage img, int width, int height) {
      JFrame fr = new JFrame();
      fr.addWindowListener(
         new WindowAdapter() {
            public void windowClosing(WindowEvent e){
               System.exit(0);
            }
         } );
      fr.setTitle("JPEG Viewer");
      viewer = new ImagePanel(img);
      viewer.setPreferredSize(new Dimension(width, height));
      Container cp = fr.getContentPane();
      fr.getContentPane().setLayout(new GridLayout(1,1));
      cp.add(viewer);
      fr.pack();
      fr.setSize(new Dimension(width, height));
      fr.show();
      viewer.repaint();
   }


   class ImagePanel extends JComponent {
      BufferedImage image;
      public ImagePanel(BufferedImage img){
         image = img;
      }

      public void paintComponent(Graphics g){
         Rectangle rect = this.getBounds();
         if(image != null) {
            g.drawImage(image, 0,0,rect.width, rect.height, this);
        }
      }
   }

   public static void  main(String[] args){
      JPEGViewer ip = new JPEGViewer();
      if(args.length <1) {
         System.out.println("Enter a valid JPEG file name");
         System.exit(0);
      }
      ip.loadAndDisplay(args[0]);
   }
}
