首先要控制圖片保存后硬盤后的大小(即占用硬盤的空間,而非尺寸),真正要處理的是控制 System.Drawing.Bitmap.Save 方法的參數。
具體實現如下:
private void ThumbPicture(Image SourceImage, int TargetWidth,string savePath) { int IntWidth; //新的圖片寬 int IntHeight; //新的圖片高 try { int TargetHeight = (int)Math.Round(TargetWidth / (SourceImage.Width * 1.0f / SourceImage.Height)); if (TargetWidth * TargetHeight >= SourceImage.Width * SourceImage.Height) { SourceImage.Save(savePath); SourceImage.Dispose(); return; } //計算縮放圖片的大小 if (SourceImage.Width > TargetWidth && SourceImage.Height <= TargetHeight)//寬度比目的圖片寬度大,長度比目的圖片長度小 { IntWidth = TargetWidth; IntHeight = (IntWidth * SourceImage.Height) / SourceImage.Width; } else if (SourceImage.Width <= TargetWidth && SourceImage.Height > TargetHeight)//寬度比目的圖片寬度小,長度比目的圖片長度大 { IntHeight = TargetHeight; IntWidth = (IntHeight * SourceImage.Width) / SourceImage.Height; } else if (SourceImage.Width <= TargetWidth && SourceImage.Height <= TargetHeight) //長寬比目的圖片長寬都小 { IntHeight = SourceImage.Width; IntWidth = SourceImage.Height; } else//長寬比目的圖片的長寬都大 { IntWidth = TargetWidth; IntHeight = (IntWidth * SourceImage.Height) / SourceImage.Width; if (IntHeight > TargetHeight)//重新計算 { IntHeight = TargetHeight; IntWidth = (IntHeight * SourceImage.Width) / SourceImage.Height; } } var x = (TargetWidth - IntWidth) / 2; var y = (TargetHeight - IntHeight) / 2; using (var newImage = new Bitmap(TargetWidth, TargetHeight)) { using (var graphic = Graphics.FromImage(newImage)) {
// 核心參數啊,感覺相當於PS保存時間的質量設置參數 Int64 qualityLevel = 80L; // 高質量 graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; qualityLevel = 100L; // 低質量 //graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low; //graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed; //qualityLevel = 60L; System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1]; System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1); eParams.Param[0]=new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityLevel); graphic.DrawImage(SourceImage, 0, 0, TargetWidth, TargetHeight); SourceImage.Dispose(); // 使用控制圖片質量的保存方式 //newImage.Save(savePath); newImage.Save(savePath, codec, eParams); } } } catch (Exception ex) { } }