How to Scale An Image Maintaining Aspect Ratio Using java-image-scaling API

Below is the static function that I use to scale images in Java using Java Image Scaling 0.8.5 API. When user uploads a file, I pass that file as InputStream to this function, with StandardSize and ThumbSize, the function saves the images at passed fileStorePath with name "newFileName". It also maintains the aspect ratio for thumb and standard image both.


import com.mortennobel.imagescaling.ResampleOp;
import javax.imageio.ImageIO;

// Import other classes here ...

public class UtilMethods {
public static void saveStandardAndThumbImage(String fileStorePath, String newFileName, InputStream imageInputStream, final int standardSize,
final int thumbSize) throws Exception {
BufferedImage srcImage = ImageIO.read(imageInputStream);

String extension = newFileName.substring(newFileName.indexOf(".")+1, newFileName.length());

int actualHeight = srcImage.getHeight();
int actualWidth = srcImage.getWidth();
double imageRatio = (double) actualWidth / (double) actualHeight;

// First Save the standard size
int height, width;
if (actualHeight > standardSize || actualWidth > standardSize) {
height = width = standardSize;
if (imageRatio > 1) // 1 is standard ratio
height = (int) (standardSize / imageRatio);
else
width = (int) (standardSize * imageRatio);
} else {
height = actualHeight;
width = actualWidth;
width = actualWidth;
}
ResampleOp resampleOp = new ResampleOp(width, height);
BufferedImage scaledImage = resampleOp.filter(srcImage, null);
ImageIO.write(scaledImage, extension, new File(fileStorePath, newFileName));

// Lets save the thumb size image now
resampleOp = null;
scaledImage = null;
if (actualHeight > thumbSize || actualWidth > thumbSize) {
height = width = thumbSize;
if (imageRatio > 1)
height = (int) (thumbSize / imageRatio);
else
width = (int) (thumbSize * imageRatio);
} else {
height = actualHeight;
width = actualWidth;
}
resampleOp = new ResampleOp(width, height);
scaledImage = resampleOp.filter(srcImage, null);
ImageIO.write(scaledImage, extension, new File(fileStorePath, "s-" + newFileName));
}
}

Comments