Last active
April 28, 2021 15:21
-
-
Save typable/631da96046993b046b1930108ff48171 to your computer and use it in GitHub Desktop.
Image Scaling
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
public static BufferedImage scaleByWidth(BufferedImage sourceImage, int targetWidth) { | |
double factor = (double) targetWidth / (double) sourceImage.getWidth(); | |
int targetHeight = (int) (sourceImage.getHeight() * factor); | |
return scale(sourceImage, targetWidth, targetHeight); | |
} | |
public static BufferedImage scaleByHeight(BufferedImage sourceImage, int targetHeight) { | |
double factor = (double) targetHeight / (double) sourceImage.getHeight(); | |
int targetWidth = (int) (sourceImage.getWidth() * factor); | |
return scale(sourceImage, targetWidth, targetHeight); | |
} | |
public static BufferedImage scale(BufferedImage sourceImage, int targetWidth, int targetHeight) { | |
BufferedImage targetImage = null; | |
if(sourceImage != null) { | |
double deltaWidth = (double) targetWidth / (double) sourceImage.getWidth(); | |
double deltaHeight = (double) targetHeight / (double) sourceImage.getHeight(); | |
targetImage = new BufferedImage(targetWidth, targetHeight, sourceImage.getType()); | |
Graphics2D g = targetImage.createGraphics(); | |
g.scale(deltaWidth, deltaHeight); | |
g.drawImage(sourceImage, 0, 0, null); | |
g.dispose(); | |
} | |
return targetImage; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment