图像缩略图的Java类库Thumbnailator

今天经同事介绍了一款java图像缩略图类库Thumbnailator,尝试了下,效果还不错,使用也比较方便,收藏一下。github地址: https://github.com/coobird/thumbnailator,简介和使用范例: https://www.oschina.net/question/76860_25758?sort=default&p=2

BufferedImage image=ImageIO.read(new File("d://12.jpg"));
//按比例、图片质量缩放		Thumbnails.of(image).scale(0.5f).outputQuality(0.5).toFile("d://14.jpg");
//指定宽高等比缩放:指定的宽高可能不成比例,会依据宽或高调整尺寸,到底依据宽,还是高,采用最小缩放原则
Thumbnails.of(image).size(100, 250).toFile("d://13.jpg");

之前对于等比缩放在具体场景中的使用还存在疑问,如何去确定最终的尺寸?ckfinder实现了图片的等比压缩,研究了下其实现。在ckfinder中设置了imgWidth、imgHeight、imgQuality,最大宽度、高度、图片质量,以下方法去计算最终尺寸:
private static Dimension createThumbDimension(BufferedImage image, int maxWidth, int maxHeight)
	Dimension dimension = new Dimension();
	if (image.getWidth() >= image.getHeight()) {
		if (image.getWidth() >= maxWidth) {
			dimension.width = maxWidth;
			dimension.height = Math.round(maxWidth / image.getWidth() * image.getHeight());
		}else {
			dimension.height = image.getHeight();
			dimension.width = image.getWidth();
		}
	}else if (image.getHeight() >= maxHeight) {
	      dimension.height = maxHeight;
	      dimension.width = Math.round(maxHeight / image.getHeight() * image.getWidth());
	}else {
	      dimension.height = image.getHeight();
	      dimension.width = image.getWidth();
	}
	return dimension;
}
从上述代码可以看出,找出宽、高较大的值使其等于配置中的最大值(大于配置最大值的情况),再按照缩放比例调整对应的宽或者高。确定了尺寸方案,我们就可以结合thumbnailator实现自己的图片压缩。

猜你喜欢

转载自sheungxin.iteye.com/blog/2364139
今日推荐