java上传图片并压缩图片大小
Thumbnailator 是一个优秀的图片处理的Google开源Java类库。处理效果远比Java API的好。从API提供现有的图像文件和图像对象的类中简化了处理过程,两三行代码就能够从现有图片生成处理后的图片,且允许微调图片的生成方式,同时保持了需要写入的最低限度的代码量。还支持对一个目录的所有图片进行批量处理操作。
支持的处理操作:图片缩放,区域裁剪,水印,旋转,保持比例。
另外值得一提的是,Thumbnailator至今仍不断更新,怎么样,感觉很有保障吧!
Thumbnailator官网:http://code.google.com/p/thumbnailator/
下面我们介绍下如何使用Thumbnailator
使用介绍地址:
http://blog.csdn.net/chenleixing/article/details/44685817
http://www.qzblog.net/blog/220
http://blog.csdn.net/wangpeng047/article/details/17610451
缩略图压缩文件jar包
<!-- 图片缩略图 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
按指定大小把图片进行缩放(会遵循原图高宽比例)
//按指定大小把图片进行缩和放(会遵循原图高宽比例)
//此处把图片压成400×500的缩略图
Thumbnails.of(fromPic).size(400,500).toFile(toPic);//变为400*300,遵循原图比例缩或放到400*某个高度
按照指定比例进行缩小和放大
//按照比例进行缩小和放大
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;
}
}
批量压缩图片:
package com.xhj.util;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap; import net.coobird.thumbnailator.Thumbnails;
public class ImgChange { /**
* 读取某个目录下所有文件、文件夹
* @param path
* @return LinkedHashMap<String,String>
*/
public static LinkedHashMap<String,String> getFiles(String path) {
LinkedHashMap<String,String> files = new LinkedHashMap<String,String>();
File file = new File(path);
File[] tempList = file.listFiles(); for (int i = 0; i < tempList.length; i++) {
if (!tempList[i].isDirectory()) {
files.put(tempList[i].getName(),tempList[i].getPath());
}
}
return files;
} public static void main(String[] args) {
try {
LinkedHashMap<String,String> files = getFiles("D:/img");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date beginDate = new Date();
System.out.println("开始:"+sdf.format(beginDate));
int i = 0;
for (String fileName : files.keySet()) {
i = i+1;
System.out.println("第"+i+"张:"+sdf.format(new Date()));
//图片尺寸不变,压缩图片文件大小outputQuality实现,参数1为最高质量
double scale = 1.0;
Thumbnails.of("D:/img/"+fileName).scale(scale).toFile("D:/imgCopy/"+fileName);
File file = new File("D:/imgCopy/"+fileName);
if (file.exists()) {
while (file.length()>=500000) {
scale = scale*0.9;
file.delete();
Thumbnails.of("D:/img/"+fileName).scale(scale).toFile("D:/imgCopy/"+fileName);
}
}
}
Date endDate = new Date();
System.out.println("结束:"+sdf.format(endDate));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
java上传图片并压缩图片大小的更多相关文章
- java 上传图片 并压缩图片大小
Thumbnailator 是一个优秀的图片处理的Google开源Java类库.处理效果远比Java API的好.从API提供现有的图像文件和图像对象的类中简化了处理过程,两三行代码就能够从现有图片生 ...
- java 上传图片 并压缩图片大小(转)
Thumbnailator 是一个优秀的图片处理的Google开源Java类库.处理效果远比Java API的好.从API提供现有的图像文件和图像对象的类中简化了处理过程,两三行代码就能够从现有图片生 ...
- java实现上传图片并压缩图片大小功能
缩略图压缩文件jar包 <!-- 图片缩略图 --> <dependency> <groupId>net.coobird</groupId> <a ...
- java上传图片时压缩图片
/** * 函数:调整图片尺寸或生成缩略图 v 1.1 * @param $Image 需要调整的图片(含路径) * @param $Dw 调整时最大宽度;缩略图时的绝对宽度 * @param $Dh ...
- 压缩图片大小(Java源码)
/** * * 直接指定压缩后的宽高: * @param oldFile * 要进行压缩的文件 * @param width * 压缩后的宽度 * @param height * 压缩后的高度 * @ ...
- 【问题帖】压缩图片大小至指定Kb以下
像PS,QQ影像等都有该功能,将图片大小压缩至指定kb以下. 我也来山寨一把,到目前为止,控制图片的大小,平时的解决方案通过分辨率和质量来控制的. 假定最后压缩的大小是100kb,那么在保证不大于10 ...
- Java使用 Thumbnails 压缩图片
业务:用户上传一张图片到文件站,需要返回原图url和缩略图url 处理思路: 因为上传图片方法返回url是单个上传,第一步先上传原图并返回url 处理缩略图并上传:拿到MultipartFile压缩成 ...
- 上传图片时压缩图片 - 前端(canvas)做法
HTML前端代码: <?php $this->layout('head'); ?> <?php $this->layout('sidebar'); ?> <m ...
- vue + vant 上传图片之压缩图片
<van-uploader v-model="fileList" multiple :after-read="afterRead" :max-count= ...
随机推荐
- DLL Injection with Delphi(转载)
原始链接 I had recently spent some time playing around with the simple to use DelphiDetours package from ...
- Executors、ThreadPoolExecutor线程池讲解
官方+白话讲解Executors.ThreadPoolExecutor线程池使用 Executors:JDK给提供的线程工具类,静态方法构建线程池服务ExecutorService,也就是Thread ...
- Python之数据分析
什么是数据分析? 运用不同行业中,专门从事行业数据搜集.整理.分析,并依据数据做出行业研究.评估和预测的专业人员. 熟悉行业知识.公司业务及流程,最好有自己独到的见解,若脱离行业认知和公司业务背景,分 ...
- 《linux就该这么学》课堂笔记07 while、case、计划任务、用户增删改查命令
while条件循环语句 while 条件测试操作 do 命令序列 done case条件测试语句 case 变量值 in 模式一) 命令序列1 ;; 模式二) 命令序列2 ;; *) 默认命令序列 ...
- python的包管理软件Conda的用法
创建自己的虚拟环境 conda create -n learn python= 切换环境: activate learn 查看所有环境: conda env list 安装第三方包: conda in ...
- C# 只允许运行一个程序实例
using System; using System.Windows.Forms; using System.Runtime.InteropServices;//使用DllImport的必须. usi ...
- MVC开发中自定义返回类型
在做项目web的MVC中,会用到返回值的问题,我们一般使用AjaxResult的返回值,根据自己的需要进行自定义,如下参考: using System; using System.Collection ...
- 点击一个超链接,弹出固定大小的新窗口(js实现)
1.最基本的弹出窗口代码 <SCRIPT LANGUAGE="javascript"> <!-- window.open ('page.html') --> ...
- Error handling in Swift does not involve stack unwinding. What does it mean?
Stack unwinding is just the process of navigating up the stack looking for the handler. Wikipedia su ...
- continue语句:编程把100-300之间的能被25整除的数输出
#include<stdio.h>void main(){ int n; for(n=100;n<=300;n++) { if(n%25!=0) continue; printf(& ...