首页>代码>SpringBoot集成Thumbnailator压缩图片>/springboot-thumbnailator/src/main/java/com/simon/springbootthumbnailator/util/ImageUtil.java
package com.simon.springbootthumbnailator.util;
import com.simon.springbootthumbnailator.config.ImgZipConfig;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
/**
* 图片压缩工具类
*
* @author Simon
*/
public class ImageUtil {
public static String imgUploadCompress(MultipartFile multipartFile, String path, Double scale) throws IOException {
//图片非法--非图片格式
if (!checkImage(multipartFile)) {
return "-1";
}
// 如果没有传默认项目名称,走默认配置
if (path == null || path.trim().equals("")) {
path = ImgZipConfig.name;
}
// 如果没有传默认项目名称,走默认配置
if (scale == null) {
scale = ImgZipConfig.defaultScale;
}
// 如果压缩比例非法,走默认配置
if (scale > 1 || scale <= 0) {
scale = ImgZipConfig.defaultScale;
}
String origFilename = UUID.randomUUID().toString() + getFileExtension(multipartFile);
String imagesPath = createFileBySysTime(path + "/");
String newPath = imagesPath + "/" + origFilename;
File dest = new File(ImgZipConfig.imagePath + newPath);
try {
Thumbnails.of(multipartFile.getInputStream()).scale(scale).toFile(dest);
return newPath;
} catch (IOException e) {
try {
multipartFile.transferTo(dest);
return newPath;
} catch (IOException e1) {
e1.printStackTrace();
return "0";
}
}
}
/**
* 根据时间创建文件夹
*
* @param path
* @return
* @throws IOException
*/
private static String createFileBySysTime(String path) throws IOException {
Calendar calendar = Calendar.getInstance();
Date time = calendar.getTime();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String fileName = format.format(time);
String newPath = path + fileName;
File file = new File(ImgZipConfig.imagePath + newPath);
if (!file.exists()) {
if (!file.mkdir()) {
System.out.println("当前路径不存在,创建创建路径");
file.mkdirs();
}
}
System.out.println("创建成功" + file.toString());
return newPath;
}
/**
* 获取文件后缀
*
* @param cFile
* @return
*/
private static String getFileExtension(MultipartFile cFile) {
String originalFileName = cFile.getOriginalFilename();
return originalFileName.substring(originalFileName.lastIndexOf("."));
}
/**
* 校验图片是否为图片格式
*
* @param multipartFile
* @return
*/
private static boolean checkImage(MultipartFile multipartFile) {
try {
BufferedImage bi = ImageIO.read(multipartFile.getInputStream());
if (bi == null) {
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}

最近下载
最近浏览