Skip to content

Instantly share code, notes, and snippets.

@typable
Last active Apr 28, 2021
Embed
What would you like to do?
Image Scaling
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