开源工具Thumbnailator的使用

需求是传入一张大图,按大图的原始比例缩小后,再去将图片截取成我们传入的尺寸。这样做的目的是可以防止截取的只有图片的部分位置,该做法可以尽可能截取图片中间部分。

需要引入的包的pom文件为:

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>net.coobird</groupId>
      <artifactId>thumbnailator</artifactId>
      <version>0.4.8</version>
  </dependency>

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

public class TestThumbnailator {

	public static void main(String[] args) throws IOException {
		TestThumbnailator tt = new TestThumbnailator();
		int min_width=200;
		int min_height=300;
		File file = new File("D:/picture/vert.jpg");
		tt.test7(min_width, min_height, file, "D:/picture/vert1.jpg");

	}
	
	public void test7(int min_width,int min_height,File file,String path) throws IOException {
		FileInputStream fis = new FileInputStream(file);
		BufferedImage bufferedImg = ImageIO.read(fis);
		int imgWidth = bufferedImg.getWidth();
		int imgHeight = bufferedImg.getHeight();
		double sca=1.00f;

		if((imgHeight*min_width)==(imgWidth*min_height)){
			if(imgWidth<=min_width){
				Thumbnails.of(bufferedImg).scale(sca).sourceRegion(Positions.CENTER, imgWidth, imgHeight).toFile(path);
				return;
			}
			sca=(double)min_width/(double)imgWidth;
			Thumbnails.of(bufferedImg).scale(sca).toFile(path);
		}
		//先把按比例压缩,再截height达到设定比例
		if((imgHeight*min_width)>(imgWidth*min_height)){
			if(imgWidth<=min_width){
				Thumbnails.of(bufferedImg).scale(sca).sourceRegion(Positions.CENTER, imgWidth, min_height*imgWidth/min_width).toFile(path);
				return;
			}
			sca=(double)min_width/(double)imgWidth;
			Thumbnails.of(bufferedImg).scale(sca).sourceRegion(Positions.CENTER, (int)(min_width/sca), (int)(min_height/sca)).toFile(path);
		}
		//先把按比例压缩,再截width达到设定比例
		if((imgHeight*min_width)<(imgWidth*min_height)){
			if(imgHeight<=min_height){
				Thumbnails.of(bufferedImg).scale(sca).sourceRegion(Positions.CENTER, min_width*imgHeight/min_height, imgHeight).toFile(path);
				return;
			}
			sca=(double)min_height/(double)imgHeight;
			Thumbnails.of(bufferedImg).scale(sca).sourceRegion(Positions.CENTER, (int)(min_width/sca), (int)(min_height/sca)).toFile(path);
		}
	}
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值