3

We have some very large jpgs which are used when print on A0 printers.

The problem is that we need to convert this large image down to a thumbnail for use in a few java UIs.

Is there any way to convert the image (with Java) without loading the whole image into memory? Currently we get out of memory exceptions when we try to load the images.

Is there anything in the standard code or is my best bet to use jmagick? A pure java implementation would be best for our deployment.

Thanks

Andrea
  • 11,801
  • 17
  • 65
  • 72
Neil Wightman
  • 1,103
  • 2
  • 9
  • 29
  • Duplicate question: [Loading large images as thumbnails without memory issues in Java?](http://stackoverflow.com/questions/5874593/loading-large-images-as-thumbnails-without-memory-issues-in-java) – Robert May 30 '12 at 13:51
  • I did see this but couldnt get it to work as it kept saying "java.lang.IllegalStateException: Input not set" – Neil Wightman May 31 '12 at 08:04

1 Answers1

8

I managed to get it working and the full code is as follows.

The call to reader.setInput(iis, true, true); is the magic which I was missing from the previous post.

FileInputStream fin = new FileInputStream(source);

ImageInputStream iis = ImageIO.createImageInputStream(fin);

Iterator iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
    return;
}

ImageReader reader = (ImageReader) iter.next();

ImageReadParam params = reader.getDefaultReadParam();

reader.setInput(iis, true, true);

params.setSourceSubsampling(width, height, 0, 0);

BufferedImage img = reader.read(0, params);

ImageIO.write(img, "JPG", destination);
RCB
  • 775
  • 1
  • 6
  • 29
Neil Wightman
  • 1,103
  • 2
  • 9
  • 29
  • 2
    width and height are not the image size but the number of pixels to advance between pixels. So its really a ratio of the source size and required output size. – Neil Wightman May 31 '12 at 09:26