Resizing and cropping images in Java – revisited

2011 June 17
by Patrick Herrera

Soon after publishing my previous article (http://blog.futuremedium.com.au/2011/01/28/a-journey-with-resizing-and-cropping-images-in-java/) I came across an article from an engineer on the Java 2D team – from the horse’s mouth so to speak: http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html

In this article he contrasts various methods of resizing images and I’ve come to the conclusion that my original method still stands although I haven’t fully investigated the suggestion of using different methods depending on the extend of the rescaling required.

What I have done however is replace my original resize method with the following:

private BufferedImage doResize(int newWidth, int newHeight, double scaleX, double scaleY, BufferedImage source) {
 GraphicsConfiguration gc = getDefaultConfiguration();
 BufferedImage result = gc.createCompatibleImage(newWidth, newHeight, source.getColorModel().getTransparency());
 Graphics2D g2d = null;
 try {
   g2d = result.createGraphics();
   g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                        RenderingHints.VALUE_INTERPOLATION_BICUBIC);
   g2d.scale(scaleX, scaleY);
   g2d.drawImage(source, 0, 0, null);
 } finally {
   if (g2d != null) { g2d.dispose(); }
 }
 return result;
}

This removes the references to the AffineTransform, but note the continued use of setting the RenderingHint to ensure the quality doesn’t suck.

I’m assuming that internally this updated technique uses the same algorithms, as I did a test resizing 200 images and the time was virtually identical, and the resulting quality was 100% identical as far as I could see.

And that is about enough of that …

3 Responses leave one →
  1. 2011 July 2
    IonelM permalink

    Hi, Patrick

    I needed to resize images to create thumbnails. I used your method, but somehow the thumbnailed images turned out pixelated, and pretty ugly.
    So, from one test to another, I found that, at least for thumbnails, the Image.getScaledInstance(newWidth, newHeight, Image.SCALE_AREA_AVERAGING) renders pretty good results.
    I thought it might be useful for other people looking for this.

    Thanks

  2. 2011 July 5

    Hi IonelM,

    Sounds like you have come across the issue where the quality isn’t as good when scaling down by a factor of more that 2 as mentioned in the java.net article, so your suggestion is the correct way to handle it in that situation.

    Thanks for the tip,

    Patrick

Trackbacks & Pingbacks

  1. A journey with resizing and cropping images in Java | Future Medium

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS