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.of(filePathName).scale(scale).outputQuality(quality).outputFormat("jpg").toFile(thumbnailFilePathName); Thumbnails.of(filePathName).scale(scale).outputFormat("jpg").toFile(thumbnailFilePathName); Thumbnails.of(filePathName).size(400,500).toFile(thumbnailFilePathName);//變為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 @RequestMapping(path = "/thumb", produces = "application/json;charset=UTF-8") public class TestThumbnails { /** * @Description:保存圖片並且生成縮略圖 * @param imageFile 圖片文件 * @param request 請求對象 * @param uploadPath 上傳目錄 * @return */ private static Logger log = LoggerFactory.getLogger(TestThumbnails.class); @RequestMapping("/up") public String testThumb(MultipartFile imageFile, HttpServletRequest request) { String res = this.uploadFileAndCreateThumbnail(imageFile, request, ""); return res; } public static String uploadFileAndCreateThumbnail(MultipartFile 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").format(new Date());//設置日期格式 //拼接后台文件名稱 String pathName = fileDirectory + File.separator + uuid + "." + FilenameUtils.getExtension(imageFile.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 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); //寫出文件 // IOUtils.copy(inputStream, fileOutputStream); byte[] buffer = new byte[2048]; IOUtils.copyLarge(inputStream, 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.getExtension(imageFile.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.read(imageFile.getInputStream()); //獲取圖片流 if (bufferedImage == null) { // 證明上傳的文件不是圖片,獲取圖片流失敗,不進行下面的操作 } width = bufferedImage.getWidth(); // 通過圖片流獲取圖片寬度 height = bufferedImage.getHeight(); // 通過圖片流獲取圖片高度 // 省略邏輯判斷 } catch (Exception e) { // 省略異常操作 } System.out.println(width); while (width * scale > maxWidth) {//處理圖片像素寬度(當像素大於1200時進行圖片等比縮放寬度) scale -= 0.1; } //拼接文件路徑 String thumbnailFilePathName = realPath + File.separator + thumbnailPathName; System.out.println(scale); System.out.println(quality); System.out.println((int) width * scale); /*if(true){ return result.toJSONString(); }*/ try { //注釋掉之前長寬的方式,改用大小 // Thumbnails.of(filePathName).size(width, height).toFile(thumbnailFilePathName); if (size < 200 * 1024) { Thumbnails.of(filePathName).scale(scale).outputFormat("jpg").toFile(thumbnailFilePathName); } else { Thumbnails.of(filePathName).scale(scale).outputQuality(quality).outputFormat("jpg").toFile(thumbnailFilePathName);//(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(); } }