java 图片 批量 压缩 +全部压缩
2012-05-18 10:07 java ee spring 阅读(506) 评论(0) 编辑 收藏 举报
/*
oldsrc : 原图片地址文件夹 如 'd:/'
newsrc : 压缩后图片地址文件夹 如 'e:/'
widthdist,heightdist : 压缩后的宽和高
createtime 2010-11-25
@auto yijianfeng
*/
int heightdist) {
try {
File file = new File(oldsrc);
if (!file.exists()) {
return;
}
File[] srcfile = file.listFiles();
if (srcfile != null) {
for (int i = 0; i < srcfile.length; i++) {
if (srcfile[i].isFile()
&& (srcfile[i].getName().endsWith(".jpg")
|| srcfile[i].getName().endsWith(".JPG")
|| srcfile[i].getName().endsWith(".gif") || srcfile[i]
.getName().endsWith(".gif"))) {
Image src = javax.imageio.ImageIO.read(srcfile[i]);
BufferedImage tag = new BufferedImage((int) widthdist,
(int) heightdist, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(
src.getScaledInstance(widthdist, heightdist,
Image.SCALE_SMOOTH), 0, 0, null);
FileOutputStream out = new FileOutputStream(newsrc
+ srcfile[i].getName());
JPEGImageEncoder encoder = JPEGCodec
.createJPEGEncoder(out);
System.out.println(oldsrc + "/" + srcfile[i].getName());
encoder.encode(tag);
out.close();
} else {
reduceImgAll(oldsrc + srcfile[i].getName(), newsrc,
widthdist, heightdist);
}
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}