Dec 03
|
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_ARGB); // 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_ARGB); 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();
There’s also a getScaledInstance() method of the Image class which has been around since the early days of Java. Generally its worth avoiding for performance reasons.