我想压缩大约 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),它仍然不起作用!谁知道解决方法?请帮帮我,谢谢!