I am using the following codes to resize an image, I can easily get same aspect ratio as the original image by using the getScaledInstance
function by setting one parameter to negative, so that it automatically maintains the other paramter to get the aspect ratio. But the problem that I am facing is with the BufferedImage
, I cannot set it to the desired aspect ratio because I don't know beforehand what values of height it will generate(width I have set to 500).I have also included the image that I can getting as a result of running the following code. BufferedImage
I have set to 800x600 because I have no other option.My previous question was resizing an image without compromising the aspect ratio
public class ResizeImage {
public static void main(String[] args) throws IOException {
BufferedImage img1 = new BufferedImage(800, 600,
BufferedImage.TYPE_INT_RGB);
img1.createGraphics()
.drawImage(
ImageIO.read(
new File(
"C:/Users/Public/Pictures/Sample Pictures/Desert.jpg"))
.getScaledInstance(500, -1, Image.SCALE_SMOOTH),
0, 0, null);
ImageIO.write(img1, "jpg", new File(
"C:/Users/Public/Pictures/Sample Pictures/test/Desert.jpg"));
}
}
You can do the math to get the original image aspect ratio
double ratio = img1.getWidth() / img1.getHeigth();
and invoke the getScaledInstance with this ratio
blabla.getScaledInstance(500, (int)500 / ratio, Image.SCALE_SMOOTH);