Java开源图片工具Thumbnailator简介

来源:互联网 发布:淘宝网开发者 编辑:程序博客网 时间:2024/06/05 18:41

thumbnailator Maven地址

<dependency>    <groupId>net.coobird</groupId>    <artifactId>thumbnailator</artifactId>    <version>0.4.8</version></dependency>

Thumbnailator是一个非常好的图片开源工具,使用起来很方便。

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

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

另外提醒大家一点,若png、gif格式图片中含有透明背景,使用该工具压缩处理后背景会变成黑色,这是Thumbnailator的一个bug,预计后期版本会解决。

0 0
原创粉丝点击