Quality Image Resizing with JAI

ThumbMaster Reference: resizeImageToFit

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.

Declaration

static RenderedImage resizeImageToFit(source, width, height)

Parameters

source
A RenderedImage object containing the source image that is to be resized.
width
The width of the box to resize the image to fit inside of. The result image will have a width that is equal to or less than this value.
height
The height of the box to resize the image to fit inside of. The result image will have a height that is equal to or less than this value.

Details

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

Example Usage

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"));
...
Example 1: Resizing images using resizeImageToFit

© 2008 Sean Kleinjung. All Rights Reserved.