thumbnailator压缩图片并存至Excel单元格代码
生活随笔
收集整理的這篇文章主要介紹了
thumbnailator压缩图片并存至Excel单元格代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 依賴
- 壓縮圖片工具類:
- 存至excel的轉化器
- Excel導入導出的數據類
- 將數據庫實體轉化為excel實體
依賴
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.6</version></dependency><dependency><groupId>net.coobird</groupId><artifactId>thumbnailator</artifactId><version>0.4.8</version></dependency>壓縮圖片工具類:
@description: 調用Thumbnails壓縮圖片
public class ImgUtil {private static Logger logger = LoggerFactory.getLogger(ImgUtil.class);/*** 根據指定大小壓縮圖片** @param imageBytes 源圖片字節數組* @param desFileSize 指定圖片大小,單位kb* @param imageId 影像編號* @return 壓縮質量后的圖片字節數組*/public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize, String imageId) {if (imageBytes == null || imageBytes.length <= 0 || imageBytes.length < desFileSize * 1024) {return imageBytes;}long srcSize = imageBytes.length;//double accuracy = getAccuracy(srcSize / 1024);double accuracy=0.4;try {while (imageBytes.length > desFileSize * 1024) {ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);//Thumbnails用來壓縮圖片的工具Thumbnails.of(inputStream).scale(accuracy).outputQuality(accuracy).toOutputStream(outputStream);imageBytes = outputStream.toByteArray();}logger.info("【圖片壓縮】imageId={} | 圖片原大小={}kb | 壓縮后大小={}kb",imageId, srcSize / 1024, imageBytes.length / 1024);} catch (Exception e) {logger.error("【圖片壓縮】msg=圖片壓縮失敗!", e);}return imageBytes;}/*** 自動調節精度(經驗數值)** @param size 源圖片大小* @return 圖片壓縮質量比*/private static double getAccuracy(long size) {double accuracy;if (size < 900) {accuracy = 0.5;} else if (size < 2047) {accuracy = 0.6;} else if (size < 3275) {accuracy = 0.44;} else {accuracy = 0.4;}return accuracy;}}存至excel的轉化器
/*** @author Hai* @program: subtlechat* @description: 將URL圖片的格式轉化器* @create 2020/10/8 - 12:45**/ public class MyUrlImageConverter implements Converter<URL> {@Overridepublic Class supportJavaTypeKey() {return URL.class;}@Overridepublic CellDataTypeEnum supportExcelTypeKey() {return CellDataTypeEnum.IMAGE;}@Overridepublic URL convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,GlobalConfiguration globalConfiguration) {throw new UnsupportedOperationException("Cannot convert images to url.");}@Overridepublic CellData convertToExcelData(URL value, ExcelContentProperty contentProperty,GlobalConfiguration globalConfiguration) throws IOException {InputStream inputStream = null;try {//開啟連接URLConnection uc = value.openConnection();//openConnection:返回一個URLConnection實例,該實例表示到URL引用的遠程對象的連接。URL url = null;//獲取響應狀態int statusCode = ((HttpURLConnection) uc).getResponseCode();switch (statusCode){case 200:inputStream = value.openStream();break;case 404://默認給一個圖片url = new URL("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1598096095144&di=9a72ad26e83effb9341c711c9818b85f&imgtype=0&src=http%3A%2F%2Fpic.616pic.com%2Fys_bnew_img%2F00%2F11%2F69%2Fj2AjnHspwT.jpg");inputStream = url.openStream();break;default :url = new URL("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1598096095144&di=9a72ad26e83effb9341c711c9818b85f&imgtype=0&src=http%3A%2F%2Fpic.616pic.com%2Fys_bnew_img%2F00%2F11%2F69%2Fj2AjnHspwT.jpg");inputStream = url.openStream();break;}byte[] bytes = IoUtils.toByteArray(inputStream);byte[] compressBytes = ImgUtil.compressPicForScale(bytes,200, UUID.randomUUID().toString());return new CellData(compressBytes);}catch (ConnectException exception){//捕獲下鏈接異常URL url = new URL("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1598096095144&di=9a72ad26e83effb9341c711c9818b85f&imgtype=0&src=http%3A%2F%2Fpic.616pic.com%2Fys_bnew_img%2F00%2F11%2F69%2Fj2AjnHspwT.jpg");inputStream = url.openStream();byte[] bytes = IoUtils.toByteArray(inputStream);return new CellData(bytes);}catch (FileNotFoundException fileNotFoundException){URL url = new URL("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1598096095144&di=9a72ad26e83effb9341c711c9818b85f&imgtype=0&src=http%3A%2F%2Fpic.616pic.com%2Fys_bnew_img%2F00%2F11%2F69%2Fj2AjnHspwT.jpg");inputStream = url.openStream();byte[] bytes = IoUtils.toByteArray(inputStream);return new CellData(bytes);}finally {if (inputStream != null) {inputStream.close();}}} }Excel導入導出的數據類
@Data @ColumnWidth(25) @ContentRowHeight(30) public class GroupMsgContentData {@ExcelProperty("消息內容編號")private Integer id;@ExcelProperty("發送者的編號")private Integer fromId;@ExcelProperty("昵稱")private String fromName;//@ExcelProperty(value = "頭像",converter = UrlImageConverter.class)@ExcelIgnoreprivate URL fromProfile;@ExcelProperty("發送時間")@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")private Date createTime;@ExcelProperty(value = {"內容","文本"})@ColumnWidth(50)private String textContent;@ExcelProperty(value = {"內容","圖片"},converter = MyUrlImageConverter.class)@ColumnWidth(50)private URL imageContent;@ExcelIgnoreprivate Integer messageTypeId;@Overridepublic String toString() {return "GroupMsgContentData{" +"id=" + id +", fromId=" + fromId +", fromName='" + fromName + '\'' +", fromProfile=" + fromProfile +", createTime=" + createTime +", textContent='" + textContent + '\'' +", imageContent=" + imageContent +", messageTypeId=" + messageTypeId +'}';}注意保存圖片的這一數據是:
@ExcelProperty(value = {“內容”,“圖片”},converter = MyUrlImageConverter.class)
@ColumnWidth(50)
private URL imageContent;
將數據庫實體轉化為excel實體
public static GroupMsgContentData convertEntityToData(GroupMsgContent groupMsgContent) throws MalformedURLException {GroupMsgContentData groupMsgContentData = new GroupMsgContentData();groupMsgContentData.setFromId(groupMsgContent.getFromId());groupMsgContentData.setId(groupMsgContent.getId());groupMsgContentData.setFromName(groupMsgContent.getFromName());groupMsgContentData.setCreateTime(groupMsgContent.getCreateTime());//轉化為URL以Excel導出圖片groupMsgContentData.setFromProfile(new URL(groupMsgContent.getFromProfile()));//根據消息類型設置內容if (groupMsgContent.getMessageTypeId()==1){groupMsgContentData.setTextContent(groupMsgContent.getContent());}if (groupMsgContent.getMessageTypeId()==2){groupMsgContentData.setImageContent(new URL(groupMsgContent.getContent()));}return groupMsgContentData;}總結
以上是生活随笔為你收集整理的thumbnailator压缩图片并存至Excel单元格代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 整合rabbitmq+redis发送验证
- 下一篇: 解决LoggerFactory is n