Created
January 14, 2018 11:40
-
-
Save kevcodez/21d2faf6c10c3af4293f4dc0321995a1 to your computer and use it in GitHub Desktop.
Scale images (BufferedImage) in Java to a max height and width
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.*; | |
import java.awt.image.BufferedImage; | |
public class ImageScaler { | |
public BufferedImage resizeImage(BufferedImage originalImage, Dimension maxDimension) { | |
Dimension imageDimensions = new Dimension(originalImage.getWidth(), originalImage.getHeight()); | |
Dimension scaledDimensions = getScaledDimension(imageDimensions, maxDimension); | |
BufferedImage resizedImage = new BufferedImage(scaledDimensions.width, scaledDimensions.height, | |
BufferedImage.TYPE_INT_RGB); | |
Graphics2D g = resizedImage.createGraphics(); | |
g.drawImage(originalImage, 0, 0, scaledDimensions.width, scaledDimensions.height, Color.WHITE, null); | |
g.dispose(); | |
return resizedImage; | |
} | |
private Dimension getScaledDimension(Dimension imgSize, Dimension maxDimension) { | |
int originalWidth = imgSize.width; | |
int originalHeight = imgSize.height; | |
int newWidth = originalWidth; | |
int newHeight = originalHeight; | |
if (originalWidth > maxDimension.getWidth()) { | |
newWidth = maxDimension.width; | |
newHeight = (newWidth * originalHeight) / originalWidth; | |
} | |
if (newHeight > maxDimension.height) { | |
newHeight = maxDimension.height; | |
newWidth = (newHeight * originalWidth) / originalHeight; | |
} | |
return new Dimension(newWidth, newHeight); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment