执行javax.imageio.ImageIO.read(“filename”)时的java.lang.OutOfMemoryError

时间:2012-07-26 16:24:12

标签: java eclipse image

我想压缩大约4M或更多的“JPG”图片。这是我的代码:

public static void Compress(String sourceFolder,String destFolder,double proportion) throws IOException
{
    File source=new File(sourceFolder);
    File[] sourceFiles=null;
    if(source.isDirectory())
    {
        sourceFiles=source.listFiles();
        for(int i=0;i<sourceFiles.length;i++)
        {
            String name="";
            javax.imageio.ImageIO.setUseCache(false);
            Image src = javax.imageio.ImageIO.read(sourceFiles[i]);
            name=sourceFiles[i].getName();
            int width=src.getWidth(null);
            int height=src.getHeight(null);
            destWidth=(int) (height*proportion);
            destHeight=(int) (width*proportion);
            BufferedImage tag=new BufferedImage(destWidth,destHeight,BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();  
            g.drawImage(src, 0, 0, destWidth, destHeight, null);
            src.flush();
            src=null;
            FileOutputStream out = new FileOutputStream(destFolder+"/"+name);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
            encoder.encode(tag);  
            out.close(); 
        }
    }
    else
        System.exit(0);
}

运行时

Image src = javax.imageio.ImageIO.read("filename");

发生异常:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.awt.image.DataBufferByte.<init>(DataBufferByte.java:58)
at java.awt.image.ComponentSampleModel.createDataBuffer(ComponentSampleModel.java:397)
at java.awt.image.Raster.createWritableRaster(Raster.java:938)
at javax.imageio.ImageTypeSpecifier.createBufferedImage(ImageTypeSpecifier.java:1056)
at javax.imageio.ImageReader.getDestination(ImageReader.java:2879)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:943)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:915)
at javax.imageio.ImageIO.read(ImageIO.java:1422)
at javax.imageio.ImageIO.read(ImageIO.java:1282)
at functions.CompressImage.Compress(CompressImage.java:50)
at functions.CompressImage.main(CompressImage.java:24)

我尝试了运行参数(-Xms = 1g),它仍然不起作用! 谁知道解决方案?请帮帮我,谢谢!

1 个答案:

答案 0 :(得分:0)

您需要获取堆转储并进行分析。所以最简单的方法是添加像

这样的JVM参数
 -XX:+HeapDumpOnOutOfMemoryError 

这将自动创建堆转储/稍后您可以使用java分析器(yourkit,jprofiler等)分析出错了什么