Home > Articles > Programming > Java

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

Other Zooming Techniques

If your application requires a simple zoom feature, you can try other ways of zooming. We already mentioned one technique in Chapter 6: manipulating drawImage() parameters.

Using the Image Class

You need to use the following method to create a scaled instance of an image:

  • public Image getScaledInstance(int width, int height, int hints)

Set the width and height parameters to suit the scale factor. If Sx is the desired scale factor in the x direction (magnified image width divided by original image width), then magnified width 5 Sx 3 image width. Likewise, if Sy is the desired scale factor in the y direction, then magnified height 5 Sy 3 image height.

The hints parameter is similar to the renderingHints attribute we saw in Chapter 5. This parameter can take any one of the following values:

  • SCALE_DEFAULT. With this option the default scaling algorithm is used.

  • SCALE_FAST. This option produces the image fast rather than smoothly. In this case scaling might use the nearest-neighbor algorithm.

  • SCALE_SMOOTH. This option produces a smoother scaled image. Here the choice is image quality rather than speed. In this case the scaling algorithm used could be bilinear or bicubic, depending on the availability of the implementation in a given platform.

  • SCALE_REPLICATE. With this option the scaling algorithm provided in the ReplicateScaleFilter class is used.

  • SCALE_AREA_AVERAGING. With this option the area-averaging scaling algorithm provided in the AreaAverageScaleFilter class is used.

Using Filters

Two filter classes are available for scaling: ReplicateScaleFilter and AreaAverage ScaleFilter. Listing 7.15 shows an example using the latter:

LISTING 7.15 Scaling using filters

public Image scale(Image image, double magfactor) {
  int imageWidth = image.getWidth(imObs);
  int imageHeight = image.getHeight(imObs);
  AreaAverageScaleFilter scalefilter =
    new AreaAverageScaleFilter(imageWidth*magfactor,
  ImageProducer ip =
    new FilteredImageSource(image.getSource(), scalefilter);
  return Toolkit.getDefaultToolkit().createImage(ip);

If you want to obtain the width and height of the original image, the input for the method shown in Listing 7.15 should pertain to an already loaded image.

  • + Share This
  • 🔖 Save To Your Account