RGBImageFilter
TheRGBImageFilteris used to convert one image to another, pixel by pixel, transforming
the colors along the way. This filter could be used to brighten an image, to increase its contrast,
or even to convert it to grayscale.
To demonstrateRGBImageFilter, we have developed a somewhat complicated example
that employs a dynamic plug-in strategy for image-processing filters. We’ve created an interface
for generalized image filtering so that an applet can simply load these filters based on<param>
tags without having to know about all of theImageFilters in advance. This example consists of
the main applet class calledImageFilterDemo, the interface calledPlugInFilter, and a utility
class calledLoadedImage, which encapsulates some of theMediaTrackermethods we’ve
been using in this chapter. Also included are three filters—Grayscale,Invert, andContrast—
which simply manipulate the color space of the source image usingRGBImageFilters, and
two more classes—BlurandSharpen—which do more complicated “convolution” filters
that change pixel data based on the pixels surrounding each pixel of source data.Blurand
Sharpenare subclasses of an abstract helper class calledConvolver. Let’s look at each part
of our example.
ImageFilterDemo.java
TheImageFilterDemoclass is the applet framework for our sample image filters. It employs
a simpleBorderLayout, with aPanelat theSouthposition to hold the buttons that will
represent each filter. ALabelobject occupies theNorthslot for informational messages
about filter progress. TheCenteris where the image (which is encapsulated in theLoadedImage
Canvassubclass, described later) is put. We parse the buttons/filters out of thefilters <param>
tag, separating them with +’s using aStringTokenizer.
TheactionPerformed( )method is interesting because it uses the label from a button as the
name of a filter class that it tries to load with(PlugInFilter) Class.forName(a).newInstance( ).
This method is robust and takes appropriate action if the button does not correspond to a proper
class that implementsPlugInFilter.
/*
* <applet code=ImageFilterDemo width=350 height=450>
* <param name=img value=vincent.jpg>
* <param name=filters value="Grayscale+Invert+Contrast+Blur+ Sharpen">
* </applet>
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class ImageFilterDemo extends Applet implements ActionListener {
Image img;
PlugInFilter pif;
Image fimg;
Image curImg;
LoadedImage lim;
Label lab;
Button reset;
772 Part II: The Java Library