15 January 2009

Powerful image editing in Java

The Java Advanced Imaging (JAI) API provides a very powerful way of manipulating images on the server. For a current app under development, we needed to receive an image file (JPG, PNG, or GIF) and resize it to a set width (letting the height adjust to maintain aspect ratio). JAI came to the rescue when the built-in image processing packages in Java were too slow.

The following code demonstrates the image resizing capabilities of JAI; for maximum image quality, we use the "SubsampleAverage". Thanks to this article.

BufferedImage resizedImage = null;

try {
SeekableStream stream = SeekableStream.wrapInputStream(is, true);
RenderedOp newImage = JAI.create("stream",stream);
((OpImage)newImage.getRendering()).setTileCache(null);

double scale = targetWidth / newImage.getWidth();

ParameterBlock pb = new ParameterBlock();
pb.addSource(newImage);
pb.add(scale);
pb.add(scale);

/*
* For best results, must use the following rendering hints.
*/
RenderingHints qualityHints =
new RenderingHints(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);

resizedImage = (JAI.create("SubsampleAverage",
pb,qualityHints)).getAsBufferedImage();
}
catch (Exception e)
{
this.error = e.getMessage();
}

No comments: