300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 图片压缩上传Thumbnailator 插件

图片压缩上传Thumbnailator 插件

时间:2020-12-16 17:00:20

相关推荐

图片压缩上传Thumbnailator 插件

假如你现在还在为自己的技术担忧,假如你现在想提升自己的工资,假如你想在职场上获得更多的话语权,假如你想顺利的度过35岁这个魔咒,假如你想体验BAT的工作环境,那么现在请我们一起开启提升技术之旅吧,详情请点击http://106.12.206.16:8080/qingruihappy/index.html

一,接口已经写死

1 public static String upload(String appCode, MultipartFile inputFile)

1 public static String upload(String appCode, File inputFile)

后台已经写死成这两种格式了

1 MultipartFile inputFile = multipartRequest.getFile(fileElementId); 2 CommonsMultipartFile cf= (CommonsMultipartFile)inputFile; 3 DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 4 String storeLocation = fi.getStoreLocation().toString(); 5 originalFilename = inputFile.getOriginalFilename(); 6 imageType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).trim().toLowerCase(); 7 long sizeOther = inputFile.getSize(); 8 size = sizeOther +"kb"; 9 double scale = 1.0d ;10 if(sizeOther >= 3*1024*1024){11 if(sizeOther > 0){12 scale = (3*1024*1024f) / sizeOther ;13 }14 Thumbnails.of(inputFile.getInputStream()).scale(1f).outputQuality(scale).outputFormat("jpg").toFile(storeLocation);15 File file = new File(storeLocation+".jpg");16 fssId = FssFileClient.upload("app-weixin", file);17 file.delete();18 }else{19 fssId = FssFileClient.upload("app-weixin", inputFile);20 }

StoreLocation=/opt/oracle/tomcat/t-2/work/Catalina/localhost/weixin/upload_6af40051_15fc4efb752__7ffd_00000001.tmp

StoreLocation=D:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp5\work\Catalina\localhost\weixin\upload__ad6bac5_15fc4f98fa1__8000_00000000.tmp

去找到这个路径,因为在这个路径下会产生一个缓存文件,对这个缓存文件进行压缩,压缩完了之上传,上传至后在删除。

二,就是自己创建一个文件,然后在进行修改

1MultipartFile inputFile = multipartRequest.getFile(fileElementId); 2 originalFilename = inputFile.getOriginalFilename(); 3 imageType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).trim().toLowerCase(); 4 long sizeOther = inputFile.getSize(); 5 size = sizeOther +"kb"; 6 double scale = 1.0d ; 7 if(sizeOther >= 3*1024*1024){ 8 if(sizeOther > 0){ 9 scale = (3*1024*1024f) / sizeOther ;10 }11 String path=request.getSession().getServletContext().getRealPath("/")+"js" + System.getProperty("file.separator") + "upload"+System.getProperty("file.separator")+"yasuo."+imageType;12 Thumbnails.of(inputFile.getInputStream()).scale(1f).outputQuality(scale).toFile(path);13 File file = new File(path);14 fssId = FssFileClient.upload("app-weixin", file);15 }else{16 fssId = FssFileClient.upload("app-weixin", inputFile);17 }

自己创建了一个upload的文件,在这个里面进行修改。

三,详细的 讲解

1 <!-- 图片缩略图 -->2 <dependency>3 <groupId>net.coobird</groupId>4 <artifactId>thumbnailator</artifactId>5 <version>0.4.8</version>6 </dependency>

3.1,按指定大小把图片进行缩放(会遵循原图高宽比例)

1 //按指定大小把图片进行缩和放(会遵循原图高宽比例) 2 //此处把图片压成400×500的缩略图3 Thumbnails.of(fromPic).size(400,500).toFile(toPic);//变为400*300,遵循原图比例缩或放到400*某个高度

3.2,按照指定比例进行缩小和放大

1 //按照比例进行缩小和放大2 Thumbnails.of(fromPic).scale(0.2f).toFile(toPic);//按比例缩小3 Thumbnails.of(fromPic).scale(2f);//按比例放大

图片尺寸不变,压缩图片文件大小

1 //图片尺寸不变,压缩图片文件大小outputQuality实现,参数1为最高质量2 Thumbnails.of(fromPic).scale(1f).outputQuality(0.25f).toFile(toPic);

我这里只使用了 图片尺寸不变,压缩文件大小 源码

1 /** 2* 3* @Description:保存图片并且生成缩略图 4* @param imageFile 图片文件 5* @param request 请求对象 6* @param uploadPath 上传目录 7* @return 8*/ 9public static BaseResult uploadFileAndCreateThumbnail(MultipartFile imageFile,HttpServletRequest request,String uploadPath) { 10 if(imageFile == null ){ 11 return new BaseResult(false, "imageFile不能为空"); 12 } 1314 if (imageFile.getSize() >= 10*1024*1024) 15 { 16 return new BaseResult(false, "文件不能大于10M"); 17 } 18 String uuid = UUID.randomUUID().toString(); 1920 String fileDirectory = CommonDateUtils.date2string(new Date(), CommonDateUtils.YYYY_MM_DD); 2122 //拼接后台文件名称 23 String pathName = fileDirectory + File.separator + uuid + "." 24 + FilenameUtils.getExtension(imageFile.getOriginalFilename()); 25 //构建保存文件路劲 26 //-5-6 yangkang 修改上传路径为服务器上 27 String realPath = request.getServletContext().getRealPath("uploadPath"); 28 //获取服务器绝对路径 linux 服务器地址 获取当前使用的配置文件配置 29 //String urlString=PropertiesUtil.getInstance().getSysPro("uploadPath"); 30 //拼接文件路劲 31 String filePathName = realPath + File.separator + pathName; 32 log.info("图片上传路径:"+filePathName); 33 //判断文件保存是否存在 34 File file = new File(filePathName); 35 if (file.getParentFile() != null || !file.getParentFile().isDirectory()) { 36 //创建文件 37 file.getParentFile().mkdirs(); 38 } 3940 InputStream inputStream = null; 41 FileOutputStream fileOutputStream = null; 42 try { 43 inputStream = imageFile.getInputStream(); 44 fileOutputStream = new FileOutputStream(file); 45 //写出文件 46 //-05-12 yangkang 改为增加缓存 47 // IOUtils.copy(inputStream, fileOutputStream); 48 byte[] buffer = new byte[2048]; 49 IOUtils.copyLarge(inputStream, fileOutputStream, buffer); 50 buffer = null; 51 52 } catch (IOException e) { 53 filePathName = null; 54 return new BaseResult(false, "操作失败", e.getMessage()); 55 } finally { 56 try { 57 if (inputStream != null) { 58 inputStream.close(); 59 } 60 if (fileOutputStream != null) { 61 fileOutputStream.flush(); 62 fileOutputStream.close(); 63 } 64 } catch (IOException e) { 65 filePathName = null; 66 return new BaseResult(false, "操作失败", e.getMessage()); 67 } 68} 697071 // String fileId = FastDFSClient.uploadFile(file, filePathName); 7273 /** 74* 缩略图begin 75*/ 7677 //拼接后台文件名称 78 String thumbnailPathName = fileDirectory + File.separator + uuid + "small." 79 + FilenameUtils.getExtension(imageFile.getOriginalFilename()); 80 //added by yangkang -3-30 去掉后缀中包含的.png字符串 81 if(thumbnailPathName.contains(".png")){ 82 thumbnailPathName = thumbnailPathName.replace(".png", ".jpg"); 83 } 84 long size = imageFile.getSize(); 85 double scale = 1.0d ; 86 if(size >= 200*1024){ 87 if(size > 0){ 88 scale = (200*1024f) / size ; 89 } 90 } 919293 //拼接文件路劲 94 String thumbnailFilePathName = realPath + File.separator + thumbnailPathName; 95 try { 96 //added by chenshun -3-22 注释掉之前长宽的方式,改用大小 97 // Thumbnails.of(filePathName).size(width, height).toFile(thumbnailFilePathName); 98 if(size < 200*1024){ 99 Thumbnails.of(filePathName).scale(1f).outputFormat("jpg").toFile(thumbnailFilePathName);100 }else{101 Thumbnails.of(filePathName).scale(1f).outputQuality(scale).outputFormat("jpg").toFile(thumbnailFilePathName);102 }103 104 } catch (Exception e1) {105 return new BaseResult(false, "操作失败", e1.getMessage());106 }107 /**108* 缩略图end109*/110 111 Map<String, Object> map = new HashMap<String, Object>();112 //原图地址113 map.put("originalUrl", pathName);114 //缩略图地址115 map.put("thumbnailUrl", thumbnailPathName);116 return new BaseResult(true, "操作成功", map);117}

获取当前使用的配置文件信息

1 /** 2* 根据key从gzt.properties配置文件获取配置信息 3* @param key 键值 4* @return 5*/ 6public String getSysPro(String key){ 7 return getSysPro(key, null); 8} 9/**10* 根据key从gzt.properties配置文件获取配置信息 11* @param key 键值12* @param defaultValue 默认值13* @return14*/15public String getSysPro(String key,String defaultValue){16 return getValue("spring/imageserver-"+System.getProperty("spring.profiles.active")+".properties", key, defaultValue);17}

例:

1 //获取服务器绝对路径 linux 服务器地址 2 String urlString=PropertiesUtil.getInstance().getSysPro("uploadPath");

PropertiesUtil 类

1 package com.mon.properties; 2 3 import org.slf4j.Logger; 4 import org.slf4j.LoggerFactory; 5 6 import java.io.IOException; 7 import java.io.InputStream; 8 import java.io.InputStreamReader; 9 import java.util.Properties;10 import java.util.concurrent.ConcurrentHashMap;11 12 /**13 * 14 * @ClassName PropertiesUtil.java 15 * @Description 系统配置工具类16 * @author caijy17 * @date 6月9日 上午10:50:3818 * @version 1.0.019 */20 public class PropertiesUtil {21private Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);22private ConcurrentHashMap<String, Properties> proMap;23private PropertiesUtil() {24 proMap = new ConcurrentHashMap<String, Properties>();25}26private static PropertiesUtil instance = new PropertiesUtil();27 28/**29* 获取单例对象30* @return31*/32public static PropertiesUtil getInstance()33{34 return instance;35}36 37/**38* 根据key从gzt.properties配置文件获取配置信息 39* @param key 键值40* @return41*/42public String getSysPro(String key){43 return getSysPro(key, null);44}45/**46* 根据key从gzt.properties配置文件获取配置信息 47* @param key 键值48* @param defaultValue 默认值49* @return50*/51public String getSysPro(String key,String defaultValue){52 return getValue("spring/imageserver-"+System.getProperty("spring.profiles.active")+".properties", key, defaultValue);53}54/**55* 从配置文件中获取对应key值56* @param fileName 配置文件名57* @param key key值58* @param defaultValue 默认值59* @return60*/61public String getValue(String fileName,String key,String defaultValue){62 String val = null;63 Properties properties = proMap.get(fileName);64 if(properties == null){65 InputStream inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);66try {67 properties = new Properties();68 properties.load(new InputStreamReader(inputStream,"UTF-8"));69 proMap.put(fileName, properties);70 val = properties.getProperty(key,defaultValue);71 } catch (IOException e) {72 logger.error("getValue",e);73 }finally{74 try {75 if (inputStream != null) { 76inputStream.close();77 }78 } catch (IOException e1) {79 logger.error(e1.toString());80 }81 }82 }else{83 val = properties.getProperty(key,defaultValue);84 }85 return val;86}87 }

假如你现在还在为自己的技术担忧,假如你现在想提升自己的工资,假如你想在职场上获得更多的话语权,假如你想顺利的度过35岁这个魔咒,假如你想体验BAT的工作环境,那么现在请我们一起开启提升技术之旅吧,详情请点击http://106.12.206.16:8080/qingruihappy/index.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。