先看java代碼:
import java.io.File;
import javax.imageio.ImageIO;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
try{
String fileName = "D:\\soft\\Tomcat 6.0\\webapps\\XXX\\upload\\images\\me.jpg";
File f = new File(fileName); //得到原始文件
double newHeight = 1.0; //設置縮放比例
double newWeight = 1.0; //設置縮放比例
String dir = "D:\\soft\\Tomcat 6.0\\webapps\\tianjin\\upload\\images";
File newFile = new File(dir,"me.jpg"); //新的文件路徑及名字
BufferedImage bi = ImageIO.read(f);
//假設圖片寬 高 最大為120 120
Image itemp = bi.getScaledInstance (120,120,bi.SCALE_SMOOTH);
if((bi.getHeight()>120) || (bi.getWidth()>120)){
if (bi.getHeight()>bi.getWidth()){
newHeight = 120.0/bi.getHeight();
}else{
newWeight = 120.0/bi.getWidth();
}
}
www.2cto.com
AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(newHeight, newWeight), null);
itemp = op.filter(bi, null);
try {
ImageIO.write((BufferedImage)itemp,"jpg", newFile);
System.out.println("well done");
}catch (Exception ex) {
ex.printStackTrace();
}
}catch(Exception e){
}
則在JSP中,先用smartupload上傳到服務器上,然後再用上面的代碼把它進行縮放以後,或者覆蓋原有的圖片,或者創建新的文件。