ZT 上傳圖片的縮放處理

來源:互聯網
上載者:User
圖片上傳到伺服器後,會根據情況將圖片縮小成一個表徵圖,我們可以利用java強大的圖形處理功能,對上傳的圖片進行縮放處理.
下面的程式使用jdk1.4中最新的ImageIO對圖片進行讀寫.使用AffineTransform對圖片進行縮放.
import java.io.File;
import java.awt.image.BufferedImage;
import java.awt.Image;
import java.awt.image.AffineTransformOp;
import javax.imageio.ImageIO;
import java.awt.geom.AffineTransform;
public class UploadImg{
/**
* @param fromdir 圖片的原始目錄
* @param todir 處理後的圖片存放目錄
* @param imgfile 原始圖片
* @param sysimgfile 處理後的圖片檔案名稱首碼
*
*/
............................
public boolean CreateThumbnail() throws Exception
{
//ext是圖片的格式 gif JPG 或png
String ext="";
double Ratio=0.0;
File F = new File(fromdir,imgfile);
if (!F.isFile())
throw new Exception(F+" is not image file error in CreateThumbnail!");
//首先判斷上傳的圖片是gif還是JPG ImageIO只能將gif轉換為png
if (isJpg(imgfile)){
ext="jpg";
}else{
ext="png";
}
File ThF = new File(todir,sysimgfile+"."+ext);
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())
Ratio = 120.0/Bi.getHeight();
else
Ratio = 120.0/Bi.getWidth();
}
AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(Ratio, Ratio), null);
Itemp = op.filter(Bi, null);
try {
ImageIO.write((BufferedImage)Itemp, ext, ThF);
}catch (Exception ex) {
throw new Exception(" ImageIo.write error in CreatThum.: "+ex.getMessage());
}
return (true);
}
}
該程式由於使用到Java 的AWT,雖然沒有顯示,但是在linux系統下,程式需要X11 windows的支援.需要安裝 XFree86
或XFree86-Xvfb ,加入 export DISPLAY=hostdomain:0.0
為這個問題,我也頭疼半天,查詢網上類似我這樣抱怨很多,既然Java是一次編寫,到處運行,好象有點名不副實.
當然也可以使用PJA VNC 或ACME Laboratories 但由於該程式使用到jdk1.4最新的類,估計其他替代產品沒有出來,只好作罷.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.