Image Filters

This document explains the basics of image filters. You do not have to be an imaging expert to write one, however some knowledge of AWT and JAI doesn't hurt. SUN's JAI tutorial should get you started.

Writing a filter, only requires implementing a simple interface org.jmage.filter.ImageFilter. It uses JAI's PlanarImage class internally to do it's work. Your filter implementation should be stateless, and if you plan on using the static JAI wrapper class, take into consideration it's not synchronized. Always explicitly return the filtered image. Depending on JAI transformation, it may be a different PlanarImage instance than the one you passed in.

If you require extra parameters for processing, implement ConfigurableImageFilter instead, it will give you an instance of java.util.Properties with everything found by the RequestMapper through the initialize() method. Let's take a look at an example.


public class BicubicResizeFilter extends ConfigurableImageFilter {

    ...

    public void initialize(Properties filterProperties) throws FilterException {
           try {
               left = Float.valueOf(filterProperties.getProperty(LEFT, DEFAULT_CROP)).floatValue();
               assert (left >= 0) : LEFT + CROP_RANGE_ERROR;
               right = Float.valueOf(filterProperties.getProperty(RIGHT, DEFAULT_CROP)).floatValue();
               assert (right >= 0) : RIGHT + CROP_RANGE_ERROR;
               top = Float.valueOf(filterProperties.getProperty(TOP, DEFAULT_CROP)).floatValue();
               assert (top >= 0) : TOP + CROP_RANGE_ERROR;
               bottom = Float.valueOf(filterProperties.getProperty(BOTTOM, DEFAULT_CROP)).floatValue();
               assert (bottom >= 0) : BOTTOM + CROP_RANGE_ERROR;

               this.filterProperties = filterProperties;
               if (log.isDebugEnabled()) log.debug(INITIALIZED);
           } catch (Throwable t) {
               //log error
           }
    }

    public PlanarImage filter(PlanarImage image) throws FilterException {
        int width = image.getWidth();
        int height = image.getHeight();

        ParameterBlock pb = new ParameterBlock();
        pb.addSource(image);
        //coordinates are 0 based
        pb.add(left);
        pb.add(top);
        pb.add(width - left - right);
        pb.add(height - top - bottom);

        PlanarImage result = (PlanarImage) JAI.create("crop", pb);
        return result;
    }
}

Typical for a simple JAI transformation are the creation of a ParameterBlock which holds all the properties and then calling the static JAI.create(String, ParameterBlock) method to perform the operation.