Skip to content

Instantly share code, notes, and snippets.

@worthlesscog
Created July 1, 2012 07:15
Show Gist options
  • Save worthlesscog/3027281 to your computer and use it in GitHub Desktop.
Save worthlesscog/3027281 to your computer and use it in GitHub Desktop.
Proportionally scale and smooth
/**
* @see http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html
*/
private BufferedImage scale(BufferedImage image, int width, int height, int smoothingSteps) {
int w = image.getWidth();
int h = image.getHeight();
int targetH, targetW;
if (w > h) {
targetW = width;
targetH = (int) ((float) h / w * height);
} else {
targetH = height;
targetW = (int) ((float) w / h * width);
}
BufferedImage i = image;
for (int n = 0; (w / 2) >= targetW && (h / 2) >= targetH && n < smoothingSteps; i = draw(i, w, h)) {
w /= 2;
h /= 2;
n++;
}
return draw(i, targetW, targetH);
}
private BufferedImage draw(BufferedImage image, int w, int h) {
BufferedImage buffer = new BufferedImage(w, h, (image.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics2d = buffer.createGraphics();
graphics2d.drawImage(image.getScaledInstance(w, h, Image.SCALE_AREA_AVERAGING), 0, 0, null);
graphics2d.dispose();
return buffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment