////// 為圖片生成縮略圖 /// /// 原圖片的路徑 /// 縮略圖寬 /// 縮略圖高 ///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; }
調用方法
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); }