/* @(#) ListImagesBean.java 1.0 2000/10/10
 * Copyright (c) 2000 Larry Rodrigues
 */
package viewer;
import java.io.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.image.*;
import java.util.*;
import java.awt.image.renderable.*;
import javax.media.jai.*;
import com.sun.media.jai.codec.*;

/** An image manipulation bean that can be used in the server side. It can be instantiated
   * by a servlet or a JSP page.
   * It uses the JAI operators to load and manipulate images.
   * @version 1.0  10 October 2000
   * @author Lawrence Rodrigues
   */
public class JAIManipBean{
   protected double rotationAngle=0.0, magFactor=0.0;
   protected PlanarImage image;
   public JAIManipBean(){}

   public void setRotationAngle(double rot){
      rotationAngle= rot;
   }

   public double getRotationAngle(){
      return rotationAngle;
   }

   public void setMagFactor(double mag){
      magFactor = mag;
   }

   public double getMagFactor(){
      return magFactor;
   }

   public void manipAndPost(String imagepath, OutputStream out){
      PlanarImage pimage = readAsPlanarImage(imagepath);
      PlanarImage outimage = manip(pimage, getRotationAngle(), getMagFactor());
      saveAsJPEG(outimage,out);
   }

   public static PlanarImage readAsPlanarImage(String filename) {
      return JAI.create("fileload", filename);
   }

   public static void saveAsJPEG(RenderedImage image, OutputStream out ){
      try {
      JPEGEncodeParam param = new JPEGEncodeParam();
      ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, param);
      encoder.encode(image);
      out.close();
      } catch (Exception e) {}
   }

   protected PlanarImage manip(PlanarImage image, double rot, double mag) {
      if(( rot <= 0.001) && (mag <=0.0)) return image;
      RenderedOp op =null, op1=null, op2 =null;
      if(rot > 0.001){
         op1 = rotate(image, rot);
         if(mag <=0.0) return op1.createInstance();
         else {
           op2 = scale(op1, mag,mag);
           return op2.createInstance();
         }
      }else {
         op2 = scale(image, mag,mag);
         return op2.createInstance();
      }
   }

   public RenderedOp scale(PlanarImage image, double magx, double magy) {
      ParameterBlock pb = new ParameterBlock();
      pb.addSource(image);
      pb.add((float)magx);
      pb.add((float)magy);
      pb.add(0f);
      pb.add(0f);
      pb.add(Interpolation.getInstance(Interpolation.INTERP_NEAREST));
      return JAI.create("scale", pb);
   }

    public RenderedOp rotate(PlanarImage image, double ang) {
      ParameterBlock pb = new ParameterBlock();
      pb.addSource(image);
      pb.add((float)(image.getWidth())/2);
      pb.add((float)(image.getHeight())/2);
      pb.add((float)ang);
      pb.add(Interpolation.getInstance(Interpolation.INTERP_NEAREST));
      return JAI.create("rotate", pb);
   }

}