Sometimes we need to get aspect ratio for an image in Java to fulfil our requirement. You can use the below code to get aspect ratio for an image in Java very easily:
- Define the dimension boundary of which you want resized image as below ( here you will define the height/width to get aspect ration of the image)
Dimension boundary = new Dimension(350, 350); // here you can provide custom height/width
- Get the Scaled dimension of the image you want to resize. In this method you will pass Original imageSize and boundary.
/**
* This method will provide aspect ratio of an image
* @param imgSize
* @param boundary
* @return
*/
public static Dimension getScaledDimension(BufferedImage imgSize, Dimension boundary) {
int original_width = imgSize.getWidth();
int original_height = imgSize.getHeight();
int bound_width = boundary.width;
int bound_height = boundary.height;
int new_width = original_width;
int new_height = original_height;
// first check if we need to scale width
if (original_width > bound_width) {
//scale width to fit
new_width = bound_width;
//scale height to maintain aspect ratio
new_height = (new_width * original_height) / original_width;
}
// then check if we need to scale even with the new height
if (new_height > bound_height) {
//scale height to fit instead
new_height = bound_height;
//scale width to maintain aspect ratio
new_width = (new_height * original_width) / original_height;
}
return new Dimension(new_width, new_height);
}
Hope this will help you.Good Luck :)
1 Comment(s)