As usual I want to share the solutions for my coding problems! I’m sure many of you tried to resize images with Java to make thumbnails for example or to fit some images and logos in a game or just to create an animation…
Anyway, while I was working on a project of mine “DPMagnifier” (Display Picture Magnifier), I had to resize images to a fixed size of 96×96 the same way MSN Messenger does. I checked the Java Documentation, and found out that have implemented some Rendering algorithms. The best algorithm to resize a large image into a small one is the Bicubic! So there was some rendering hints like RenderingHints.VALUE_INTERPOLATION_BICUBIC. but too bad, Java people did not implement this resizing algorithm well! I tried it and it was just the same like the Bilinear algorithm. So enough talking about the issue… here’s the solution:
BufferedImage temp = javax.imageio.ImageIO.read(new File(imagefile));
/* determine thumbnail size from WIDTH and HEIGHT */
int thumbWidth = width;
int thumbHeight = height;
int imageWidth = temp.getWidth(null);
int imageHeight = temp.getHeight(null);
int tempWidth;
int tempHeight;
int x = 0;
int y = 0;
if (imageWidth < imageHeight) {
tempWidth = width;
tempHeight = (int)(((double)imageHeight*width)/imageWidth);
y = -(tempHeight - tempWidth)/2;
}
else {
tempHeight = height;
tempWidth = (int)(((double)imageWidth*height)/imageHeight);
x = -(tempWidth - tempHeight)/2;
}
Image temp1 = temp.getScaledInstance(tempWidth, tempHeight, Image.SCALE_SMOOTH);
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
image.getGraphics().drawImage(temp1, x, y, null);
try {
javax.imageio.ImageIO.write(image, "png", new File("output.png"));
} catch (IOException e) {
e.printStackTrace();
}
If you have a better solution… or maybe you have implemented a better resizing function, write a comment and share it with us!
Cheers…