import java.awt.Image;
import javax.swing.ImageIcon;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class subImage extends JFrame {
  public subImage (ImageIcon img, int x, int y, int w, int h) {
    BufferedImage bimg = new BufferedImage(img.getIconWidth(), 
					   img.getIconHeight(), 
					   BufferedImage.TYPE_INT_RGB);
  
    Graphics2D g2d = bimg.createGraphics();
    g2d.drawImage(img.getImage(), 0, 0, null);
    
    BufferedImage subImage = bimg.getSubimage(x, y, w, h);
    JLabel label = new JLabel (new ImageIcon((Image)subImage));
    getContentPane().add(label);
    addWindowListener( new WindowAdapter() 
      {
        public void windowClosing(WindowEvent e){
          System.exit(0);
        }
      }
		       );
    setSize(w, h);
    setVisible(true);
  }

  public static void main (String[] args) {
    int x=0, y=0, w=0, h=0;
    ImageIcon img = null;

    switch( args.length) {
    case 5 : h = Integer.parseInt(args[4]);
    case 4 : w = Integer.parseInt(args[3]);
    case 3 : y = Integer.parseInt(args[2]);
    case 2 : x = Integer.parseInt(args[1]);
    case 1 : img = new ImageIcon (args[0]);
      break;
    default: System.out.println("Usage: subImage <image> <x> <y> <w> <h>");
      System.exit(0);
    }
    
    if (h==0)
      h = img.getIconHeight()-y;
    if (w==0)
      w = img.getIconWidth()-x;

    new subImage(img, x, y, w, h);
  }
}


