我正在使用 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;
}
我知道它现在是一个旧帖子,但我希望它可以帮助将来的人。
关于java - 使用 ImageIO.read(file) 读取图像;导致 java.lang.OutOfMemoryError : Java heap space,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8222224/