
import java.awt.*;
import java.awt.image.*;
import java.awt.image.renderable.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.awt.image.DataBuffer;
import javax.media.jai.*;
import javax.swing.*;


public class PaintTest extends WindowAdapter {

  public PaintTest( String name ) {

    try {
      // read sources
      PlanarImage src;
      src = JAIImageReader.readImage( name );
      
      // create destination image (rescaling of the source image)
      PlanarImage dst = rescale( src );

      // create GUI (put the destination image in an IconJAI)
      setupGUI( dst );

    } catch( IllegalArgumentException e ) {
      JOptionPane.showMessageDialog( null, e.getMessage(), "PaintTest", JOptionPane.ERROR_MESSAGE );
      System.exit( 1 );
    }
  }
   
  private void setupGUI( PlanarImage display ) {

    JFrame frame = new JFrame();
    frame.addWindowListener(this);
    
    // Application panel
    IconJAI imageIcon = new IconJAI( display );
    Dimension iconSize = new Dimension( imageIcon.getIconWidth(),
					imageIcon.getIconHeight());
    JLabel imageLabel = new JLabel();
    imageLabel.setIcon( imageIcon );
    imageLabel.setPreferredSize( iconSize );
    
    frame.getContentPane().setLayout( new BorderLayout() );
    frame.getContentPane().add( imageLabel, BorderLayout.CENTER );
    frame.pack();
    frame.setVisible(true);
  }

  // rescale the data in the image and force the destination image to 
  // hold data of type DataBuffer.TYPE_BYTE.
  private PlanarImage rescale( PlanarImage image ) {
    
    PlanarImage result=null;

    Rectangle rect = image.getBounds();
    
    // rescale to range
    double[] scale = { 0.5 };
    double[] offset = { 0.0 };
    
    ParameterBlock pb = new ParameterBlock();
    pb.addSource( image );
    pb.add( scale );
    pb.add( offset );
    result = JAI.create( "rescale", pb, 
			 getRenderingHints( 
					   DataBuffer.TYPE_BYTE, 
					   image.getSampleModel(), 
					   rect ) );
    
    return result;
  }
  
  RenderingHints getRenderingHints( int dType, 
				    SampleModel smSrc, 
				    Rectangle srcBounds ){
    
// This causes the repainting of the image to be very slow.
    SampleModel sm =
      RasterFactory.createBandedSampleModel( dType,
					     (int)srcBounds.getWidth(),
					     (int)srcBounds.getHeight(),
					     smSrc.getNumBands() );
    
    ImageLayout il = new ImageLayout();
    il.setSampleModel(sm);
    return new RenderingHints(JAI.KEY_IMAGE_LAYOUT, il);
  }
  
  /** Handles window close events. */
  public void windowClosing(WindowEvent e) {
        System.exit(0);
  }
  
  public static void main(String[] args) {
    if ( args.length!=1 ) {
      System.out.println("Usage: PaintTest Image");
      System.exit(1);
    }
    new PaintTest( args[0] );
  }
}









