Thursday, March 19, 2009

How do I scale or resize a BufferedImage?

There are two main ways to scale an image.

The first is to ‘paint’ a scaled version of the image to a new image of the required size.


// Create new (blank) image of required (scaled) size

BufferedImage scaledImage = new BufferedImage(
width, height, BufferedImage.TYPE_INT_RGB);

// Paint scaled version of image to new image

Graphics2D graphics2D = scaledImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, width, height, null);

// clean up

graphics2D.dispose();



The second is to use an AffineTransform




BufferedImage scaledImage = new BufferedImage(
width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = scaledImage.createGraphics();
AffineTransform xform = AffineTransform.getScaleInstance(scale, scale);
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics2D.drawImage(image, xform, null);
graphics2D.dispose();

No comments: