The image resizing challenge

; Date: Tue May 22 2007

Tags: Java

There's this (web.archive.org) challenge which was posted, well really it's a long complaint about complexity. Fabrizio Giudici posted an alternative using the Mistral toolkit. It's interesting he says it takes a hundred lines of code to resize an image, when I (with my meager experience in graphics code) was able to do it in 5 lines of code over three years ago.

public static BufferedImage mkThumbImage(BufferedImage orig, int thumbW) {
    double origRatio = (double)orig.getWidth() / (double)orig.getHeight();
    int thumbH = (int)(thumbW * origRatio);
    Image scaled = orig.getScaledInstance(thumbW, thumbH, Image.SCALE_SMOOTH);
    BufferedImage ret = new BufferedImage(thumbW, thumbH, BufferedImage.TYPE_INT_RGB);
    ret.getGraphics().drawImage(scaled, 0, 0, null);
    return ret;
}

Then to read & write the image you'd use javax.image.ImageIO, there are convenience functions so reading and writing is one line of code. But it's only one line of code if you're okay with the defaults.

UPDATE: I shoulda read the article he referenced. Chris Campbell was discussing the problems with using getScaledInstance (the method I used above) and offering alternative approaches that are more modern.

Chris offers this idiom as a simple/fast way to scale an image:

g.drawImage(img, 0, 0, img.getWidth()*2, img.getHeight()*2, null);

Which leads to the following code (untested) which should do the job

BufferedImage img = ImageIO.read(new File("c:/tmp/c.jpg"));
int thumbW = img.getWidth()*scale;
int thumbH = img.getHeight()*scale;
BufferedImage ret = new BufferedImage(thumbW, thumbH, BufferedImage.TYPE_INT_RGB);
ret.getGraphics().drawImage(img, 0, 0, thumbW, thumbH, null);
ImageIO.write(ret, "jpeg", new File("c:/tmp/c-thumb.jpg"));

six lines.

Source: (web.archive.org) weblogs.java.net

About the Author(s)

(davidherron.com) David Herron : David Herron is a writer and software engineer focusing on the wise use of technology. He is especially interested in clean energy technologies like solar power, wind power, and electric cars. David worked for nearly 30 years in Silicon Valley on software ranging from electronic mail systems, to video streaming, to the Java programming language, and has published several books on Node.js programming and electric vehicles.