on May 24th, 2008Smooth JPEG image scaling in Java.
Today, I have to write Java utility for resizing JPEG images for my photo gallary. It wasn’t so easy, because to resize is really stupid task. But what about smoothing of result images. They used to become absolutely unsuitable for posting to my web-site.
I found solution and glad to open a source code:
private void resizeImage(String filename, String newfilename)
throws InterruptedException, ImageFormatException, IOException
{
LOG.info("Resizing file : " + filename);
// load image from file
Image image = Toolkit.getDefaultToolkit().getImage(filename);
MediaTracker mediaTracker = new MediaTracker(new Container());
mediaTracker.addImage(image, 0);
mediaTracker.waitForID(0);
// get real size
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double imageRatio = (double)imageWidth / (double)imageHeight;
// determine - vertical or horizontal
if(imageHeight > imageWidth) {
// vertical
imageHeight = biggerPart;
imageWidth = (int)(imageHeight * imageRatio);
} else {
// horizontal
imageWidth = biggerPart;
imageHeight = (int)(imageWidth / imageRatio);
}
LOG.info("New height = " + imageHeight + " and width = " + imageWidth);
// draw original image to new image object and
// scale it to the new size on-the-fly
BufferedImage newImage = new BufferedImage(imageWidth,
imageHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = newImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics2D.drawImage(image, 0, 0, imageWidth, imageHeight, null);
// Soften
float softenFactor = 0.09f;
float[] softenArray = {0, softenFactor, 0, softenFactor, 1-(softenFactor*4), softenFactor, 0, softenFactor, 0};
Kernel kernel = new Kernel(3, 3, softenArray);
ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
newImage = cOp.filter(newImage, null);
// save new image to OUTFILE
BufferedOutputStream out = new BufferedOutputStream(new
FileOutputStream(newfilename));
try {
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(newImage);
quality = Math.max(0, Math.min(quality, 100));
param.setQuality((float)quality / 100.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(newImage);
}finally {
out.close();
}
LOG.info("Resized file : " + filename + " to " + newfilename);
}
Enjoy!