繁体   English   中英

使用ImageIO.read(file);读取图像 导致java.lang.OutOfMemoryError:Java堆空间

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

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

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。

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

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;
}

我知道这是一个旧帖子,但我希望它将来能对某人有所帮助。

为什么不尝试在BufferedImage上调用flush( )。 它释放了一些持有的资源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM