java使用thumbnailator-0.4.8.jar 產生縮圖

來源:互聯網
上載者:User

標籤:

情境一:圖片尺寸不變,修改圖片檔案類型

 使用:

    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 產生縮圖

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.