天天看点

java图片压缩--Thumbnailator.jar

package com.dhcc.csm.utils.thumbnailator;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.Date;

import javax.imageio.ImageIO;

import com.dhcc.csm.utils.DateUtils;

import net.coobird.thumbnailator.Thumbnails;

public class Thumbnailator {
	private static DecimalFormat df = new DecimalFormat("#.00");
	private static final int bigSize = 100;
	private static final int smallSize = 50;  
	public static void main(String[] args) {
		File file = new File("D:\\dhceprftp\\c.png");
		System.out.println(thumbnail(file).toString());
	}

	/**
	 * 不按照比例,指定大小进行缩放
	 * 
	 * @param inFilepath
	 * @param width
	 * @param height
	 * @param outFilepath
	 * @throws IOException
	 */
	public static void keepAspectRatioFalse(String inFilepath, int width, int height, String outFilepath){
		try {
			Thumbnails.of(inFilepath).size(width, height).keepAspectRatio(false).toFile(outFilepath);
		}catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	//宽高缩放相同百分比压缩图片
	public static File thumbnail(File sourcefile) {		
		File realFile = sourcefile;
		if (sourcefile.exists() && sourcefile.isFile()) {
			InputStream is = null;
	        BufferedImage src = null;
			int width = -1;
	        int height = -1;
			try {
	            is = new FileInputStream(sourcefile);
	            src = ImageIO.read(is);
	            width = src.getWidth(null); // 得到源图宽
	            height = src.getHeight(null); // 得到源图高
	            is.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
			
			int newWidth = width;
			int newHeight = height;
			double rete = 0.3;
			double bigRete = 0.3; 
			double smallRete = 0.3; 
			//源文件大小大于bigSize kb的,压缩;源文件大小小于bigSize kb的,放大
			int i = 0;
			while((int)(realFile.length() / 1024) > bigSize || (int)(realFile.length() / 1024) < smallSize) {
				// 计算缩略图最总的宽度和高度
				System.out.println((int)(realFile.length() / 1024));
				if((int)(realFile.length() / 1024) > bigSize) {
					bigRete = bigRete - 0.05;
					rete = Double.parseDouble(df.format(bigRete));
				}
				
				if((int)(realFile.length() / 1024) < smallSize) {
					smallRete = smallRete + 0.1;
					rete = Double.parseDouble(df.format(smallRete));
				}
				
				if(i>0) {
					realFile.delete();
				}
				
				newWidth = (int) (width * rete);
	            newHeight = (int) (height * rete);
	            
	            if(newWidth!=0 && newHeight!=0) {
		            System.out.println(newWidth+"=="+newHeight);
		            String filepath = sourcefile.toString();
		    		String newFilePath = filepath.substring(0,filepath.indexOf(sourcefile.getName()))+DateUtils.yyyyMMddHHmmssSSS(new Date()) + ".jpg";
		            keepAspectRatioFalse(filepath, newWidth, newHeight, newFilePath);
		            realFile = new File(newFilePath);
				} 
	            i++;
			}
		}
		return realFile;
    }
}