我使用下面的代码将BufferedIMage写入磁盘,但如果我不关闭程序,我无法用Windows打开它。我当时认为writer.dispose会做的伎俩但是我错了我想,我错过了什么?感谢您的帮助!
private void saveToFile( BufferedImage img, File file ) throws IOException
{
ImageWriter writer = null;
java.util.Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
if( iter.hasNext() )
{
writer = (ImageWriter)iter.next();
}
ImageOutputStream ios = ImageIO.createImageOutputStream( file );
writer.setOutput(ios);
ImageWriteParam param = new JPEGImageWriteParam( java.util.Locale.getDefault() );
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ;
param.setCompressionQuality(0.98f);
writer.write(null, new IIOImage( img, null, null ), param);
writer.dispose();// here the dispose not working
}
答案 0 :(得分:4)
我猜你也应该关闭ios
。请尝试以下方法:
private void saveToFile( BufferedImage img, File file ) throws IOException
{
ImageWriter writer = null;
java.util.Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
if( iter.hasNext() )
{
writer = (ImageWriter)iter.next();
}
try {
ImageOutputStream ios = ImageIO.createImageOutputStream( file );
writer.setOutput(ios);
ImageWriteParam param = new JPEGImageWriteParam( java.util.Locale.getDefault() );
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ;
param.setCompressionQuality(0.98f);
writer.write(null, new IIOImage( img, null, null ), param);
}
finally {
if (ios != null) {
try {
ios.flush();
}
catch ( IOException e) {
}
try {
ios.close();
}
catch ( IOException e) {
}
}
if (writer != null) {
writer.dispose();
}
}
}