標籤:
情境一:圖片尺寸不變,修改圖片檔案類型
使用:
Thumbnails.of("F:\\image\\IMG_20131229_114806.png") .scale(1f)
.outputFormat("jpg")
.toFile("F:\\image\\output\\IMG_20131229_114806");
注意:outputFormat:輸出的圖片格式。注意使用該方法後toFile()方法不要再含有檔案類型的尾碼了,否則會產生 IMG_20131229_114806.jpg.jpg 的圖片。
情境二:圖片尺寸不變,壓縮圖片檔案大小
使用:
Thumbnails.of("F:\\image\\IMG_20131229_114806.png") .scale(1f)
.outputQuality(0.25f)
.outputFormat("jpg")
.toFile("F:\\image\\output\\IMG_20131229_114806");
注意:outputQuality:輸出的圖片品質,範圍:0.0~1.0,1為最高品質。注意使用該方法時輸出的圖片格式必須為jpg(即outputFormat("jpg")。其他格式我沒試過,感興趣的自己可以試試)。否則若是輸出png格式圖片,則該方法作用無效【這其實應該算是bug】。
情境三:壓縮至指定圖片尺寸(例如:橫400高300),不保持圖片比例
使用:
Thumbnails.of("F:\\image\\IMG_20131229_114806.png")
.forceSize(400, 300)
.toFile("F:\\image\\output\\IMG_20131229_114806");
情境四:壓縮至指定圖片尺寸(例如:橫400高300),保持圖片不變形,多餘部分裁剪掉
使用:
String imagePath = "F:\\image\\IMG_20131229_114806.jpg";
BufferedImage image = ImageIO.read(new File(imagePath));
Builder<BufferedImage> builder = null;
int imageWidth = image.getWidth();
int imageHeitht = image.getHeight();
if ((float)300 / 400 != (float)imageWidth / imageHeitht) {
if (imageWidth > imageHeitht) {
image = Thumbnails.of(imagePath).height(300).asBufferedImage();
} else {
image = Thumbnails.of(imagePath).width(400).asBufferedImage();
}
builder = Thumbnails.of(image).sourceRegion(Positions.CENTER, 400, 300).size(400, 300);
} else {
builder = Thumbnails.of(image).size(400, 300);
}
builder.outputFormat("jpg").toFile("F:\\image\\output\\IMG_20131229_114806");
這種情況複雜些,既不能用size()方法(因為橫高比不一定是4/3,這樣壓縮後的圖片橫為400或高為300),也不能用forceSize()方法。首先判斷橫高比,確定是按照橫400壓縮還是高300壓縮,壓縮後按中心400*300的地區進行裁剪,這樣得到的圖片便是400*300的裁剪後縮圖。
使用size()或forceSize()方法時,如果圖片比指定的尺寸要小(比如size(400, 300),而圖片為40*30),則會展開到指定尺寸。
java使用thumbnailator-0.4.8.jar 產生縮圖