开源工具Thumbnailator的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_37622786/article/details/81003567

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

需要引入的包的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);
		}
	}
	
}

猜你喜欢

转载自blog.csdn.net/weixin_37622786/article/details/81003567