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

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

   public void loadAndDisplay(String filename){
      BufferedImage bufimg = loadImage(filename);
      //System.out.println("bufimage = "+ bufimg);
      Image img = Toolkit.getDefaultToolkit().createImage(bufimg.getSource());
      //System.out.println("image = "+ img);
      displayImage(img);
   }

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

   public void displayImage(Image img) {
      int width = img.getWidth(this);
      int height = img.getHeight(this);
      System.out.println("width = "+ width+ "  height = "+height);
      displayImage(img, width, height);
   }

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

   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;
      }
   }

   class ImagePanel extends JComponent {
      protected Image image;
      public ImagePanel(Image 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){
      SimpleViewer2D ip = new SimpleViewer2D();
      if(args.length <1) {
         System.out.println("Enter a valid JPEG file name");
         System.exit(0);
      }
      ip.loadAndDisplay(args[0]);
   }
}
