java使用thumbnailator-0.4.8.jar 生成缩略图

场景一:图片尺寸不变,修改图片文件类型

 使用:

    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(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),则会拉伸到指定尺寸。 


转载于:https://my.oschina.net/xiaoyuHe/blog/417602

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值