public static buffered image resize(buffered image source,int targetW,int targetH) {
// targetW,targetth分別代表目標長度和寬度。
int type = source . gettype();
BufferedImage target = null
double sx =(double)targetW/source . getwidth();
double sy =(double)targetH/source . getheight();
//這裏我們想在targetW和target的範圍內實現比例縮放。如果不需要比例縮放
//只需註釋下面的if else語句。
if(sx & gt;sy)
{
sx = sy
targetW =(int)(sx * source . getwidth());
}否則{
sy = sx
targetH =(int)(sy * source . getheight());
}
if (type == BufferedImage。TYPE _ CUSTOM){//手工制作
color model cm = source . getcolormodel();
writable raster raster = cm . createcompatiblewritableraster(targetW,targetH);
boolean alphaPremultiplied = cm . isalphapremultiplied();
target = new BufferedImage(cm,raster,alphaPremultiplied,null);
}否則
target = new buffered image(targetW,targetH,type);
graphics 2d g = target . create graphics();
//比exlax更平滑:
g . setrenderinghint(rendering hints。關鍵渲染,渲染提示。值_渲染_質量);
g . drawrendedimage(source,affinite transform . getscale instance(sx,sy));
g . dispose();
返回目標;
}
public static void savimageasjpg(String from filestr,String saveToFileStr,int width,int hight)
引發異常{
BufferedImage srcImage
//String ex = from filestr . substring(from filestr . index of(" . "),from filestr . length());
String imgType = " JPEG
if (fromFileStr.toLowerCase()。endsWith("。png")) {
imgType = " PNG
}
//system . out . println(ex);
File saveFile =新文件(saveToFileStr);
File fromFile =新文件(from filestr);
src image = imageio . read(from file);
如果(寬度& gt0 ||高度& gt0)
{
srcImage = resize(srcImage,width,height);
}
ImageIO.write(srcImage,imgType,save file);
}
公共靜態void main (String argv[]) {
嘗試{
//參數1(從),參數2(到),參數3(寬度)和參數4(高度)
Saveimageasyjpg ("c: \ \文檔和設置\ \ xugang \ \ desktop \\tmr-06.jpg ",
" c: \ \文檔和設置\ \徐剛\ \桌面\\2.jpg ",
120,120);
} catch(異常e){
e . printstacktrace();
}
}