Home > Articles

  • Print
  • + Share This
This chapter is from the book

RescaleOp

RescaleOp does not scale the size of an image as you would expect it to. Instead, RescaleOp performs a rescaling operation by multiplying the color value of each pixel in the source image by a scale factor and then adding an offset. Here is the formula applied to each color component of the source pixels:

dstR = (srcR * scaleFactor) + offset
dstG = (srcG * scaleFactor) + offset
dstB = (srcB * scaleFactor) + offset

Rescaling operations can be used to brighten, darken, or tint images. The following code example increases the overall brightness of the picture by 10 percent:

BufferedImage dstImage = null;
RescaleOp op = new RescaleOp(1.1f, 0.0f, null);
dstImage = op.filter(sourceImage, null);

The first two parameters of the RescaleOp constructor are respectively the scale factor and the offset. Note that a RescaleOp with an offset of 0 is no different from a ConvolveOp with a 1 x 1 kernel. You can also adjust each color component independently:

BufferedImage dstImage = null;
float[] factors = new float[] {
    1.4f, 1.4f, 1.4f
};
float[] offsets = new float[] {
    0.0f, 0.0f, 30.0f
};
RescaleOp op = new RescaleOp(factors, offsets, null);
dstImage = op.filter(sourceImage, null);

In this case, the overall brightness is increased by 40 percent, and all of the pixel colors are shifted toward the blue color. The offset of 30 increases the blue component of each pixel by 12 percent (30/256). Remember, the offset is added to the color value and must therefore be a value between 0 and 255, as opposed to the scale factor, which acts as a percentage.

Figure 8-10 shows the result produced by a RescaleOp with a scale factor of 1.4 for each component and an offset of 30 for the blue component.

Figure 8-10

Figure 8-10 The image is brighter and the blues are bluer after processing.

Just as in LookupOp, the number of values used in the scale factors and offset arrays depend on the number of components in the source image. Working on TYPE_INT_RGB or TYPE_INT_ARGB pictures is therefore easier than working on other types of BufferedImage. When the source image contains an alpha channel, you do not need to specify a factor and an offset for the alpha component. Java 2D automatically preserves the original values.

These five BufferedImageOps will probably be all you need for most situations. Nevertheless, you might want to create your own specialized BufferedImageOp to create advanced graphical effects.

  • + Share This
  • 🔖 Save To Your Account