ExecutorService executor = Executors.newFixedThreadPool(Integer.valueOf(7));
try {
for(File file : files) {
executor.execute(new Runnable() {
@Override
public void run() {
construct(file, length);
}
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(null != executor) {
executor.shutdown();
}
}
其中线程个数取CPU核数+1
@Component
public class PostConstruct {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
int twoI = 0;
int threeI = 0;
@Value("${oldPath}")
private String oldPath;
@Value("${newDisk}")
private String newDisk;
@Value("${cpus}")
private String cpus;
@javax.annotation.PostConstruct
public void test() {
List<File> files = new ArrayList<>();
files = traverseFolder(oldPath,files);
int length = files.size();
System.out.println("总共"+length+"文件");
if(!CollectionUtils.isEmpty(files)) {
ExecutorService executor = Executors.newFixedThreadPool(Integer.valueOf(cpus));
try {
for(File file : files) {
executor.execute(new Runnable() {
@Override
public void run() {
construct(file, length);
}
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(null != executor) {
executor.shutdown();
}
}
}
}
public void construct(File file,Integer length){
String path = file.getAbsolutePath();
try (ImageInputStream iis = ImageIO.createImageInputStream(new File(path))) {
Iterator<ImageReader> it = ImageIO.getImageReaders(iis);
if (!it.hasNext()) {
System.out.println("Can't get ImageReaders");
return ;
}
ImageReader reader = it.next();
reader.setInput(iis);
IIOMetadata metadata = reader.getImageMetadata(0);
IIOMetadataNode rootNode = (IIOMetadataNode) metadata.getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName);
int xDpi = -1;
// 横DPI取得
NodeList nodes = rootNode.getElementsByTagName("HorizontalPixelSize");
if (nodes.getLength() > 0) {
IIOMetadataNode node = (IIOMetadataNode) nodes.item(0);
NamedNodeMap nodeAttrs = node.getAttributes();
Node attr = nodeAttrs.item(0);
xDpi = Math.round(25.4f / Float.parseFloat(attr.getNodeValue()));
}
if (xDpi == 300) {
String newImage = newDisk + path.substring(1, path.length());
File newImageFile = new File(newImage);
String absolutePath = newImageFile.getParent();
boolean directory = new File(absolutePath).isDirectory();
if (!directory) {
new File(absolutePath).mkdirs();
}
imageCopy(path, newImage);
Thumbnails.of(new File(path))
.size(1654, 2338)
.outputQuality(1)
.toFile(new File(path));
handleDpi(new File(path), 200, 200);
threeI++;
} else {
twoI++;
}
System.out.println(fmt.format(new Date())+":"+Thread.currentThread().getName()+":200dpi:" + twoI + "/" + length + ";300dpi:" + threeI + "/" + length);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 遍历目录
* @param path
* @param fileList
* @return
*/
public static List<File> traverseFolder(String path,List<File> fileList) {
File file = new File(path);
if (file.exists()) {
File[] files = file.listFiles();
if (null == files || files.length == 0) {
return fileList;
} else {
for (File file2 : files) {
if (file2.isDirectory()) {
traverseFolder(file2.getAbsolutePath(),fileList);
} else {
fileList.add(file2);
}
}
}
} else {
System.out.println("文件不存在!");
}
return fileList;
}
/**
* 拷贝图片
* @param oldImage
* @param newImage
*/
public static void imageCopy(String oldImage, String newImage) {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(oldImage);
//创建文件输出流对象读取指定目录下的文件
out = new FileOutputStream(newImage);
//定义一个int类型的变量length
int length = 0;
byte[] buff=new byte[1024];
//获取文件拷贝的时间
//通过循环将读取到的文件字节信息写入到新文件
while ((length = in.read(buff)) != -1) {
out.write(buff,0,length);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(null != out){
out.flush();
out.close();
}
//关闭流
if(null != in) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 压缩图片
* @param file
* @param xDensity
* @param yDensity
*/
public static void handleDpi(File file, int xDensity, int yDensity) {
FileOutputStream fileOutputStream = null;
try {
BufferedImage image = ImageIO.read(file);
fileOutputStream = new FileOutputStream(file);
JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(fileOutputStream);
JPEGEncodeParam jpegEncodeParam = jpegEncoder.getDefaultJPEGEncodeParam(image);
jpegEncodeParam.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);
jpegEncoder.setJPEGEncodeParam(jpegEncodeParam);
jpegEncodeParam.setQuality(0.75f, false);
jpegEncodeParam.setXDensity(xDensity);
jpegEncodeParam.setYDensity(yDensity);
jpegEncoder.encode(image, jpegEncodeParam);
image.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
//关流
try {
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}