From ebf5a7981f01065193f58a6f3e13e01123894ce0 Mon Sep 17 00:00:00 2001 From: nathan Date: Sun, 17 Sep 2017 16:28:38 +0200 Subject: [PATCH] Added clampMaxImageSize so an image will be a max of that size, but still maintain it's aspect ratio. --- src/dorkbox/util/ImageUtil.java | 42 +++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/src/dorkbox/util/ImageUtil.java b/src/dorkbox/util/ImageUtil.java index 12b2291..5291b27 100644 --- a/src/dorkbox/util/ImageUtil.java +++ b/src/dorkbox/util/ImageUtil.java @@ -39,6 +39,44 @@ import javax.swing.ImageIcon; public class ImageUtil { + /** + * @return returns an image, where the aspect ratio is kept, but the maximum size is maintained. + */ + public static + BufferedImage clampMaxImageSize(final BufferedImage image, final int size) { + int width = image.getWidth(null); + int height = image.getHeight(null); + + if (width <= size && height <= size) { + return image; + } + + // scale width/height + if (width > size) { + double scaleRatio = (double) size / (double) width; + width = size; + height = (int) (height * scaleRatio); + } + + if (height > size) { + double scaleRatio = (double) size / (double) height; + height = size; + width = (int) (width * scaleRatio); + } + + int type = image.getType(); + if (type == 0) { + type = BufferedImage.TYPE_INT_ARGB; + } + + BufferedImage resizedImage = new BufferedImage(width, height, type); + Graphics2D g = resizedImage.createGraphics(); + g.drawImage(image, 0, 0, width, height, null); + g.dispose(); + + return resizedImage; + } + /** * There are issues with scaled images on Windows. This correctly scales the image. */ @@ -196,10 +234,6 @@ class ImageUtil { */ public static BufferedImage getSquareBufferedImage(Image image) { - if (image instanceof BufferedImage) { - return (BufferedImage) image; - } - int width = image.getWidth(null); int height = image.getHeight(null);