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

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

问题描述

我正在使用 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(file) 读取图像;导致 java.lang.OutOfMemoryError: Java heap space的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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