Skip to main content

The image resizing challenge

Posted by robogeek on May 22, 2007 at 4:00 PM PDT

There's this 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 = 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.