我正在尝试使用 Asprise 裁剪应用程序裁剪 1000 张图像。
流程是,首先从 Content Manager 下载图像,然后裁剪图像,然后再次将裁剪后的图像上传到 Content Manager 中。
我已经创建了批处理文件来运行 1000 张图像, 最初它适用于 300 张图像并给出以下错误
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.awt.image.DataBufferInt.<init>(Unknown Source)
at java.awt.image.Raster.createPackedRaster(Unknown Source)
at java.awt.image.DirectColorModel.createCompatibleWritableRaster(
n Source)
at java.awt.image.BufferedImage.<init>(Unknown Source)
at sun.java2d.loops.GraphicsPrimitive.convertFrom(Unknown Source)
at sun.java2d.loops.GraphicsPrimitive.convertFrom(Unknown Source)
at sun.java2d.loops.MaskBlit$General.MaskBlit(Unknown Source)
at sun.java2d.loops.Blit$GeneralMaskBlit.Blit(Unknown Source)
at sun.java2d.pipe.DrawImage.blitSurfaceData(Unknown Source)
at sun.java2d.pipe.DrawImage.renderImageCopy(Unknown Source)
at sun.java2d.pipe.DrawImage.copyImage(Unknown Source)
at sun.java2d.pipe.DrawImage.copyImage(Unknown Source)
at sun.java2d.SunGraphics2D.drawImage(Unknown Source)
at sun.awt.image.ImageRepresentation.drawToBufImage(Unknown Source
at sun.java2d.pipe.DrawImage.copyImage(Unknown Source)
at sun.java2d.pipe.ValidatePipe.copyImage(Unknown Source)
at sun.java2d.SunGraphics2D.drawImage(Unknown Source)
at sun.java2d.SunGraphics2D.drawImage(Unknown Source)
然后我将堆大小增加到 -Xmx728M,可处理 500 多个图像,但再次出现相同的内存不足错误。
它在标记行上抛出错误
private BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage)image;
}
image = new ImageIcon(image).getImage();
boolean hasAlpha = hasAlpha(image);
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
int transparency = Transparency.OPAQUE;
if (hasAlpha) {
transparency = Transparency.BITMASK;
}
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(
image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) {
// The system does not have a screen
e.printStackTrace();
}
if (bimage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
if (hasAlpha) {
type = BufferedImage.TYPE_INT_ARGB;
}
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
}
Graphics g = bimage.createGraphics();
g.drawImage(image, 0, 0, null); //error
g.dispose();
return bimage;
}
我可以做什么来解决这个问题? 如何释放BufferedImage内存?
我用过
BufferedImageObj.flush();
BufferedImageObj=null;
但是这不起作用。
最佳答案
我怀疑您的错误实际上并不是该行的结果;相反,我怀疑绘制图像会将程序插入 OutOfMemory 状态。
您通常无法同时在内存中保存那么多图像。请记住,Java 默认情况下以全分辨率加载图像。我认为它不容易容纳数百张图像。确保您只在特定时刻加载您需要的内容。然后,当不再需要该图像时,通过将图像设置为 null,让 JVM 垃圾回收内存。
关于java - 图像和堆大小问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15964105/