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

//首先NuGet安装:Magick.NET.Core,Magick.NET-Q16-AnyCPU
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 @ 2023-06-12 13:39  你好创造者  阅读(345)  评论(0编辑  收藏  举报