使用ImageIO.read(文件)读取图像;导致java.lang.OutOfMemoryError:Java堆空间 [英] Reading images using ImageIO.read(file); causes java.lang.OutOfMemoryError: Java heap space

查看:235
本文介绍了使用ImageIO.read(文件)读取图像;导致java.lang.OutOfMemoryError:Java堆空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ImageIO API来编写PNG文件。此代码在循环中调用并导致OutOfMemory错误。无论如何可以修复以下代码以避免OutOfMemory错误?或者是增加JVM堆大小的唯一选择?

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堆大小为1024M。

Java heap size is 1024M.

推荐答案

我有一个类似的问题,我必须读取36张图像,裁剪它们并将它们保存到一个新文件(一次一个)。我发现每次迭代后我必须将图像设置为null,以允许Java进行垃圾收集。即:

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.

这篇关于使用ImageIO.read(文件)读取图像;导致java.lang.OutOfMemoryError:Java堆空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆