package com.hunuo.common;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class ImageUtil {
/**
* 產生縮圖
* @param srcImageFile 源圖片檔案的File執行個體 File file = new File("檔案名稱");
* @param dstImageFileName 待產生的縮圖片完整路徑(產生的格式為:image/jpeg);
* @throws Exception
*/
public static void makeSmallImage(File srcImageFile,String dstImageFileName) throws Exception {
FileOutputStream fileOutputStream = null;
JPEGImageEncoder encoder = null;
BufferedImage tagImage = null;
Image srcImage = null;
try{
srcImage = ImageIO.read(srcImageFile);
int srcWidth = srcImage.getWidth(null);//原圖片寬度
int srcHeight = srcImage.getHeight(null);//原圖片高度
int dstMaxSize = 120;//目標縮圖的最大寬度/高度,寬度與高度將按比例縮寫
int dstWidth = srcWidth;//縮圖寬度
int dstHeight = srcHeight;//縮圖高度
float scale = 0;
//計算縮圖的寬和高
if(srcWidth>dstMaxSize){
dstWidth = dstMaxSize;
scale = (float)srcWidth/(float)dstMaxSize;
dstHeight = Math.round((float)srcHeight/scale);
}
srcHeight = dstHeight;
if(srcHeight>dstMaxSize){
dstHeight = dstMaxSize;
scale = (float)srcHeight/(float)dstMaxSize;
dstWidth = Math.round((float)dstWidth/scale);
}
//產生縮圖
tagImage = new BufferedImage(dstWidth,dstHeight,BufferedImage.TYPE_INT_RGB);
tagImage.getGraphics().drawImage(srcImage,0,0,dstWidth,dstHeight,null);
fileOutputStream = new FileOutputStream(dstImageFileName);
encoder = JPEGCodec.createJPEGEncoder(fileOutputStream);
encoder.encode(tagImage);
fileOutputStream.close();
fileOutputStream = null;
}finally{
if(fileOutputStream!=null){
try{
fileOutputStream.close();
}catch(Exception e){
}
fileOutputStream = null;
}
encoder = null;
tagImage = null;
srcImage = null;
System.gc();
}
}
}