图片压缩上传Thumbnailator 插件
一,接口已经写死
public static String upload(String appCode, MultipartFile inputFile)
public static String upload(String appCode, File inputFile)
后台已经写死成这两种格式了
MultipartFile inputFile = multipartRequest.getFile(fileElementId);
CommonsMultipartFile cf= (CommonsMultipartFile)inputFile;
DiskFileItem fi = (DiskFileItem)cf.getFileItem();
String storeLocation = fi.getStoreLocation().toString();
originalFilename = inputFile.getOriginalFilename();
imageType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).trim().toLowerCase();
long sizeOther = inputFile.getSize();
size = sizeOther +"kb";
double scale = 1.0d ;
if(sizeOther >= 3*1024*1024){
if(sizeOther > 0){
scale = (3*1024*1024f) / sizeOther ;
}
Thumbnails.of(inputFile.getInputStream()).scale(1f).outputQuality(scale).outputFormat("jpg").toFile(storeLocation);
File file = new File(storeLocation+".jpg");
fssId = FssFileClient.upload("app-weixin", file);
file.delete();
}else{
fssId = FssFileClient.upload("app-weixin", inputFile);
}
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
去找到这个路径,因为在这个路径下会产生一个缓存文件,对这个缓存文件进行压缩,压缩完了之上传,上传至后在删除。
二,就是自己创建一个文件,然后在进行修改
MultipartFile inputFile = multipartRequest.getFile(fileElementId);
originalFilename = inputFile.getOriginalFilename();
imageType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).trim().toLowerCase();
long sizeOther = inputFile.getSize();
size = sizeOther +"kb";
double scale = 1.0d ;
if(sizeOther >= 3*1024*1024){
if(sizeOther > 0){
scale = (3*1024*1024f) / sizeOther ;
}
String path=request.getSession().getServletContext().getRealPath("/")+"js" + System.getProperty("file.separator") + "upload"+System.getProperty("file.separator")+"yasuo."+imageType;
Thumbnails.of(inputFile.getInputStream()).scale(1f).outputQuality(scale).toFile(path);
File file = new File(path);
fssId = FssFileClient.upload("app-weixin", file);
}else{
fssId = FssFileClient.upload("app-weixin", inputFile);
}
自己创建了一个upload的文件,在这个里面进行修改。
三,详细的 讲解
<!-- 图片缩略图 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
3.1,按指定大小把图片进行缩放(会遵循原图高宽比例)
//按指定大小把图片进行缩和放(会遵循原图高宽比例)
//此处把图片压成400×500的缩略图
Thumbnails.of(fromPic).size(400,500).toFile(toPic);//变为400*300,遵循原图比例缩或放到400*某个高度
3.2,按照指定比例进行缩小和放大
//按照比例进行缩小和放大
Thumbnails.of(fromPic).scale(0.2f).toFile(toPic);//按比例缩小
Thumbnails.of(fromPic).scale(2f);//按比例放大
图片尺寸不变,压缩图片文件大小
//图片尺寸不变,压缩图片文件大小outputQuality实现,参数1为最高质量
Thumbnails.of(fromPic).scale(1f).outputQuality(0.25f).toFile(toPic);
我这里只使用了 图片尺寸不变,压缩文件大小 源码
/**
*
* @Description:保存图片并且生成缩略图
* @param imageFile 图片文件
* @param request 请求对象
* @param uploadPath 上传目录
* @return
*/
public static BaseResult uploadFileAndCreateThumbnail(MultipartFile imageFile,HttpServletRequest request,String uploadPath) {
if(imageFile == null ){
return new BaseResult(false, "imageFile不能为空");
}
if (imageFile.getSize() >= 10*1024*1024)
{
return new BaseResult(false, "文件不能大于10M");
}
String uuid = UUID.randomUUID().toString();
String fileDirectory = CommonDateUtils.date2string(new Date(), CommonDateUtils.YYYY_MM_DD);
//拼接后台文件名称
String pathName = fileDirectory + File.separator + uuid + "."
+ FilenameUtils.getExtension(imageFile.getOriginalFilename());
//构建保存文件路劲
//2016-5-6 yangkang 修改上传路径为服务器上
String realPath = request.getServletContext().getRealPath("uploadPath");
//获取服务器绝对路径 linux 服务器地址 获取当前使用的配置文件配置
//String urlString=PropertiesUtil.getInstance().getSysPro("uploadPath");
//拼接文件路劲
String filePathName = realPath + File.separator + pathName;
log.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 new BaseResult(false, "操作失败", e.getMessage());
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (IOException e) {
filePathName = null;
return new BaseResult(false, "操作失败", e.getMessage());
}
}
// String fileId = FastDFSClient.uploadFile(file, filePathName);
/**
* 缩略图begin
*/
//拼接后台文件名称
String thumbnailPathName = fileDirectory + File.separator + uuid + "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 >= 200*1024){
if(size > 0){
scale = (200*1024f) / 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){
Thumbnails.of(filePathName).scale(1f).outputFormat("jpg").toFile(thumbnailFilePathName);
}else{
Thumbnails.of(filePathName).scale(1f).outputQuality(scale).outputFormat("jpg").toFile(thumbnailFilePathName);
}
} catch (Exception e1) {
return new BaseResult(false, "操作失败", e1.getMessage());
}
/**
* 缩略图end
*/
Map<String, Object> map = new HashMap<String, Object>();
//原图地址
map.put("originalUrl", pathName);
//缩略图地址
map.put("thumbnailUrl", thumbnailPathName);
return new BaseResult(true, "操作成功", map);
}
获取当前使用的配置文件信息
/**
* 根据key从gzt.properties配置文件获取配置信息
* @param key 键值
* @return
*/
public String getSysPro(String key){
return getSysPro(key, null);
}
/**
* 根据key从gzt.properties配置文件获取配置信息
* @param key 键值
* @param defaultValue 默认值
* @return
*/
public String getSysPro(String key,String defaultValue){
return getValue("spring/imageserver-"+System.getProperty("spring.profiles.active")+".properties", key, defaultValue);
}
例:
//获取服务器绝对路径 linux 服务器地址
String urlString=PropertiesUtil.getInstance().getSysPro("uploadPath");
PropertiesUtil 类
package com.xyz.imageserver.common.properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
/**
*
* @ClassName PropertiesUtil.java
* @Description 系统配置工具类
* @author caijy
* @date 2015年6月9日 上午10:50:38
* @version 1.0.0
*/
public class PropertiesUtil {
private Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
private ConcurrentHashMap<String, Properties> proMap;
private PropertiesUtil() {
proMap = new ConcurrentHashMap<String, Properties>();
}
private static PropertiesUtil instance = new PropertiesUtil();
/**
* 获取单例对象
* @return
*/
public static PropertiesUtil getInstance()
{
return instance;
}
/**
* 根据key从gzt.properties配置文件获取配置信息
* @param key 键值
* @return
*/
public String getSysPro(String key){
return getSysPro(key, null);
}
/**
* 根据key从gzt.properties配置文件获取配置信息
* @param key 键值
* @param defaultValue 默认值
* @return
*/
public String getSysPro(String key,String defaultValue){
return getValue("spring/imageserver-"+System.getProperty("spring.profiles.active")+".properties", key, defaultValue);
}
/**
* 从配置文件中获取对应key值
* @param fileName 配置文件名
* @param key key值
* @param defaultValue 默认值
* @return
*/
public String getValue(String fileName,String key,String defaultValue){
String val = null;
Properties properties = proMap.get(fileName);
if(properties == null){
InputStream inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);
try {
properties = new Properties();
properties.load(new InputStreamReader(inputStream,"UTF-8"));
proMap.put(fileName, properties);
val = properties.getProperty(key,defaultValue);
} catch (IOException e) {
logger.error("getValue",e);
}finally{
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e1) {
logger.error(e1.toString());
}
}
}else{
val = properties.getProperty(key,defaultValue);
}
return val;
}
}
图片压缩上传Thumbnailator 插件的更多相关文章
- 三款不错的图片压缩上传插件(webuploader+localResizeIMG4+LUploader)
涉及到网页图片的交互,少不了图片的压缩上传,相关的插件有很多,相信大家都有用过,这里我就推荐三款,至于好处就仁者见仁喽: 1.名气最高的WebUploader,由Baidu FEX 团队开发,以H5为 ...
- 纯原生js移动端图片压缩上传插件
前段时间,同事又来咨询一个问题了,说手机端动不动拍照就好几M高清大图,上传服务器太慢,问问我有没有可以压缩图片并上传的js插件,当然手头上没有,别慌,我去网上搜一搜. 结果呢,呵呵...诶~又全是基于 ...
- Html5+asp.net mvc 图片压缩上传
在做图片上传时,大图片如果没有压缩直接上传时间会非常长,因为有的图片太大,传到服务器上再压缩太慢了,而且损耗流量. 思路是将图片抽样显示在canvas上,然后用通过canvas.toDataURL方法 ...
- springMVC多图片压缩上传的实现
首先需要在配置文件中添加配置: <!--配置文件的视图解析器,用于文件上传,其中ID是固定的:multipartResolver--> <bean id="multipar ...
- 基于vue + axios + lrz.js 微信端图片压缩上传
业务场景 微信端项目是基于Vux + Axios构建的,关于图片上传的业务场景有以下几点需求: 1.单张图片上传(如个人头像,实名认证等业务) 2.多张图片上传(如某类工单记录) 3.上传图片时期望能 ...
- 基于H5+ API手机相册图片压缩上传
// 母函数 function App(){} /** * 图片压缩,默认同比例压缩 * @param {Object} path * pc端传入的路径可以为相对路径,但是在移动端上必须传入的路径是照 ...
- 分享图片压缩上传demo,可以选择一张或多张图片也可以拍摄照片
2016-08-05更新: 下方的代码是比较OLD的了,是通过js进行图片的剪切 旋转 再生成,效率较低. 后来又整合了一个利用native.js本地接口的压缩代码 ,链接在这 .页面中有详细的说明, ...
- js 图片压缩上传(base64位)以及上传类型分类
一.input file上传类型 1.指明只需要图片 <input type="file" accept='image/*'> 2.指明需要多张图片 <input ...
- HTML多图片压缩上传
本文介绍的是多张图片在前端统一压缩后再通过ajax提交给后台处理的业务,使用到的是LocalResizeIMG.js插件. 一.首先介绍项目结构 二.分享引用核心文件,这里没有分享CSS文件,因为没有 ...
随机推荐
- bzoj 4546: codechef XRQRS [可持久化Trie]
4546: codechef XRQRS 可持久化Trie codechef上过了,bzoj上蜜汁re,看别人说要开5.2e5才行. #include <iostream> #includ ...
- BZOJ 3473: 字符串 [广义后缀自动机]
3473: 字符串 Time Limit: 20 Sec Memory Limit: 256 MBSubmit: 354 Solved: 160[Submit][Status][Discuss] ...
- 《深入理解Java虚拟机》——垃圾收集器与内存分配策略
GC需要完成: 哪些内存需要回收 什么时候回收 如何回收 如何确定对象不再使用 引用计数算法 给对象添加一个引用计数器,当有一个地方引用它时,计数器值进行加1操作:当引用失效时,计数器值进行减1操作: ...
- 10位时间戳转为C#格式时间
/// <summary> /// 10位时间戳转为C#格式时间 /// </summary> /// <param name=”timeStamp”></p ...
- 在linux内核中实现自己的系统调用
如实现一个简单的打印:printk 1.cd linux-ok6410/kernel/ vim printk.cvoid sys_pk(){printk("<0>this is ...
- PHP 批量获取指定目录下的文件列表(递归,穿透所有子目录)
//调用 $dir = '/Users/xxx/www'; $exceptFolders = array('view','test'); $exceptFiles = array('BaseContr ...
- go入门
1.hello world 小程序 package main import "fmt" func main() { fmt.println("hello,世界" ...
- 使用nodejs搭建api的mock服务
1. 介绍 公司的业务开发都是静态页面,开发前期总是避免不了获取api的问题.在vue中有一些mockjs的方案,方案都是注入性质的,和最终部署总是有差别,而且业务大部分还在zepto下,很难找到合适 ...
- PHP opcache扩展安装
下面是我在PHP 5.4下的安装方法: https://pecl.php.net/get/zendopcache-7.0.5.tgz tar xzf zendopcache-7.0.5.tgz cd ...
- cmd命令报4048错误
解决方法: win10系统:快捷键win+x,找到命令提示符(管理员),打开再下载相应的依赖包. win7/8:打开开始,输入命令提示符,找到管理员权限的命令提示符,打开再下载相应的依赖包. 提示:如 ...