在.NET 6中,微软官方建议把 System.Drawing.Common 迁移到 SkiaSharp 库。因为System.Drawing.Common 被设计为 Window 技术的精简包装器,因此其跨平台实现欠佳。
SkiaSharp是一个基于谷歌的Skia图形库(Skia.org)的用于.NET平台的跨平台2D图形API
它提供了一个全面的2D API,可以跨移动、服务器和桌面模型来渲染图像。
SkiaSharp提供跨平台绑定:.NET Standard 1.3、.NET Core、.NET 6、Tizen、Android、iOS、tvOS、watchOS、macOS、Mac Catalyst、WinUI 3 (Windows App SDK / Uno Platform)、Windows Classic Desktop (Windows.Forms / WPF)、Windows UWP (Desktop / Mobile / Xbox / HoloLens)、Web Assembly (WASM)、Uno Platform (iOS / macOS / Android / WebAssembly / UWP)。
.NET Core中使用SkiaSharp示例
安装SkiaSharp包
NuGet\Install-Package SkiaSharp -Version 2.88.3
使用SkiaSharp调整图片大小:
var rootPath = Directory.GetCurrentDirectory(); // 获取站点根目录using (var file = System.IO.File.OpenRead(rootPath + "\\1.png")) // 读取文件{using (var fileStream = new SKManagedStream(file)){using (var bitmap = SKBitmap.Decode(fileStream)){// 调整图片到100x80using (var resized = bitmap.Resize(new SKImageInfo(100, 80), SKFilterQuality.Medium)){if (resized != null){using (var image = SKImage.FromBitmap(resized)){using (var writeStream = System.IO.File.OpenWrite(rootPath + "\\new-1.png")){image.Encode(SKEncodedImageFormat.Png, 80).SaveTo(writeStream); // 保存文件}}}}}}
使用SkiaSharp创建验证码图片:
using (var surface = SKSurface.Create(new SKImageInfo(100, 80)))
{var canvas = surface.Canvas;canvas.Clear(SKColors.Blue);var paint = new SKPaint(){Color = SKColors.Red,IsAntialias = true, // 抗锯齿Style = SKPaintStyle.Fill,TextAlign = SKTextAlign.Center,TextSize = 16f,Typeface = SKTypeface.FromFamilyName("Microsoft YaHei", SKFontStyle.Bold)};var coord = new SKPoint(50, 48);canvas.DrawText("my text", coord, paint);using (var image = surface.Snapshot()){using (var writeStream = System.IO.File.OpenWrite(rootPath + "\\code-img.png")){image.Encode(SKEncodedImageFormat.Png, 80).SaveTo(writeStream);}}
}
也可以在canvas上画图片做一些截取图片的操作,可以调用canvas.DrawImage方法。
总体来说用法和原来的System.Drawing.Common库类似,旧的代码稍微做一些修改就可以了。