image util: add function to scale images while preserving aspect ratio
This commit is contained in:
@@ -209,7 +209,38 @@ public class ImageUtil
|
|||||||
*/
|
*/
|
||||||
public static BufferedImage resizeImage(final BufferedImage image, final int newWidth, final int newHeight)
|
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);
|
return ImageUtil.bufferedImageFromImage(resized);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user