Resizes an image so that it will fit inside a box with specified dimensions. The original image’s aspect ratio will be preserved, so that the new image will not be distorted.
static RenderedImage resizeImageToFit(source, width, height)
The new image’s width and height are guaranteed to be less than or equal to the requested values, and at least one dimension will match exactly. The following table contains example image dimensions, and what size image will be created by a call to this method.
| Original Size | Requested Size | New Size |
|---|---|---|
| 400×400 | 200×200 | 200×200 |
| 800×400 | 200×200 | 200×100 |
| 400×800 | 200×200 | 100×200 |
The following example shows how to load an image file, resize it to fit inside a 150×150 pixel area, and then save it as a new image:
import net.devella.thumbs.ThumbMaster;
...
// read source image from a file
RenderedImage source =
ImageIO.read(new File("/tmp/source.png"));
// resize the image
RenderedImage result =
ThumbMaster.resizeImageToFit(source, 150, 150);
// write the image to a new file
ImageIO.write(result, "png", new File("/tmp/result.png"));
...
© 2008 Sean Kleinjung. All Rights Reserved.