需求
公司的图片需要压缩,网上又没有合适的压缩工具,于是突发奇想用java 写了一个压缩工具。
程序核心代码
import net.coobird.thumbnailator.Thumbnails;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
public class Start {
public static void main(String[] args){
String path = System.getProperty("user.dir");
String outPath = path + "\\out";
File outFileDir = new File(outPath);
if(!outFileDir.exists()){
outFileDir .mkdir();
}
String[] imgType = new String[]{"jpg", "png"};
System.out.println("当前文件路径:" + path);
File fileDir = new File(path);
File[] files = fileDir.listFiles();
for (File tmpFile :
files) {
String[] suffixTmp = tmpFile.getName().split("\\.");
String suffix = suffixTmp[suffixTmp.length - 1];
String[] nameTmp = tmpFile.getName().split("\\\\");
String name = nameTmp[nameTmp.length - 1].split("\\.")[0];
if(Arrays.asList(imgType).contains(suffix)) {
try {
Thumbnails.of(tmpFile)
.size(600, 800)
.toFile(new File(outPath + "\\" + name + "." + suffix));
System.out.println("转换成功:" + tmpFile.getName());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
pom配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.xszn</groupId>
<artifactId>dealwith_pic</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>Start</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
|