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);

double scale = targetWidth / newImage.getWidth();

ParameterBlock pb = new ParameterBlock();

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

resizedImage = (JAI.create("SubsampleAverage",
catch (Exception e)
this.error = e.getMessage();

No comments: