Thumbnails是Google公司开源的图片处理工具
一、将Thumbnails引入到maven工程
<dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.8</version> </dependency>
二、关键代码
String filePathName = "需要压缩的图片根路径"; String thumbnailFilePathName = "压缩之后的图片路径"; double scale = 1d;//图片缩小倍数0~1),1代表保持原有的大小 double quality = 1d;//压缩的质量,1代表保持原有的大小默认1) Thumbnails.offilePathName).scalescale).outputQualityquality).outputFormat"jpg").toFilethumbnailFilePathName); Thumbnails.offilePathName).scalescale).outputFormat"jpg").toFilethumbnailFilePathName); Thumbnails.offilePathName).size400,500).toFilethumbnailFilePathName);//变为400*500,遵循原图比例缩或放到400*某个高度
三、Spring-boot的例子
package com.example.atlogging.controller; import com.alibaba.fastjson.JSONObject; import net.coobird.thumbnailator.Thumbnails; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; @RestController @RequestMappingpath = "/thumb", produces = "application/json;charset=UTF-8") public class TestThumbnails { /** * @Description:保存图片并且生成缩略图 * @param imageFile 图片文件 * @param request 请求对象 * @param uploadPath 上传目录 * @return */ private static Logger log = LoggerFactory.getLoggerTestThumbnails.class); @RequestMapping"/up") public String testThumbMultipartFile imageFile, HttpServletRequest request) { String res = this.uploadFileAndCreateThumbnailimageFile, request, ""); return res; } public static String uploadFileAndCreateThumbnailMultipartFile imageFile, HttpServletRequest request, String uploadPath) { JSONObject result = new JSONObject); int maxWidth = 1200;//压缩之后的图片最大宽度 if imageFile == null) { result.put"msg", "imageFile不能为空"); return result.toJSONString); } if imageFile.getSize) >= 10 * 1024 * 1024) { result.put"msg", "文件不能大于10M"); return result.toJSONString); } String uuid = UUID.randomUUID).toString); String fileDirectory = new SimpleDateFormat"yyyyMMdd").formatnew Date));//设置日期格式 //拼接后台文件名称 String pathName = fileDirectory + File.separator + uuid + "." + FilenameUtils.getExtensionimageFile.getOriginalFilename)); //构建保存文件路径 //修改上传路径为服务器上 String realPath = "F:/桌面temp/ys";//request.getServletContext).getRealPath"uploadPath"); //获取服务器绝对路径 linux 服务器地址 获取当前使用的配置文件配置 //String urlString=PropertiesUtil.getInstance).getSysPro"uploadPath"); //拼接文件路径 String filePathName = realPath + File.separator + pathName; log.info"图片上传路径:" + filePathName); //判断文件保存是否存在 File file = new FilefilePathName); if file.getParentFile) != null || !file.getParentFile).isDirectory)) { //创建文件 file.getParentFile).mkdirs); } InputStream inputStream = null; FileOutputStream fileOutputStream = null; try { inputStream = imageFile.getInputStream); fileOutputStream = new FileOutputStreamfile); //写出文件 // IOUtils.copyinputStream, fileOutputStream); byte[] buffer = new byte[2048]; IOUtils.copyLargeinputStream, fileOutputStream, buffer); buffer = null; } catch IOException e) { filePathName = null; result.put"msg", "操作失败"); return result.toJSONString); } finally { try { if inputStream != null) { inputStream.close); } if fileOutputStream != null) { fileOutputStream.flush); fileOutputStream.close); } } catch IOException e) { filePathName = null; result.put"msg", "操作失败"); return result.toJSONString); } } //拼接后台文件名称 String thumbnailPathName = fileDirectory + File.separator + uuid + "small." + FilenameUtils.getExtensionimageFile.getOriginalFilename)); if thumbnailPathName.contains".png")) { thumbnailPathName = thumbnailPathName.replace".png", ".jpg"); } long size = imageFile.getSize); double scale = 1d; double quality = 1d; if size >= 200 * 1024) {//当图片超过200kb的时候进行压缩处理 if size > 0) { quality = 200 * 1024f) / size; } } //图片信息 double width = 0; double height = 0; try { BufferedImage bufferedImage = ImageIO.readimageFile.getInputStream)); //获取图片流 if bufferedImage == null) { // 证明上传的文件不是图片,获取图片流失败,不进行下面的操作 } width = bufferedImage.getWidth); // 通过图片流获取图片宽度 height = bufferedImage.getHeight); // 通过图片流获取图片高度 // 省略逻辑判断 } catch Exception e) { // 省略异常操作 } System.out.printlnwidth); while width * scale > maxWidth) {//处理图片像素宽度(当像素大于1200时进行图片等比缩放宽度) scale -= 0.1; } //拼接文件路径 String thumbnailFilePathName = realPath + File.separator + thumbnailPathName; System.out.printlnscale); System.out.printlnquality); System.out.printlnint) width * scale); /*iftrue){ return result.toJSONString); }*/ try { //注释掉之前长宽的方式,改用大小 // Thumbnails.offilePathName).sizewidth, height).toFilethumbnailFilePathName); if size < 200 * 1024) { Thumbnails.offilePathName).scalescale).outputFormat"jpg").toFilethumbnailFilePathName); } else { Thumbnails.offilePathName).scalescale).outputQualityquality).outputFormat"jpg").toFilethumbnailFilePathName);//thumbnailFilePathName + "l."); } } catch Exception e1) { result.put"msg", "操作失败"); return result.toJSONString); } /** * 缩略图end */ //原图地址 result.put"originalUrl", pathName); //缩略图地址 result.put"thumbnailUrl", thumbnailPathName); //缩略图地址 result.put"msg", "操作成功"); result.put"status", 200); return result.toJSONString); } }