Thumbnailator圖片處理(圖片縮放,區域裁剪,水印,旋轉,保持比例)
阿新 • • 發佈:2018-12-15
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();
}