1. 程式人生 > >C#生成高清縮圖

C#生成高清縮圖

1.原始碼

/// <summary>  
   /// 為圖片生成縮圖    
   /// </summary>  
   /// <param name="phyPath">原圖片的路徑</param>  
   /// <param name="width">縮圖寬</param>  
   /// <param name="height">縮圖高</param>  
   /// <returns></returns>  
   public System.Drawing.Image GetThumbnail(System.Drawing.Image image, int width, int height)  
   {  
       Bitmap bmp = new Bitmap(width, height);  
       //從Bitmap建立一個System.Drawing.Graphics  
       System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);  
       //設定   
       gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;  
       //下面這個也設成高質量  
       gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;  
       //下面這個設成High  
       gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;  
       //把原始影象繪製成上面所設定寬高的縮小圖  
       System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, width, height);  
   
       gr.DrawImage(image, rectDestination, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);  
       return bmp;  
   }  

2.呼叫
HttpPostedFile file = photoFile.PostedFile;  
        if (!file.ContentType.Contains("image"))  
        {  
return "照片格式不合法";  
        }  
        string ext = Path.GetExtension(file.FileName).ToLower();  
        if (ext != ".jpg" && ext != ".gif" && ext != ".png" && ext != ".jpeg")  
        {  
return "請您上傳jpg、gif、png圖片";  
        }  
        if (file.ContentLength > 5 * 1024 * 1024)  
        {  
return "請您上傳512位元組內的圖片";  
        }  
        string newName = Guid.NewGuid().ToString();  
        string tempPath = "upload/";  
        string img = tempPath + newName + ext;  
        string filePath = Server.MapPath(img);  
        if (!Directory.Exists(tempPath))  
        {  
            Directory.CreateDirectory(tempPath);  
        }  
        using (System.Drawing.Image originalImage = System.Drawing.Image.FromStream(file.InputStream))  
        {  
            GetThumbnail(originalImage, 504, 374).Save(filePath);  
        }  

轉自網路,原作者佚名