Reading images using ImageIO.read(file); causes ja

2019-02-26 04:34发布

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.

2条回答
Emotional °昔
2楼-- · 2019-02-26 05:23

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.

查看更多
萌系小妹纸
3楼-- · 2019-02-26 05:26

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

查看更多
登录 后发表回答