手里有些图片,几万张,想要对这些图片生成预览图,但是总是报错,麻烦各位大大帮我看下我代码里面问题出在何处,谢谢了!
package liuc.test;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* @author Liuc
* @date 2013-4-17
*/
public class CreateBrevImg {
public static void main(String[] args) {
String filePath = "C:\\Users\\Administrator\\Desktop\\testP";
String brevFilePath = "C:\\Users\\Administrator\\Desktop\\Brev";
CreateBrevImg c = new CreateBrevImg();
c.getBrev(filePath, brevFilePath);
}
public void getBrev(String filePath, String brevFilePath){
File file = new File(filePath);
File[] files = file.listFiles();
InputStream is = null ;
String tmpBrevPicPath = "";
File tmpFile;
int i = 0;
int new_w=150;
int new_h=100;
Image src;
BufferedImage tag;
FileOutputStream newimage;
JPEGImageEncoder encoder;
try {
for (File file2 : files) {
if("Brev".equals(file2.getName())){
continue;
}
// System.out.println(file2.getAbsolutePath());
tmpBrevPicPath = brevFilePath + "\\" + file2.getName();
if(file2.getName().indexOf('.')==-1){
continue;
}
tmpFile = file2;
is = new FileInputStream(tmpFile);
// ImgUtil.brvePic(tmpBrevPicPath, is);
src = javax.imageio.ImageIO.read(is);
tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src,0,0,new_w,new_h,null);
newimage=new FileOutputStream(tmpBrevPicPath);
encoder = JPEGCodec.createJPEGEncoder(newimage);
encoder.encode(tag);
newimage.close();
i++;
}
} catch (Exception e) {
e.printStackTrace();
} finally{
System.out.println("已转换" + i + "张图片");
is = null ;
files = null;
file = null;
src = null;
tag = null;
newimage = null;
tmpFile = null;
encoder = null;
}
}
}
------解决方案--------------------
for循环一次就关闭流,因为你每次for循环进去后是重新打开流的,或者中间flush以下。
------解决方案--------------------