Image resizing - maintaining aspect ratio
How do I resize an image and keep its aspect ratio?
This is the method I am using:
private static BufferedImage resizeImage(BufferedImage originalImage,
int type) {
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT,
type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
return resizedImage;
}
Variable type
:
BufferedImage original = ImageIO.read(new File(imagePath));
int type = original.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
: original.getType();
The problem is that some images resize correctly, but others lose aspect ratio due to IMG_WIDTH and IMG_HEIGHT.
Is there a way to get the original dimensions of the image and then apply some aspect ratio to maintain the aspect ratio of the resized image?
source to share
Why don't you use originalImage.getWidth()
and originalImage.getHeight()
? Then you can calculate the aspect ratio easily. Don't forget int / int = int, so you need to do
double ratio = 1.0 * originalImage.getWidth() / originalImage.getHeight();
or
double ratio = (double) originalImage.getWidth() / originalImage.getHeight();
For additional math, you can calculate
int height = (int) IMG_WIDTH/ratio;
int width = (int) IMG_HEIGHT*ratio;
Then see which option works best and resize to (IMG_WIDTH, height)
or(width, IMG_HEIGHT)
source to share
To get the size of the image, see getWidth()
/ getHeight()
. The rest is just relatively simple math.
Assuming IMG_WIDTH
u IMG_HEIGHT
represent the largest desired size:
- Find which one reaches the limit first.
- Calculate the ratio between actual size and maximum size.
- Multiply another dimension in the image by the same factor.
source to share