c# 图像压缩
/// <summary> /// 图片尺寸压缩 /// </summary> /// <param name="bitmap"></param> /// <param name="maxWidth"></param> /// <param name="maxHeight"></param> /// <returns></returns> public static System.Drawing.Bitmap CompressImageWithSize(System.Drawing.Bitmap bitmap, int maxWidth = 1024 , int maxHeight = 1024) { int actualWidth = bitmap.Width < maxWidth ? bitmap.Width : maxWidth; int actualHeight = int.Parse(Math.Round(bitmap.Height * (double)actualWidth / bitmap.Width).ToString()); try { var actualBitmap = new System.Drawing.Bitmap(actualWidth, actualHeight); var g = System.Drawing.Graphics.FromImage(actualBitmap); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default; g.DrawImage(bitmap, new System.Drawing.Rectangle(0, 0, actualWidth, actualHeight) , new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height) , System.Drawing.GraphicsUnit.Pixel); g.Dispose(); return actualBitmap; } catch (Exception ex) { MessageBox.Show(ex.Message, "压缩图片时发生错误"); return null; } } /// <summary> /// 图像质量压缩 /// </summary> /// <param name="bitmap"></param> /// <param name="quality">质量压缩率,取值0到100</param> /// <returns></returns> public static System.Drawing.Bitmap CompressImageWithQuality(System.Drawing.Bitmap bitmap, System.Drawing.Imaging.ImageCodecInfo encoding , int quality = 20) { var ps = new System.Drawing.Imaging.EncoderParameters(1); ps.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); var stream = new MemoryStream(); bitmap.Save(stream, encoding , ps); var compressedBitmap = new System.Drawing.Bitmap(stream); return compressedBitmap; } private static Dictionary<string, System.Drawing.Imaging.ImageCodecInfo> GetImageEncoders() { var result = new Dictionary<string, System.Drawing.Imaging.ImageCodecInfo>(); var encoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders().ToList(); foreach (var encode in encoders) result.Add(encode.MimeType, encode); return result; }
调用示例:
var dialog = new Microsoft.Win32.OpenFileDialog { Filter = "图像文件|*.*" }; if (dialog.ShowDialog() == true) { try { using (var originalBitmap = new System.Drawing.Bitmap(dialog.FileName)) { using (var resizedBitmap = CompressImageWithSize(originalBitmap)) { var encoding = GetImageEncoders()["image/jpeg"]; using (var compressedBitmap = CompressImageWithQuality(resizedBitmap, encoding ,20)) { using (var stream = new MemoryStream()) { compressedBitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); //dataItem.ImageStream = stream; //ViewModel.LastModifiedTime = DateTime.Now; } } } } } catch (Exception ex) { MessageBox.Show(ex.Message, "加载图片失败"); } }
桂棹兮兰桨,击空明兮溯流光。