Reading images using ImageIO.read(file); causes java.lang.OutOfMemoryError: Java heap space

arjunurs picture arjunurs · Nov 22, 2011 · Viewed 9.2k times · Source

I am using a ImageIO API to write a PNG file. This code is called in a loop and causes an OutOfMemory error. Is there anyway the following code can be fixed to avoid the OutOfMemory error? Or is the only option to increase the JVM heap size?

File file = new File(resultMap.get("outputFile").toString());

//ImageIO to convert jpg to png
BufferedImage img = ImageIO.read(file);
file = new File(resultMap.get("outputFile").toString() + ".png");
ImageIO.write(img, "png", file);   

Java heap size is 1024M.

Answer

larssin picture larssin · Feb 5, 2012

I had a similar problem where I had to read in 36 images, crop them and save them to a new file (one at a time). I figured out that I had to set the images to null after each iteration to allow Java to do its garbage collection. I.e:

BufferedImage img;
for (int i=0; i<36; i++) {
    img = ImageIo.ImageIO.read(anImageFile);
    /* Do what's needed with the image (cropping, resizing etc.) */
    ImageIO.write(img, "jpg", outputFile);
    img.flush();
    img = null;
}

I know it's now an old post but I hope that it can help someone in the future.