场景一:图片尺寸不变,修改图片文件类型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(400, 300)
.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, 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),则会拉伸到指定尺寸。