使用Thumbnails實現(xiàn)圖片指定大小壓縮
更新時間:2019年08月29日 08:37:20 作者:DcForever
這篇文章主要為大家詳細介紹了使用Thumbnails實現(xiàn)圖片指定大小壓縮,具有一定的參考價值,感興趣的小伙伴們可以參考一下
項目中有個要求,對上傳服務器的圖片大小進行判斷,大于500k的圖片要進行壓縮處理,讓其小于500k后在上傳。
可以通過java api的ImageIO實現(xiàn)圖片壓縮,但是看了網上的博客普遍都說bug比較多,會有OOM內存溢出的現(xiàn)象。
Thumbnails插件是Google的插件,能指定不同的參數進行壓縮操作。
比如:寬高(size),縮放(scale),制定質量比(outputQuality)等。
插件使用的jar包為:
thumbnailator-0.4.8.jar
代碼如下:
/** * * @param srcPath 原圖片地址 * @param desPath 目標圖片地址 * @param desFileSize 指定圖片大小,單位kb * @param accuracy 精度,遞歸壓縮的比率,建議小于0.9 * @return */ public static String commpressPicForScale(String srcPath,String desPath, long desFileSize , double accuracy){ try { File srcFile = new File(srcPath); long srcFilesize = srcFile.length(); System.out.println("原圖片:"+srcPath + ",大小:" + srcFilesize/1024 + "kb"); //遞歸壓縮,直到目標文件大小小于desFileSize commpressPicCycle(desPath, desFileSize, accuracy); File desFile = new File(desPath); System.out.println("目標圖片:" + desPath + ",大小" + desFile.length()/1024 + "kb"); System.out.println("圖片壓縮完成!"); } catch (Exception e) { e.printStackTrace(); } return desPath; } public static void commpressPicCycle(String desPath , long desFileSize, double accuracy) throws IOException{ File imgFile = new File(desPath); long fileSize = imgFile.length(); //判斷大小,如果小于500k,不壓縮,如果大于等于500k,壓縮 if(fileSize <= desFileSize * 500){ return; } //計算寬高 BufferedImage bim = ImageIO.read(imgFile); int imgWidth = bim.getWidth(); int imgHeight = bim.getHeight(); int desWidth = new BigDecimal(imgWidth).multiply( new BigDecimal(accuracy)).intValue(); int desHeight = new BigDecimal(imgHeight).multiply( new BigDecimal(accuracy)).intValue(); Thumbnails.of(desPath).size(desWidth, desHeight).outputQuality(accuracy).toFile(desPath); //如果不滿足要求,遞歸直至滿足小于1M的要求 commpressPicCycle(desPath, desFileSize, accuracy); }
然后壓縮圖片大?。?/p>
commpressPicForScale(filePath, filePath, 500, 0.8);
壓縮完成:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Android用注解與反射實現(xiàn)Butterknife功能
Butterknife是一個在android上實現(xiàn)ioc(控制反轉)的一個庫。ioc的核心是解耦。解耦的目的是修改耦合對象時不影響另外一個對象,降低模塊之間的關聯(lián)。在Spring中ioc更多的是依靠xml的配置。而android上的IOC框架可以不使用xml配置2022-11-11