Magick.NET跨平台压缩图片的用法

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
//首先NuGet安装:Magick.NET.Core,Magick.NET-Q16-AnyCPU<br>using ImageMagick;
 
/// <summary>
        /// 压缩图片
        /// </summary>
        /// <param name="imageData">图片字节流</param>
        /// <param name="maxWidth">最大宽度</param>
        /// <param name="maxHeight">最大高度</param>
        /// <returns></returns>
        public static byte[] CompressImage(byte[] imageData, int maxWidth, int maxHeight)
        {
            using var image = new MagickImage(imageData);
            double width = image.Width;
            double height = image.Height;
 
            double scale = Math.Min(maxWidth / width, maxHeight / height);
 
            if (scale >= 1) //图片尺寸不高于最大尺寸,直接返回原图 
                return imageData;
 
            int newWidth = (int)Math.Round(width * scale, MidpointRounding.AwayFromZero);
            int newHeight = (int)Math.Round(height * scale, MidpointRounding.AwayFromZero);
 
            image.Resize(newWidth, newHeight);
 
            var compressedImage = image.ToByteArray(MagickFormat.Jpg);
 
            return compressedImage;
        }

  

posted @   你好创造者  阅读(379)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
点击右上角即可分享
微信分享提示