1.缩略图压缩文件jar包
<!-- 图片缩略图 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
2.thumbnailator的一些功能
1、指定大小进行缩放
[java] view plain copy
//size(宽度, 高度)
/*
* 若图片横比200小,高比300小,不变
* 若图片横比200小,高比300大,高缩小到300,图片比例不变
* 若图片横比200大,高比300小,横缩小到200,图片比例不变
* 若图片横比200大,高比300大,图片按比例缩小,横为200或高为300
*/
Thumbnails.of("images/a380_1280x1024.jpg")
.size(200, 300)
.toFile("c:/a380_200x300.jpg");
Thumbnails.of("images/a380_1280x1024.jpg")
.size(2560, 2048)
.toFile("c:/a380_2560x2048.jpg");
2、按照比例进行缩放
[java] view plain copy
//scale(比例)
Thumbnails.of("images/a380_1280x1024.jpg")
.scale(0.25f)
.toFile("c:/a380_25%.jpg");
Thumbnails.of("images/a380_1280x1024.jpg")
.scale(1.10f)
.toFile("c:/a380_110%.jpg");
3、不按照比例,指定大小进行缩放
[java] view plain copy
//keepAspectRatio(false)默认是按照比例缩放的
Thumbnails.of("images/a380_1280x1024.jpg")
.size(200,200)
.keepAspectRatio(false)
.toFile("c:/a380_200x200.jpg");
4、旋转
[java] view plain copy
//rotate(角度),正数:顺时针负数:逆时针
Thumbnails.of("images/a380_1280x1024.jpg")
.size(1280,1024)
.rotate(90)
.toFile("c:/a380_rotate+90.jpg");
Thumbnails.of("images/a380_1280x1024.jpg")
.size(1280,1024)
.rotate(-90)
.toFile("c:/a380_rotate-90.jpg");
5、水印
[java] view plain copy
//watermark(位置,水印图,透明度)
Thumbnails.of("images/a380_1280x1024.jpg")
.size(1280,1024)
.watermark(Positions.BOTTOM_RIGHT,ImageIO.read(newFile("images/watermark.png")),0.5f)
.outputQuality(0.8f)
.toFile("c:/a380_watermark_bottom_right.jpg");
Thumbnails.of("images/a380_1280x1024.jpg")
.size(1280,1024)
.watermark(Positions.CENTER,ImageIO.read(newFile("images/watermark.png")),0.5f)
.outputQuality(0.8f)
.toFile("c:/a380_watermark_center.jpg");
6、裁剪
[java] view plain copy
//sourceRegion()
//图片中心400*400的区域
Thumbnails.of("images/a380_1280x1024.jpg")
.sourceRegion(Positions.CENTER,400,400)
.size(200,200)
.keepAspectRatio(false)
.toFile("c:/a380_region_center.jpg");
//图片右下400*400的区域
Thumbnails.of("images/a380_1280x1024.jpg")
.sourceRegion(Positions.BOTTOM_RIGHT,400,400)
.size(200,200)
.keepAspectRatio(false)
.toFile("c:/a380_region_bootom_right.jpg");
//指定坐标
Thumbnails.of("images/a380_1280x1024.jpg")
.sourceRegion(600,500,400,400)
.size(200,200)
.keepAspectRatio(false)
.toFile("c:/a380_region_coord.jpg");
7、转化图像格式
[java] view plain copy
//outputFormat(图像格式)
Thumbnails.of("images/a380_1280x1024.jpg")
.size(1280,1024)
.outputFormat("png")
.toFile("c:/a380_1280x1024.png");
Thumbnails.of("images/a380_1280x1024.jpg")
.size(1280,1024)
.outputFormat("gif")
.toFile("c:/a380_1280x1024.gif");
8、输出到OutputStream
[java] view plain copy
//toOutputStream(流对象)
OutputStreamos=newFileOutputStream("c:/a380_1280x1024_OutputStream.png");
Thumbnails.of("images/a380_1280x1024.jpg")
.size(1280,1024)
.toOutputStream(os);
9、输出到BufferedImage
[java] view plain copy
//asBufferedImage()返回BufferedImage
BufferedImagethumbnail=Thumbnails.of("images/a380_1280x1024.jpg")
.size(1280,1024)
.asBufferedImage();
ImageIO.write(thumbnail,"jpg",newFile("c:/a380_1280x1024_BufferedImage.jpg"));
3.java代码实现
private static Logger log = LoggerFactory.getLogger(ActivitySpringArticleController.class);
@ApiOperation(value="图片上传接口")
@RequestMapping(value = "activity/uploadActivitySpringFile")
@ResponseBody
public String uploadActivitySpringFile(HttpServletRequest request) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile imageFile = multipartRequest.getFile("upfile");
if(imageFile == null ){
throw new BusinessException(new ErrorCode("imageFile不能为空"));
}
if (imageFile.getSize() >= 10*1024*1024)
{
throw new BusinessException(new ErrorCode("文件不能大于10M"));
}
String uuid = UUID.randomUUID().toString();
String fileDirectory = DateUtil.date2String(new Date(), DateUtil.SIMPLE_DATE_FORMAT);
//拼接后台文件名称
String pathName = fileDirectory + File.separator + uuid + "."
+ FilenameUtils.getExtension(imageFile.getOriginalFilename());
//构建保存文件路劲
//2016-5-6 yangkang 修改上传路径为服务器上
// String realPath = request.getServletContext().getRealPath("uploadPath");
String realPath = "D://test//";
//获取服务器绝对路径 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;
throw new BusinessException(new ErrorCode("操作失败"));
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (IOException e) {
filePathName = null;
throw new BusinessException(new ErrorCode("操作失败"));
}
}
// 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(11, 12).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) {
throw new BusinessException(new ErrorCode("操作失败"));
}
/**
* 缩略图end
*/
Map<String, Object> map = new HashMap<String, Object>();
//原图地址
map.put("originalUrl", pathName);
//缩略图地址
map.put("thumbnailUrl", thumbnailPathName);
return pathName+"---------"+thumbnailPathName;
//throw new BusinessException(new ErrorCode("操作成功"));
}
4.配置文件,为上传至linux使用
获取当前使用的配置文件信息
/**
* 根据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");
5.工具类
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;
}
}
6. 测试
<!DOCTYPE html>
<html lang="en">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Get your greeting <a href="/greeting">here</a></p>
<form action="activity/downloadActivitySpringFile" method="POST" enctype="multipart/form-data">
文件:<input type="file" name="upfile"/>
<input type="submit" />
</form>
<a href="activity/downloadActivitySpringFile">下载test</a>
<p>多文件上传</p>
<form method="POST" enctype="multipart/form-data" action="/batch/upload">
<p>文件1:<input type="file" name="file" /></p>
<p>文件2:<input type="file" name="file" /></p>
<p><input type="submit" value="上传" /></p>
</form>
</body>
</html>