参考代码(需要安装 nuget 包 System.Drawing.Common)
using (Image originImage = Image.FromStream(originImageStream))
{
using (var bitmap = new Bitmap(newWidth, newHeight))
{
using (var graphic = GetGraphic(originImage, bitmap))
{
graphic.DrawImage(originImage, 0, 0, newWidth, newHeight);
using (var encoderParameters = new EncoderParameters(1))
{
using (var encoderParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L))
{
encoderParameters.Param[0] = encoderParameter;
bitmap.Save(newImageStream,
ImageCodecInfo.GetImageEncoders().Where(x => x.MimeType.Equals(mimeType, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(),
encoderParameters);
}
}
}
}
}
由于.net core缺乏基于图像的 API,所以需要引用第三方包
可以参数针对.NET Core的图像类库
缩放代码,引用的nuget包是ZKWeb.System.Drawing
public static Image ZoomImage(Image image, int destWidth, int destHeight, string ext = "png") { try { var sourceImage = image; int width, height; var sourceWidth = sourceImage.Width; var sourceHeight = sourceImage.Height; if (sourceHeight > destHeight || sourceWidth > destWidth) { if (sourceWidth * destHeight > sourceHeight * destWidth) { width = destWidth; height = destWidth * sourceHeight / sourceWidth; } else { height = destHeight; width = sourceWidth * destHeight / sourceHeight; } } else { width = sourceWidth; height = sourceHeight; } var destBitmap = new Bitmap(destWidth, destHeight); var g = Graphics.FromImage(destBitmap); g.Clear(ext == "png" ? Color.Transparent : Color.White); g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(sourceImage, new Rectangle((destWidth - width) / 2, (destHeight - height) / 2, width, height), 0, 0, sourceImage.Width, sourceImage.Height, GraphicsUnit.Pixel); g.Dispose(); var encoderParams = new EncoderParameters(); var quality = new long[1]; quality[0] = 100; var encoderParam = new EncoderParameter(Quality, quality); encoderParams.Param[0] = encoderParam; sourceImage.Dispose(); return destBitmap; } catch { return image; } }
.NET Core 2.0 开始提供了 System.Drawing.Common
@dudu:
好的~没了解
skiasharp 这个组件挺好用的