Wednesday, May 30, 2007

Processing a BufferedImage

To convert a color image to grayscale, you can use ColorConvertOp as follows:

import java.awt.image.*;
import java.awt.color.*;

ColorConvertOp op = new ColorConvertOp(ColorSpace.getInstance(CS_GRAY), null);
BufferedImage grayImage = op.filter(sourceImage, null);

To invert the colors in an image (producing a photographic negative effect), you might use a RescaleOp as follows:

RescaleOp op = new RescaleOp(-1.0f, 255f, null);
BufferedImage negative = op.filter(sourceImage, null);

To brighten an image, you can use a RescaleOp to linearly increase the intensity of each color value. More realistic brightening effects require a nonlinear transform, however. For example, you can use a LookupOp to handle brightening based on the square-root function, which boosts midrange colors more than colors that are dark or bright:

byte[] data = new byte[256];
for(int i = 0; i < 256; i++)
data[i] = (byte)(Math.sqrt((float)i/255.0) * 255);
ByteLookupTable table = new ByteLookupTable(0, data);
LookupOp op = new LookupOp(table, null);
BufferedImage brighterImage = op.filter(sourceImage, null);

You can blur an image using a ConvolveOp. When processing an image by convolution, a pixel value in the destination image is computed from the corresponding pixel value in the source image and the pixels that surround that pixel. A matrix of numbers known as the kernel is used to specify the contribution of each source pixel to the destination pixel. To perform a simple blurring operation, you might use a kernel like this to specify that the destination pixel is the average of the source pixel and the eight pixels that surround that source pixel:

0.1111  0.1111  0.1111
0.1111 0.1111 0.1111
0.1111 0.1111 0.1111

Note that the sum of the values in this kernel is 1.0, which means that the destination image has the same brightness as the source image. To perform a simple blur, use code like this:

Kernel k = new Kernel(3, 3, new float[] { .1111f, .1111f, .1111f,
.1111f, .1111f, .1111f,
.1111f, .1111f, .1111f });
ConvolveOp op = new ConvolveOp(k);
BufferedImage blurry = op.filter(sourceImage, null);