1. 程式人生 > >生成高清晰度的縮圖

生成高清晰度的縮圖

以下是我在網上找到的,經驗證失真很小,高質量  
  //呼叫示例  
  this.MakeSmallImg(f.PostedFile,this.Server.MapPath("1.jpg"),600,500);  
  //------------------------------------------------------------  
   
  public   void   MakeSmallImg(System.Web.HttpPostedFile   postFile,string   saveImg,System.Double   Width,System.Double   Height)  
  {  
   
  //原始圖片名稱  
  string   originalFilename   =   postFile.FileName;  
  //生成的高質量圖片名稱  
  string   strGoodFile   =   saveImg;  
   
   
  //從檔案取得圖片物件  
  System.Drawing.Image   image   =   System.Drawing.Image.FromStream(postFile.InputStream,true);  
   
  System.Double   NewWidth,NewHeight;  
  if(image.Width>image.Height)  
  {  
  NewWidth=Width;  
  NewHeight=image.Height*(NewWidth/image.Width);  
  }  
  else  
  {  
  NewHeight=Height;  
  NewWidth=(NewHeight/image.Height)*image.Width;  
  }  
   
  if   (NewWidth>Width)  
  {  
  NewWidth=Width;  
  }  
  if   (NewHeight>Height)  
  {  
  NewHeight=Height;  
  }  
   
  //取得圖片大小  
  System.Drawing.Size   size   =   new   Size((int)NewWidth,(int)NewHeight);  
  //新建一個bmp圖片  
  System.Drawing.Image   bitmap   =   new   System.Drawing.Bitmap(size.Width,size.Height);  
  //新建一個畫板  
  System.Drawing.Graphics   g   =   System.Drawing.Graphics.FromImage(bitmap);  
  //設定高質量插值法  
  g.InterpolationMode   =   System.Drawing.Drawing2D.InterpolationMode.High;  
  //設定高質量,低速度呈現平滑程度  
  g.SmoothingMode   =   System.Drawing.Drawing2D.SmoothingMode.HighQuality;  
  //清空一下畫布  
  g.Clear(Color.White);  
  //在指定位置畫圖  
  g.DrawImage(image,   new   System.Drawing.Rectangle(0,   0,   bitmap.Width,   bitmap.Height),    
  new   System.Drawing.Rectangle(0,   0,   image.Width,image.Height),  
  System.Drawing.GraphicsUnit.Pixel);  
   
   
  ///文字水印  
  //System.Drawing.Graphics   G=System.Drawing.Graphics.FromImage(bitmap);  
  //System.Drawing.Font   f=new   Font("宋體",10);  
  //System.Drawing.Brush   b=new   SolidBrush(Color.Black);  
  //G.DrawString("myohmine",f,b,10,10);  
  //G.Dispose();  
   
   
   
  ///圖片水印  
  //System.Drawing.Image   copyImage   =   System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("pic/1.gif"));  
  //Graphics   a   =   Graphics.FromImage(bitmap);  
  //a.DrawImage(copyImage,   new   Rectangle(bitmap.Width-copyImage.Width,bitmap.Height-copyImage.Height,copyImage.Width,   copyImage.Height),0,0,   copyImage.Width,   copyImage.Height,   GraphicsUnit.Pixel);  
   
  //copyImage.Dispose();  
  //a.Dispose();  
  //copyImage.Dispose();  
   
   
  //儲存高清晰度的縮圖  
  bitmap.Save(strGoodFile,   System.Drawing.Imaging.ImageFormat.Jpeg);  
   
  g.Dispose();  
  image.Dispose();  
  bitmap.Dispose();  
  }