图片压缩工具类

ImageCompressUtils.java
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;
 
import com.sun.image.codec.jpeg.*;
 
/** 
 * 图片压缩工具类
 * @author Gxx
 */
public class ImageCompressUtils {
 
	/**
	 * 采用指定宽度、高度或压缩比例 的方式对图片进行压缩
	 * @param dir 目录
	 * @param imgSrcName 源图片名称
	 * @param imgDestName 目标图片名称
	 * @param widthdist 压缩后图片宽度(当rate==null时,必传)
	 * @param heightdist 压缩后图片高度(当rate==null时,必传)
	 * @param rate 压缩比例 
	 */
	public static void compress(String dir, String imgSrcName, String imgDestName, int widthdist, int heightdist, Float rate) {
		try {
			File srcfile = new File(dir + imgSrcName);
			// 检查文件是否存在
			if (!srcfile.exists()) {
				return;
			}
			// 如果rate不为空说明是按比例压缩
			if (rate != null && rate > 0) {
				// 获取文件高度和宽度
				int[] results = getImgWidth(srcfile);
				if (results == null || results[0] == 0 || results[1] == 0) {
					return;
				} else {
					widthdist = (int) (results[0] * rate);
					heightdist = (int) (results[1] * rate);
				}
			}
			// 开始读取文件并进行压缩
			Image src = javax.imageio.ImageIO.read(srcfile);
			BufferedImage tag = new BufferedImage((int) widthdist,
					(int) heightdist, BufferedImage.TYPE_INT_RGB);
 
			tag.getGraphics().drawImage(
					src.getScaledInstance(widthdist, heightdist,
							Image.SCALE_SMOOTH), 0, 0, null);
 
			FileOutputStream out = new FileOutputStream(dir + imgDestName);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(tag);
			out.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
 
	/**
	 * 对图片进行压缩 - 如果宽度和高度都大于150才压缩
	 * @param dir 目录
	 * @param imgSrcName 源图片名称
	 * @param imgDestName 目标图片名称
	 */
	public static void compressWithCheck(String dir, String imgSrcName, String imgDestName) {
		File srcfile = new File(dir + imgSrcName);
		/**
		 * 检查文件是否存在
		 */
		if (!srcfile.exists()) {
			return;
		}
		int[] results = getImgWidth(srcfile);
		if (results == null || results[0] == 0 || results[1] == 0) {
			return;
		}
		int width = results[0];
		int height = results[1];
		/**
		 * 如果宽度和高度都大于150才压缩
		 */
		if(width <= 150 || height <= 150) {
			return;
		}
		int newWidth = 150;
		int newHeight = 150;
		if(width > height) {
			newWidth = (int)(width*150.0/height);
		} else {
			newHeight = (int)(height*150.0/width);
		}
		/**
		 * 检查文件是否存在
		 */
		compress(dir, imgSrcName, imgDestName, newWidth, newHeight, null);
	}
 
	/** 
     * 获取图片宽度和高度
     * @param file 图片文件
     * @return
     */  
    public static int[] getImgWidth(File file) {  
        InputStream is = null;  
        BufferedImage src = null;  
        int result[] = { 0, 0 };  
        try {  
            is = new FileInputStream(file);  
            src = javax.imageio.ImageIO.read(is);  
            result[0] = src.getWidth(null); // 得到源图宽  
            result[1] = src.getHeight(null); // 得到源图高  
            is.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return result;  
    }
 
    /**
     * main方法
     * @param args
     */
    public static void main(String[] args) {
    	int n = 0;
    	for(int i=36;i<=36;i++) {
    		System.out.println(new Date().getTime());
        	String dir = "/Users/guanxianghui/Desktop/img/";
        	String originFile = "WechatIMG3" + i + ".jpeg";
        	String uuid = UUID.randomUUID().toString().toLowerCase().replaceAll("-", "");
        	String destFile = (++n) + "_" + uuid + ".png"; 
        	String destFile_sm = (n) + "_" + uuid + "_sm" + ".png"; 
            File srcfile = new File(dir + originFile);  
        	int[] widthAndHeight = getImgWidth(srcfile);
        	System.out.println("width=" + widthAndHeight[0] + ",height=" + widthAndHeight[1]);
            System.out.println("压缩图片开始...");  
            System.out.println("压缩前srcfile size:" + srcfile.length());  
            compress(dir, originFile, destFile, 1500, (int)(widthAndHeight[1]*1500.0/widthAndHeight[0]),null);  
            compress(dir, originFile, destFile_sm, 150, (int)(widthAndHeight[1]*150.0/widthAndHeight[0]),null);  
            File distfile = new File(destFile);  
            System.out.println("压缩后distfile size:" + distfile.length());
        	System.out.println(new Date().getTime());
    	}
    }  
}