Wednesday, December 15, 2010

How to resize Buffered Images

When we need to resize or scale images in Java, the Java2D Team has been encouraging developers to move away from Image.getScaledInstance() to more updated APIs. This is exactly what I tried to do. So, if you are in need of a fairly good function that resizes images, look no further :)

private BufferedImage resizedImage(BufferedImage oriImage) {

    int type = oriImage.getType() == 0
            ? BufferedImage.TYPE_INT_ARGB : oriImage.getType();

    BufferedImage scaledImage = new BufferedImage((int) scaleWidth,
            (int) scaleHeight, type);

    // Paint scaled version of image to new image

    Graphics2D graphics2D = scaledImage.createGraphics();
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BILINEAR);

    graphics2D.drawImage(oriImage, 0, 0, (int) scaleWidth,
            (int) scaleHeight, null);

    // Clean up
    graphics2D.dispose();

//Return scaled image
 return scaledImage;

}


Aside note: Some of my co-workers asked me about AffineTransform.scale() when performing scaled functions. Well, there is nothing wrong in using AffineTransform.Here's an example:
 AffineTransform xform = AffineTransform.getScaleInstance(2, 2);
 graphics2D.drawImage(img, xform, null);

But in a majority of cases, there is a better approach. Simply use the scaling variant of Graphics.drawImage()

 graphics2D.drawImage(oriImage, 0, 0, oriImage.getWidth()*2,
            oriImage.getHeight()*2, null);

No comments:

Post a Comment