package cn.windy.samary.utils;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.n3r.idworker.Sid;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
-
@Auther: kxs
-
@Date: 2019/11/19 14:46
-
@Description:
/
public class ImageUtils {
public static Logger logger = Logger.getLogger(DateUtil.class);
/*
*-
@Description:保存图片并且生成缩略图
-
@param imageFile 图片文件
-
@param request 请求对象
-
@param uploadPath 上传目录
-
@return
*/
public static Res uploadFileAndCreateThumbnail(MultipartFile imageFile, HttpServletRequest request, String uploadPath) {
if(imageFile == null ){
return Res.error(500,“imageFile不能为空”);
}
String fileDirectory = new Sid().nextShort();
//拼接后台文件名称
String pathName = fileDirectory +"."
+ FilenameUtils.getExtension(imageFile.getOriginalFilename());
//构建保存文件路劲
//2016-5-6 yangkang 修改上传路径为服务器上
String realPath = ResourceBundleUtil.getString(“system”, “fileupload.path”);
//获取服务器绝对路径 linux 服务器地址 获取当前使用的配置文件配置
//String urlString=PropertiesUtil.getInstance().getSysPro(“uploadPath”);
//拼接文件路劲
String filePathName = realPath + File.separator + pathName;
logger.info(“图片上传路径:”+filePathName);
//判断文件保存是否存在
File file = new File(filePathName);
if (file.getParentFile() != null || !file.getParentFile().isDirectory()) {
//创建文件
file.getParentFile().mkdirs();
}InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
inputStream = imageFile.getInputStream();
fileOutputStream = new FileOutputStream(file);
//写出文件
//2016-05-12 yangkang 改为增加缓存
// IOUtils.copy(inputStream, fileOutputStream);
byte[] buffer = new byte[2048];
IOUtils.copyLarge(inputStream, fileOutputStream, buffer);
buffer = null;} catch (IOException e) {
filePathName = null;
return Res.error(500, “操作失败”);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (IOException e) {
filePathName = null;
return Res.error(500, “操作失败”);
}
}// String fileId = FastDFSClient.uploadFile(file, filePathName);
/**
- 缩略图begin
*/
//拼接后台文件名称
String thumbnailPathName = fileDirectory +“small.”
+ FilenameUtils.getExtension(imageFile.getOriginalFilename());
//added by yangkang 2016-3-30 去掉后缀中包含的.png字符串
if(thumbnailPathName.contains(".png")){
thumbnailPathName = thumbnailPathName.replace(".png", “.jpg”);
}
long size = imageFile.getSize();
double scale = 1.0d ;
if(size >= 2001024){
if(size > 0){
scale = (2001024f) / size ;
}
}//拼接文件路劲
String thumbnailFilePathName = realPath + File.separator + thumbnailPathName;
try {
//added by chenshun 2016-3-22 注释掉之前长宽的方式,改用大小
// Thumbnails.of(filePathName).size(width, height).toFile(thumbnailFilePathName);
if(size < 200*1024){
logger.info("********************不压缩");
Thumbnails.of(filePathName).scale(1f).outputFormat(“jpg”).toFile(thumbnailFilePathName);
// file.delete();
}else{
logger.info("**********************压缩");
Thumbnails.of(filePathName).scale(1f).outputQuality(scale).outputFormat(“jpg”).toFile(thumbnailFilePathName);
// file.delete();
}} catch (Exception e1) {
logger.info("*************");
return Res.error(500, “操作失败”);
}
/**- 缩略图end
*/
Map<String, Object> map = new HashMap<>();
//原图地址
map.put(“originalUrl”, pathName);
//缩略图地址
map.put(“path”, thumbnailPathName);
return Res.data(map);
} - 缩略图begin
/**
public class Res extends HashMap<String, Object> {
private static final long serialVersionUID = 1L;
public Res() {
put(“code”, 200);
put(“msg”, “操作成功!”);
}- @Description:压缩图片 Res是自己定义的map,可以修改,用这个进行压缩,上面那个方法包括原图
- @param imageFile 图片文件
- @return
*/
public static Res uploadFileAndCreateThumbnail(MultipartFile file) {
String name=UUID.randomUUID().toString().replaceAll("-","");//用UUID对图片重新命名,避免上传图片名重复
String ext=FilenameUtils.getExtension(file.getOriginalFilename());//得到上传图片的扩展名
//图片路径
String upaloadUrl = ResourceBundleUtil.getString(“system”, “fileupload.path”);
File dest=new File(upaloadUrl+File.separator+name+"."+ext);//要保存位置 例:E:/AFRA/image/图片名.jpg(此处为绝对路径)
File fileDir=new File(upaloadUrl);
//如果此文件不存在则创建
if(!fileDir.exists()){
fileDir.mkdirs();
}
try{
Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.25f).toFile(dest);//压缩成原图的0.25
}catch (IOException e){
logger.info("***********e");
try{
logger.info("***********异常");
file.transferTo(dest);//如压缩上传失败,则使用原生的上传压缩
}catch (IOException e1){
logger.info("***********异常1");
e1.printStackTrace();
}
}
Map<String, Object> map = new HashMap<>();
//缩略图地址
map.put(“path”, name+"."+ext);
return Res.data(map);
}
-
所需maven包
net.coobird
thumbnailator
0.4.8
//maven显示不全,不知道原因,第一个是groupId,第二个是artifactId第三个是version
}