Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 25: Images 777


Contrast.java
TheContrastfilter is very similar toGrayscale, except its override offilterRGB( )is slightly
more complicated. The algorithm it uses for contrast enhancement takes the red, green, and
blue values separately and boosts them by 1.2 times if they are already brighter than 128. If
they are below 128, then they are divided by 1.2. The boosted values are properly clamped
at 255 by themultclamp( )method.


import java.applet.;
import java.awt.
;
import java.awt.image.*;


public class Contrast extends RGBImageFilter implements PlugInFilter {


public Image filter(Applet a, Image in) {
return a.createImage(new FilteredImageSource(in.getSource(), this));
}

private int multclamp(int in, double factor) {
in = (int) (in * factor);
return in > 255? 255 : in;
}

double gain = 1.2;
private int cont(int in) {
return (in < 128)? (int)(in/gain) : multclamp(in, gain);
}

public int filterRGB(int x, int y, int rgb) {
int r = cont((rgb >> 16) & 0xff);
int g = cont((rgb >> 8) & 0xff);
int b = cont(rgb & 0xff);
return (0xff000000 | r << 16 | g << 8 | b);
}
}


Figure 25-9 shows the image afterContrastis pressed.


Convolver.java
The abstract classConvolverhandles the basics of a convolution filter by implementing
theImageConsumerinterface to move the source pixels into an array calledimgpixels.It
also creates a second array callednewimgpixelsfor the filtered data. Convolution filters
sample a small rectangle of pixels around each pixel in an image, called theconvolution
kernel. This area, 3×3 pixels in this demo, is used to decide how to change the center pixel
in the area.


NOTEOTE The reason that the filter can’t modify theimgpixelsarray in place is that the next pixel on
a scan line would try to use the original value for the previous pixel, which would have just been
filtered away.

Free download pdf