import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
public class ImgTools {
/**
* <code> java ImgTools /webapps/img/imgs/roomRegister 500 > ImgTools.out & <code>
*/
public static void main(String[] args) throws IOException {
if (args == null)
System.err.println("java ImgTools 图片所在文件夹 图片压缩尺寸 [图片转移目录(不写即覆盖)]");
String path = args[0];
long size = Long.valueOf(args[1]) * 1024;// kb
String tarPath = null;
if (args.length > 2)
tarPath = args[2];
// 1.读文件
List<File> list = readFiles(path);
System.out.println("共读取文件:" + list.size());
// 2.压缩图片
reSizeImg(list, size, tarPath);
}
/**
* 1.读文件
*/
private static List<File> readFiles(String path) throws FileNotFoundException {
List<File> list = new ArrayList<>();
File file = new File(path);
if (!file.isDirectory()) {
list.add(file);
} else {
File[] files = file.listFiles();
for (File file2 : files)
list.addAll(readFiles(file2.getPath()));
}
return list;
}
/**
* 2.压缩图片,等比
*/
private static void reSizeImg(List<File> files, long size, String tarPath) throws IOException {
for (int i = 0; i < files.size(); i++) {
File file = files.get(i);
System.out.print("\n文件数:[" + i + "/" + files.size() + "],正在处理文件:" + file.getPath());
long oldSize = file.length();
if (oldSize <= size)
continue;
boolean check = true;
float scale = 0.9f;
int count = 0;
String outPath = tarPath == null ? file.getPath() : tarPath + "/" + file.getName();
while (check) {
count++;
BufferedImage src = ImageIO.read(file);
if (src != null) {
int deskHeight = (int) (src.getHeight(null) * scale);
int deskWidth = (int) (src.getWidth(null) * scale);
BufferedImage tag = new BufferedImage(deskWidth, deskHeight, BufferedImage.TYPE_3BYTE_BGR);
tag.getGraphics().drawImage(src, 0, 0, deskWidth, deskHeight, null);
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
// JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(byteOut);
// encoder.encode(tag); // 近JPEG编码
ImageIO.write(tag, "JPEG", byteOut);
if (byteOut.size() > size) {
scale = scale - 0.1f;
continue;
} else {
check = !check;
}
saveFile(outPath, byteOut.toByteArray());
System.out.print(",压缩率为:" + scale + ",转换次数:" + count + ",输出文件:" + outPath);
} else {
check = !check;
}
}
}
System.out.println("=== 压缩完成 ===");
}
/**
* 3.保存文件
*/
private static void saveFile(String outPath, byte[] data) throws IOException {
FileOutputStream deskImage = new FileOutputStream(outPath); // 输出到文件流
deskImage.write(data);
deskImage.close();
}
}