java使用thumbnailator-0.4.8.jar 生成縮略圖

場景一:圖片尺寸不變,修改圖片文件類型ui

 使用:spa

    Thumbnails.of("F:\\image\\IMG_20131229_114806.png")  .scale(1f) orm

            .outputFormat("jpg"圖片

            .toFile("F:\\image\\output\\IMG_20131229_114806");get

    注意:outputFormat:輸出的圖片格式。注意使用該方法後toFile()方法不要再含有文件類型的後綴了,不然會生成 IMG_20131229_114806.jpg.jpg 的圖片。it


場景二:圖片尺寸不變,壓縮圖片文件大小io

使用:bug

    Thumbnails.of("F:\\image\\IMG_20131229_114806.png")  .scale(1f)  float

          .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(400300)  

        .toFile("F:\\image\\output\\IMG_20131229_114806");  


場景四:壓縮至原圖片的百分之多少。

  使用:

            BufferedImage image = ImageIO.read(new File("F:\\image\\IMG_20131229_114806.jpg")); 

            Thumbnails.of(image ).scale(0.25f).toFile("F:\\image\\small\\IMG_20131229_114806.jpg");

 說明:把圖片按照原圖片的25%來壓縮。



場景五:壓縮至指定圖片尺寸(例如:橫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, 400300).size(400300);  

        } else {  

            builder = Thumbnails.of(image).size(400300);  

        }  

        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),則會拉伸到指定尺寸。

相關文章
相關標籤/搜索