Saturday, November 19, 2011

How to scale images in Java ?

public class ImageScaling{

public BufferedImage getScaledInstance(final BufferedImage img,
final int targetWidth, final int targetHeight, final Object hint,
final boolean higherQuality) {
final int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB
: BufferedImage.TYPE_INT_ARGB;
BufferedImage ret = img;
int w, h;
if (higherQuality) {
// Use multi-step technique: start with original size, then
// scale down in multiple passes with drawImage()
// until the target size is reached
w = img.getWidth();
h = img.getHeight();
} else {
// Use one-step technique: scale directly from original
// size to target size with a single drawImage() call
w = targetWidth;
h = targetHeight;
}

do {
if (higherQuality && w > targetWidth) {
w /= 2;
if (w < targetWidth) {
w = targetWidth;
}
}

if (higherQuality && h > targetHeight) {
h /= 2;
if (h < targetHeight) {
h = targetHeight;
}
}

final BufferedImage tmp = new BufferedImage(w, h, type);
final Graphics2D g2 = tmp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
g2.drawImage(ret, 0, 0, w, h, null);
g2.dispose();

ret = tmp;
} while (w != targetWidth || h != targetHeight);

return ret;
}

public static void main(final String[] args) {
final File file = new File("c:\\fileImg.jpg");
try {
final BufferedImage img = ImageIO.read(file);
ImageIO.write(new ImageUtil().getScaledInstance(img, 72, 72,
RenderingHints.VALUE_INTERPOLATION_BICUBIC, true), "jpg",
new File("c:\\scaledImage.jpg"));
} catch (final IOException e) {
// AUTO Auto-generated catch block
e.printStackTrace();
}
}
}

3 comments:

Spring Boot Config Server and Config Client.

 In Spring cloud config we can externalise our configuration files to some repository like GIT HUT, Amazon S3 etc. Benefit of externalising ...