5

I'm writing a Web application that let user upload images in several formats (e.g. png,jpg,bmp). After the image has been uploaded the system should convert it to "png" and scale it to a predefined resolution.

To convert the image I use the handy method:

javax.imageio.ImageIO.write(im, type, baos);

Here's where the problem start. The first argument of Image javax.imageio.ImageIO.write is a RenderedImage. The Java Doc states that the only known implementation is BufferedImage.

I try to find a way to convert a java.awt.Image to a BufferedImage, but it doesn't seems possible. However, it is possible to draw an image on a BufferedImage.

The problem is that creating a new BufferedImage each time is very memory expensive. I can start creating a pool of BufferedImage but I'm looking for clever/news ideas.

Dani Cricco
  • 8,829
  • 8
  • 31
  • 35

5 Answers5

5

Try Thumbnailator library: http://code.google.com/p/thumbnailator/

Example code:

Thumbnails.of("large-picture.jpg")
        .scale(1.0)
        .outputFormat("png")
        .toOutputStream(os);

Library offers also much more like scaling, sizing, cropping, rotating, watermarking etc.

muras
  • 51
  • 1
  • 2
1

There's a bunch of Java libraries and SO posts about this. Did you check them out?

Community
  • 1
  • 1
The Alchemist
  • 3,397
  • 21
  • 22
  • 1
    No, I didn't check them. Do you have any recommendation for this problem. I mean, converting images with low memory footprint – Dani Cricco Aug 31 '10 at 21:33
  • No, sorry, I haven't used any of them so I can't recommend anything. You can probably find some results on Google or whereever, but your best bet is to just try them yourself. – The Alchemist Aug 31 '10 at 22:33
1

You could reuse one buffered image over and over again, using subimage to size appropriately when it's time to use the ImageIO.write method

I82Much
  • 26,901
  • 13
  • 88
  • 119
0

You could look at the implementation of BufferedImage and implement your own (A file-based implementation perhaps?). These classes are generally pretty straight-forward to read, often 50-70% comments and clearly written.

They give out the sources, why not make use of 'em?

Bill K
  • 62,186
  • 18
  • 105
  • 157
0

Launch a native converter like netpbm or imagemagick.

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347