Loading large images as thumbnails without memory issues in Java?

I'm trying to let the user load images from their harddrive, and present these visually in the GUI as a list of thumbnails (JPanels with icons added to a JList). I'm currently using ImageIO.read() to get a BufferedImage and using getScaledInstance for each image (heard that you weren't supposed use that though).

It works reasonably well with small images, but loading more than four photographs (5000x3000 or some such) and I get "java.lang.OutOfMemoryError: Java heap space". The reference to the full size BufferedImage isn't saved, so I figured that the garbage collector would dispose of it and only keep the scaled image (which oughtn't take much memory), but it doesn't seem like it. I tread getRuntime().gc() and System.gc() as well, to no effect.

Any good way of loading scaled images from file, without running into memory errors? Obviously a lot of softwares manage to do this very thing, maybe not in Java though. External libraries are okay.


Current code:

BufferedImage unscaledImage = ImageIO.read(imageFile);

int unscaledHeight = unscaledImage.getHeight();
int unscaledWidth = unscaledImage.getWidth();

int imageRatio = unscaledHeight/unscaledWidth;

if (imageRatio >= 1) {
    return new ImageIcon(unscaledImage.getScaledInstance(width,-1,Image.SCALE_FAST));
} else {
    return new ImageIcon(unscaledImage.getScaledInstance(-1,height,Image.SCALE_FAST));
}
11
задан Johannes Keinestam 3 May 2011 в 19:27
поделиться