Thumbnailator 是一個優秀的圖檔處理的Google開源Java類庫。處理效果遠比Java API的好。從API提供現有的圖像檔案和圖像對象的類中簡化了處理過程,兩三行代碼就能夠從現有圖檔生成處理後的圖檔,且允許微調圖檔的生成方式,同時保持了需要寫入的最低限度的代碼量。還支援對一個目錄的所有圖檔進行批量處理操作。
jar包下載下傳:https://pan.baidu.com/s/1P29mvsCqeL_R05DBM0EkkQ 提取碼:hfgi
1.按照比例進行縮放:
//原始圖檔的路徑 String imgPath = "F:/file/1.png"; //壓縮後圖檔的路徑 String smallImgPath = imgPath.replace(".", "_small."); try { Thumbnails.of(imgPath) //scale是比例,值在0到1之間,1f就是原圖大小 //0.5f就是原圖的一半大小,這裡的大小是指圖檔的長寬。 .scale(0.5f) //outputQuality是圖檔的品質,值也是在0到1,越接近于1品質越好,越接近于0品質越差。 .outputQuality(0.1) //.toFile圖檔處理後路徑 .toFile(smallImgPath); } catch (IOException e) { e.printStackTrace(); }
2.指定大小進行縮放:
//原始圖檔的路徑 String imgPath = "F:/file/1.png"; //壓縮後圖檔的路徑 String smallImgPath = imgPath.replace(".", "_small."); try { Thumbnails.of(imgPath) //.size是寬度、高度 .size(200, 300) .toFile(smallImgPath); } catch (IOException e) { e.printStackTrace(); }
3.不按照比例,指定大小進行縮放:
//原始圖檔路徑 String imgPath = "F:/file/1.png"; //壓縮圖檔路徑 String smallImgPath = imgPath.replace(".", "_small."); try { //keepAspectRatio(false)預設是按照比例縮放的 Thumbnails.of(imgPath) .size(200,200) .keepAspectRatio(false) .toFile(smallImgPath); } catch (IOException e) { e.printStackTrace(); }
4.旋轉:
//原始圖檔路徑 String imgPath = "F:/file/1.png"; //壓縮圖檔路徑 String smallImgPath = imgPath.replace(".", "_small."); try { //rotate(角度),正數:順時針,負數:逆時針 Thumbnails.of(imgPath) .size(1280,1024) .rotate(90) .toFile(smallImgPath); } catch (IOException e) { e.printStackTrace(); }
5.水印:
//原始圖檔路徑 String imgPath = "F:/file/1.png"; //壓縮圖檔路徑 String smallImgPath = imgPath.replace(".", "_small."); //水印圖位置 File file= new File("e:/demo/demoNext" + File.separator + "yin.png") ; try { //watermark(位置,水印圖,透明度) Thumbnails.of(imgPath) .size(1280,1024) .watermark(Positions.BOTTOM_RIGHT,ImageIO.read(file),0.5f) .outputQuality(0.5f) .toFile(smallImgPath); } catch (IOException e) { e.printStackTrace(); }
6.剪裁:
//原始圖檔路徑 String imgPath = "F:/file/1.png"; //壓縮圖檔路徑 String smallImgPath = imgPath.replace(".", "_small."); try { //sourceRegion()指定位置 //圖檔中心400*400的區域 Thumbnails.of(imgPath) .sourceRegion(Positions.CENTER,400,400) .size(200,200) .keepAspectRatio(false) .toFile(smallImgPath); //圖檔右下400*400的區域 Thumbnails.of(imgPath) .sourceRegion(Positions.BOTTOM_RIGHT,400,400) .size(200,200) .keepAspectRatio(false) .toFile(smallImgPath); //指定坐标 Thumbnails.of(imgPath) .sourceRegion(600,500,400,400) .size(200,200) .keepAspectRatio(false) .toFile(smallImgPath); } catch (IOException e) { e.printStackTrace(); }
7.轉換圖像格式:
//原始圖檔路徑 String imgPath = "F:/file/1.png"; //壓縮圖檔路徑 String smallImgPath = imgPath.replace(".", "_small."); File file= new File("e:/demo/demoNext" + File.separator + "yin.png") ; try { Thumbnails.of(imgPath) .size(1280,1024) //outputFormat(圖像格式) .outputFormat("gif") .toFile(smallImgPath); } catch (IOException e) { e.printStackTrace(); }