Tuesday, April 7, 2009

Sample code for Image Resizing in Java

I needed to resize a java.awt.Image object so that it fits into a small JLabel in my j2se/java/swing desktop application. I wrote a utility method which resizes the given Image to fit into given width and height. Here is the code of my resize method:

// import java.awt.Image;
// import java.awt.image.BufferedImage;

 * Resizes the given Image so that it fits into given width and height.
 * @param inputImage
 * @param fitWidth
 * @param fitHeight
 * @return
public static Image fitImage(Image inputImage, int fitWidth, int fitHeight) {
    int w = inputImage.getWidth(null);
    int h = inputImage.getHeight(null);
    double dw = w / (double) fitWidth;
    double dh = h / (double) fitHeight;
    if (dw <= 1d && dh <= 1d)
        return inputImage;

    double d = Math.max(dw, dh);
    w = (int)Math.min(fitWidth, Math.round(w / d));
    h = (int)Math.min(fitHeight, Math.round(h / d));
    BufferedImage bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    bufferedImage.getGraphics().drawImage(inputImage, 0, 0, w, h, null);
    return bufferedImage;

No comments:

Post a Comment