使用Thumbnails进行图片处理

public class PicTest {
	
	private static final float PIC_SIZE = 500 * 1024;
	
	private static final Logger log = Logger.getLogger(PicTest.class);
	
	public static void main(String[] args) {
		new PicTest().test3();
	}
	
	/**
	 * 图片大于150KB进行大小压缩
	 */
	public void test1(){
		//加载图片源
		File file = new File("D:/pictest/Koala.jpg"); 
		Builder<File> builder = Thumbnails.of(file);
		
		if(file.length()> PIC_SIZE){
			float qualify = PIC_SIZE / file.length();
			try {
				builder.scale(qualify).toFile(file);
			} catch (IOException e) {
				System.out.println("图片压缩失败:" + e);
			}
		}
		
	}
	
	/**
	 * 图片大于500KB进行宽和高压缩
	 */
	public void test2(){
		//加载图片源
		File file = new File("D:/pictest/Koala.jpg"); 
		Builder<File> builder = Thumbnails.of(file);
		
		if(file.length()> PIC_SIZE){
			try {
				builder.size(500, 500).toFile(file);
			} catch (IOException e) {
				System.out.println("图片压缩失败:" + e);
			}
		}
	}
	
	/**
	 * 图片不是jpg格式转换成jpg格式
	 */
	public void test3(){
		File file = new File("D:/pictest/Koala.png"); 
		Builder<File> builder = Thumbnails.of(file);
		
		if(!file.getName().toLowerCase().endsWith("jpg")){
			try {
				builder.scale(1f).outputFormat("jpg").toFile(file);
			} catch (IOException e) {
				System.out.println("图片压缩失败:" + e);
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qiaoxin666/article/details/79036161