本文並無實現一個完成的驗證碼樣例,只是提供了在當前.NET Core 2.0下使用Drawing API的另外一種思路,並以簡單Demo的形式展現出來。git
Skia是一個開源的二維圖形庫,提供各類經常使用的API,並可在多種軟硬件平臺上運行。谷歌Chrome瀏覽器、Chrome OS、安卓、火狐瀏覽器、火狐操做系統以及其它許多產品都使用它做爲圖形引擎。github
Skia由谷歌出資管理,任何人均可基於BSD免費軟件許可證使用Skia。Skia開發團隊致力於開發其核心部分, 並普遍採納各方對於Skia的開源貢獻。canvas
SkiaSharp是由Mono發起,基於谷歌的Skia圖形庫,實現的一個跨平臺的2D圖形.NET API綁定。提供一個全面的2D API,可用於跨移動、服務器和桌面模式的圖形渲染和圖像處理。api
skiasharp提供PCL和平臺特定的綁定:瀏覽器
dotnet add package SkiaSharp --version 1.59.3
前使用SkiaSharp實現文本繪圖功能,代碼以下:bash
internal static byte[] GetCaptcha(string captchaText) { byte[] imageBytes = null; int image2d_x = 0; int image2d_y = 0; SKRect size; int compensateDeepCharacters = 0; using (SKPaint drawStyle = CreatePaint()) { compensateDeepCharacters = (int)drawStyle.TextSize / 5; if (System.StringComparer.Ordinal.Equals(captchaText, captchaText.ToUpperInvariant())) compensateDeepCharacters = 0; size = SkiaHelpers.MeasureText(captchaText, drawStyle); image2d_x = (int)size.Width + 10; image2d_y = (int)size.Height + 10 + compensateDeepCharacters; } using (SKBitmap image2d = new SKBitmap(image2d_x, image2d_y, SKColorType.Bgra8888, SKAlphaType.Premul)) { using (SKCanvas canvas = new SKCanvas(image2d)) { canvas.DrawColor(SKColors.Black); // Clear using (SKPaint drawStyle = CreatePaint()) { canvas.DrawText(captchaText, 0 + 5, image2d_y - 5 - compensateDeepCharacters, drawStyle); } using (SKImage img = SKImage.FromBitmap(image2d)) { using (SKData p = img.Encode(SKEncodedImageFormat.Png, 100)) { imageBytes = p.ToArray(); } } } } return imageBytes; }
ASP.NET Core輸出圖像:服務器
[HttpGet("/api/captcha")] public IActionResult Captcha() { var bytes = SkiaCaptcha.Captcha.GetCaptcha("hello world"); return File(bytes, "image/png"); }
https://skia.org/index_zhasp.net
https://github.com/mono/SkiaSharp學習
https://developer.xamarin.com/api/namespace/SkiaSharp/spa
https://github.com/maxzhang1985/ASPNETCore_Captcha_Skia
GitHub:https://github.com/maxzhang1985/YOYOFx 若是覺還能夠請Star下, 歡迎一塊兒交流。
.NET Core 開源學習羣:214741894