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, "加载图片失败");
                }
            }
复制代码

 

posted on   空明流光  阅读(684)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2018-03-30 Eclipse 使用 VS Emulator for android 调试环境配置 步骤
2018-03-30 android ListView 可缩放,支持左右上下手势
2017-03-30 asp.net Checkbox 绑定自定义属性

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示