Tuesday, March 18, 2008

Create thumbnail in J2ME

The latest week I have been working on a J2ME project where we need to display thumbnails of piuctures from the mobile camera. I suppose this is a common scenario, but we had some unexpected problems..

The main reason for the problem is that mobile cameras today are very good. This means that images often will be very big, too big to display, but also to big to handle as an image in the J2ME environment. If you try Image.createImage() you will get an out-of-memory exception. This means that you can not create an Image even to create a thumbnail. In stead you have to create the thumbnail image straight from the stream, without creating a full-size image first.

There are different ways to do this, but since we work with a target platform that is quite new, and supports JSR-234 we chose to use this feature. A small utility function to do the resize could look something like this:


public static Image resizeImage(InputStream src, int width, int height)
{
MediaProcessor mp;
try {
mp = GlobalManager.createMediaProcessor("image/jpeg");
mp.setInput(src, MediaProcessor.UNKNOWN);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
mp.setOutput(bos);
ImageTransformControl fc = (ImageTransformControl) mp
.getControl("javax.microedition.amms.control.imageeffect.ImageTransformControl");
fc.setTargetSize(width, height, 0);
fc.setEnforced(true);
fc.setEnabled(true);

mp.complete();
src.close();
return Image.createImage(bos.toByteArray(), 0, bos.size());
} catch (MediaException e) {
System.out.println("MediaException in Utils.resizeImage():" + e.getMessage());
} catch (IOException e) {
System.out.println("IOException in Utils.resizeImage():" + e.getMessage());
}
return null;
}