10.4. Roll Your Own

The 2D API comes with a respectable toolbox of image operators. But if you're thirsting for something more exotic, you can write your own operator by implementing the BufferedImageOp interface.

The effect I'll implement is a simple one, called thresholding. A threshold operator uses three values—a threshold, a minimum, and a maximum—to determine its output. Input values that are less than the threshold are assigned the minimum value. All other input values are changed to the maximum value.[6] This process is applied, separately, to each color component of each pixel. The mapping from input to output is shown in Figure 10.6.

[6] You could implement thresholding using a LookupOp, too. The purpose of this example is to show how you can implement your own image operators.

Figure 10.6. Threshold

Our thresholding class will implement the BufferedImageOp interface, which has five methods that need to be defined:

public BufferedImage filter(BufferedImage src, BufferedImage dest)

This is the central method in BufferedImageOp. It performs the actual processing on the source image.

public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM)

This method is used to create a destination image that is compatible with the given source image and color model. We'll be talking in detail about color models in Chapter 11.

public Rectangle2D getBounds2D(BufferedImage ...

Get Java 2D Graphics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.