前言
Thumbnails是一个图片处理库,它可以对图片进行压缩、裁剪、缩放等操作。在进行文件压缩时,可以使用Thumbnails来压缩图片文件。
所需依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-mock -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<version>2.0.8</version>
<scope>compile</scope>
</dependency>
<!-- 文件压缩 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.18</version>
</dependency>
主要代码
/**
* 文件压缩--得到File
* @param tempPath 临时文件目录
* @param multipartFile 要压缩的文件
* @param width 压缩后的宽
* @param height 压缩后的高
* @return java.io.File
*/
public static File compressFile(String tempPath, MultipartFile multipartFile, int width, int height) throws IOException {
//确保此路径下有 temp.jpg文件
File file = new File(tempPath+"/temp.jpg");
Thumbnails.of(multipartFile.getInputStream()).size(width,height).toFile(file);
return file;
}
/**
*
* 文件压缩--转成MultipartFile
* @param tempPath 临时文件目录
* @param multipartFile 要压缩的文件
* @param width 压缩后的宽
* @param height 压缩后的高
* @return org.springframework.web.multipart.MultipartFile
*/
public static MultipartFile compressMultipart(String tempPath, MultipartFile multipartFile, int width, int height) throws IOException {
File file = compressFile(tempPath,multipartFile,width,height);
FileInputStream input = new FileInputStream(file);
return new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input));
}
是不是很简单0.0
好了,到这就结束啦!!!
----------------------------------------------------------------------------THANKS !!!-----------------------------------------------------------------------