image util: add function to scale images while preserving aspect ratio

This commit is contained in:
Hydrox6
2021-03-24 17:03:51 +00:00
committed by Adam
parent d34deb8ec9
commit 1603ff76bd

View File

@@ -209,7 +209,38 @@ public class ImageUtil
*/
public static BufferedImage resizeImage(final BufferedImage image, final int newWidth, final int newHeight)
{
final Image resized = image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
return resizeImage(image, newWidth, newHeight, false);
}
/**
* Re-size a BufferedImage to the given dimensions.
*
* @param image the BufferedImage.
* @param newWidth The width to set the BufferedImage to.
* @param newHeight The height to set the BufferedImage to.
* @param preserveAspectRatio Whether to preserve the original image's aspect ratio. When {@code true}, the image
* will be scaled to have a maximum of {@code newWidth} width and {@code newHeight}
* height.
* @return The BufferedImage with the specified dimensions
*/
public static BufferedImage resizeImage(final BufferedImage image, final int newWidth, final int newHeight, final boolean preserveAspectRatio)
{
final Image resized;
if (preserveAspectRatio)
{
if (image.getWidth() > image.getHeight())
{
resized = image.getScaledInstance(newWidth, -1, Image.SCALE_SMOOTH);
}
else
{
resized = image.getScaledInstance(-1, newHeight, Image.SCALE_SMOOTH);
}
}
else
{
resized = image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
}
return ImageUtil.bufferedImageFromImage(resized);
}