/* @(#) 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 edge detection bean that can be used in the server side. It can be called by a
  * servlet or a JSP page. It uses the JAI codec to load the image and the "GradientMagnitude"
  * operator to perform edge detection.
  * @version 1.0  10 October 2000
  * @author Lawrence Rodrigues
  */
public class JAIEdgeDetectBean{
   protected double rotationAngle=0.0, magFactor=0.0;
   protected PlanarImage image;
   public JAIEdgeDetectBean(){}

   public void edgeDetectAndPost(String imagepath, OutputStream out){
      PlanarImage pimage = readAsPlanarImage(imagepath);
      PlanarImage outimage = sobelGradientMagnitude(pimage);
      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) {}
   }

   public static RenderedOp sobelGradientMagnitude(PlanarImage image) {
      KernelJAI sobelVertKernel = KernelJAI.GRADIENT_MASK_SOBEL_VERTICAL;
      KernelJAI sobelHorizKernel = KernelJAI.GRADIENT_MASK_SOBEL_HORIZONTAL;
      ParameterBlock pb = new ParameterBlock();
      pb.addSource(image);
      pb.add(sobelHorizKernel);
      pb.add(sobelVertKernel);
      return JAI.create("gradientmagnitude", pb);
   }
}
