Thursday, April 8, 2010

Proportional image resizing in Java

In order to resize images in Java a simple code is used. In fact, depending on the quality of the photos you want to resize there can be different resize codes and libraries. But a common used is the one I'll show in this post. Together with the resize code I'll also give the code which makes the proportional resize. Proportional resizing is a "must" in order not to loose the shape of the image. Lest's start with the resize code which is shown below:

private static BufferedImage resizeImage(BufferedImage image, int width, int height)
BufferedImage resizedImage = new BufferedImage(width, height,
Graphics2D g = resizedImage.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
return resizedImage;

This is enough in order to resize the image, but before calling this function we need to set the proper width and height according to the proportional resize we will make.

//imageFile is any file taken from the buffer or a disk path. It should be of type

//thumbnailWidth & thumbnailHeight should be defined as values in order to have the new image's sizes.

BufferedImage originalImage =;

int originalWidth = originalImage.getWidth();
int originalHeight = originalImage.getHeight();

float widthRatio = originalWidth/thumbnailWidth;
float heightRatio = originalHeight/thumbnailHeight;

BufferedImage resizeImageJpg = null;

if (widthRatio > heightRatio)

float newThumbnailHeight = (float)originalHeight/(float)originalWidth * thumbnailWidth;

resizeImageJpg = resizeImage(originalImage, thumbnailWidth, (int) newThumbnailHeight);

float newThumbnailWidth = (float)originalWidth/(float)originalHeight * thumbnailHeight;

resizeImageJpg = resizeImage(originalImage, (int) newThumbnailWidth, thumbnailHeight);

ImageIO.write(resizeImageJpg, "jpg", new File("filename..."));

No comments:

Post a Comment