轉載自 http://blog.csdn.net/mr_smile2014/article/details/51943568
String yuantu=this.imgFileStore.getRootFile().getPath()+ "/xiangche/" +userid+"/"+newfilename;
//壓縮後的圖片保存地址
String yaosuo=this.imgFileStore.getRootFile().getPath()+ "/xiangche/yashuo/" +userid+"/"+newfilename;
File srcfile = new File(yuantu);
System.out.println("壓縮前srcfile size:" + srcfile.length());
ImageCompress.reduceImg(yuantu,yaosuo, 150,150,null);
File distfile = new File(yaosuo);
System.out.println("壓縮後distfile size:" + distfile.length());
imageCompress
package com.hoosee.actions.util;
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 com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* 圖片壓縮
*
* **/
public class ImageCompress {
/**
* 採用指定寬度、高度或壓縮比例 的方式對圖片進行壓縮
* @param imgsrc 源圖片地址
* @param imgdist 目標圖片地址
* @param widthdist 壓縮後圖片寬度(當rate==null時,必傳)
* @param heightdist 壓縮後圖片高度(當rate==null時,必傳)
* @param rate 壓縮比例
*/
public static void reduceImg(String imgsrc, String imgdist, int widthdist,
int heightdist, Float rate) {
try {
File srcfile = new File(imgsrc);
// 檢查文件是否存在
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(imgdist);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* 獲取圖片寬度
*
* @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;
}
}