It's not hard to write a filter where the
filtering depends on the position of the pixel. For example, the
following filter darkens the image the further away it is from the
upper left hand corner of the applet.
import java.awt.*;
import java.awt.image.*;
import java.applet.*;
public class ShadowImage extends Applet {
private Image picture;
public void init() {
String filename = this.getParameter("imagefile");
Image src = this.getImage(getDocumentBase(), filename);
this.picture = this.createImage(new FilteredImageSource(src.getSource(),
new ShadowFilter(this.getSize().width, this.getSize().height)));
}
public void paint (Graphics g) {
g.drawImage(this.picture, 0, 0, this);
}
}
Notice here that I no longer set
canFilterIndexColorModel
to true
. Each pixel
must be treated individually. Also notice that this filter has a
constructor. Although I'm not required provide a constructor for
this subclass, I can if it's useful.
import java.awt.image.*;
public class ShadowFilter extends RGBImageFilter {
private double edge;
public ShadowFilter(int width, int height) {
edge = Math.sqrt(width*width + height*height);
}
public int filterRGB(int x, int y, int rgb) {
double fraction = 1.0 - Math.sqrt(x*x + y*y)/edge;
if (fraction <= 0) return 0xFF000000;
int red = rgb & 0x00FF0000;
red >>>= 16;
int green = rgb & 0x0000FF00;
green >>>= 8;
int blue = rgb & 0x0000FF;
int r = (int) (red * fraction);
int g = (int) (green * fraction);
int b = (int) (blue * fraction);
return (0x000000FF << 24) | (r << 16) | (g << 8) | b;
}
}