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

6 comments:

Kamanashis Roy said...

Hi,

I thought I should share this idea http://miniim.blogspot.com/2008/05/image-thumbnail-in-optimized-way-for.html

.

Jan said...

Your solution does not work on my N95 with large images.

Do you have any other idea how i can read big images from file.

Jan said...

My Problem is i can not load the image via Image.createImage() because of outofmemoryerror

and your example does not work because MediaException

fluid said...

thanks - useful :)

Jacques Koorts said...

Does not work on phone. Please let us know where you tested your code. what picture, what size, etc.

Erik said...

This was some time ago. Don't remember the phone, but it was probably a Sony Ericsson, since I did most of my work on Sony Ericsson phones back then. The images where from the phone camera.