简体   繁体   English

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

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

I am using a ImageIO API to write a PNG file. 我正在使用ImageIO API编写PNG文件。 This code is called in a loop and causes an OutOfMemory error. 在循环中调用此代码,并导致OutOfMemory错误。 Is there anyway the following code can be fixed to avoid the OutOfMemory error? 无论如何,可以固定以下代码来避免OutOfMemory错误吗? Or is the only option to increase the JVM heap size? 还是增加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 heap size is 1024M. Java堆大小为1024M。

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). 我遇到了类似的问题,我必须读取36张图像,将它们裁剪并保存到一个新文件中(一次一个)。 I figured out that I had to set the images to null after each iteration to allow Java to do its garbage collection. 我发现必须在每次迭代后将图像设置为null,以允许Java进行垃圾回收。 Ie: 即:

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. 我知道这是一个旧帖子,但我希望它将来能对某人有所帮助。

Why dont u try calling flush( ) on BufferedImage . 为什么不尝试在BufferedImage上调用flush( )。 It releases some of the resources held. 它释放了一些持有的资源。

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

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