萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> asp.net編程 >> c#生成縮略圖不失真的方法

c#生成縮略圖不失真的方法

 使用.net的方法GetThumbnailImage生成的縮略圖失真嚴重,這裡推薦一種不失真生成縮略圖的方法

代碼如下: /// <summary> /// 獲得縮微圖 /// </summary> /// <returns></returns>   public bool GetThumbImg() { try { string imgpath; //原始路徑      if(imgsourceurl.IndexOf("",0)<0) //使用的是相對路徑      { imgpath = HttpContext.Current.Server.MapPath(imgsourceurl); //轉化為物理路徑      } else { imgpath=imgsourceurl; } System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(imgpath); int width = sourceImage.Width; int height = sourceImage.Height; if(thumbwidth <= 0) { thumbwidth = 120; } if(thumbwidth >= width) { return false; } else { (thumbwidth,thHeight*thumbwidth/thWidth,null,IntPtr.Zero); Image imgThumb=new System.Drawing.Bitmap(thumbwidth,height*thumbwidth/width); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(imgThumb); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(sourceImage, new Rectangle(0, 0, thumbwidth,height*thumbwidth/width), 0, 0, width, height, GraphicsUnit.Pixel); string thumbpath=""; sourceImage.Dispose(); if(thumburl=="") { thumbpath=imgpath; } if(thumbpath.IndexOf("",0)<0)//使用的是相對路徑       { thumbpath=HttpContext.Current.Server.MapPath(thumburl);//轉化為物理路徑       } imgThumb.Save(thumbpath,ImageFormat.Jpeg); imgThumb.Dispose(); return true; } } catch { throw; } }  
copyright © 萬盛學電腦網 all rights reserved