Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 823
arjunurs Avatar asked Nov 22 '11 05:11

arjunurs


People also ask

How do I fix Java Lang OutOfMemoryError Java heap space?

OutOfMemoryError: Java heap space. 1) An easy way to solve OutOfMemoryError in java is to increase the maximum heap size by using JVM options "-Xmx512M", this will immediately solve your OutOfMemoryError.

What causes Java Lang OutOfMemoryError Java heap space?

OutOfMemoryError is a runtime error in Java which occurs when the Java Virtual Machine (JVM) is unable to allocate an object due to insufficient space in the Java heap. The Java Garbage Collector (GC) cannot free up the space required for a new object, which causes a java. lang. OutOfMemoryError .

What does ImageIO read do?

Image I/O recognises the contents of the file as a JPEG format image, and decodes it into a BufferedImage which can be directly used by Java 2D.

What is ImageIO in Java?

ImageIO. A class containing static convenience methods for locating ImageReader s and ImageWriter s, and performing simple encoding and decoding. ImageReader. An abstract superclass for parsing and decoding of images.


2 Answers

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.

like image 121
larssin Avatar answered Sep 30 '22 16:09

larssin


Why dont u try calling flush() on BufferedImage . It releases some of the resources held.

like image 32
Ramesh PVK Avatar answered Sep 30 '22 16:09

Ramesh PVK