Scale Resize Images

I recently had to look into the image scaling code that we employ in our application because of a known bug with the JDK. Here is the original code we used to resize image icons:

int hint = Image.SCALE_AREA_AVERAGING;
icon = new ImageIcon(original.getScaledInstance(w,h, hint));

As stated, the above code occasionally will throw a ClassCastException because of a bug with the JDK. The exception is thrown because of the use of the AreaAveragingScaleFilter class which is instantiated when you use the SCALE_AREA_AVERAGING hint. A work around for this problem is to use the Image.SCALE_REPLICATE hint but which produces images with jaggies.

You can use a different approach to creating image thumb nails as in the following code:

BufferedImage bi = new BufferedImage(w, h,
   BufferedImage.TYPE_INT_ARGB);
bi.getGraphics().drawImage(original, 0, 0, w, h, null);
icon = new ImageIcon(bi);

You can also scale, rotate, and shear an image using affine transformations. The following code resizes an image using the AffineTransform class.

AffineTransform tx = new AffineTransform();
tx.scale(scalew, scaleh);
AffineTransformOp op = new AffineTransformOp(tx,
   AffineTransformOp.TYPE_BILINEAR);
BufferedImage bi = op.filter(ogininal, null);
icon = new ImageIcon(bi);

Leave a Reply