前言
本文並沒有實現一個完成的驗證碼樣例,只是提供了在當前.NET Core 2.0下使用Drawing API的另一種思路,並以簡單Demo的形式展示出來。
Skia
Skia是一個開源的二維圖形庫,提供各種常用的API,並可在多種軟硬件平台上運行。谷歌Chrome瀏覽器、Chrome OS、安卓、火狐瀏覽器、火狐操作系統以及其它許多產品都使用它作為圖形引擎。
Skia由谷歌出資管理,任何人都可基於BSD免費軟件許可證使用Skia。Skia開發團隊致力於開發其核心部分, 並廣泛采納各方對於Skia的開源貢獻。
SkiaSharp
SkiaSharp是由Mono發起,基於谷歌的Skia圖形庫,實現的一個跨平台的2D圖形.NET API綁定。提供一個全面的2D API,可用於跨移動、服務器和桌面模式的圖形渲染和圖像處理。
skiasharp提供PCL和平台特定的綁定:
- .NET Core / .NET Standard 1.3
- Xamarin.Android
- Xamarin.iOS
- Xamarin.tvOS
- Xamarin.Mac
- Windows Classic Desktop (Windows.Forms / WPF)
- Windows UWP (Desktop / Mobile / Xbox / HoloLens)
使用SkiaSharp
dotnet add package SkiaSharp --version 1.59.3
ASP.NET驗證碼?
前使用SkiaSharp實現文本繪圖功能,代碼如下:
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://github.com/mono/SkiaSharp
https://developer.xamarin.com/api/namespace/SkiaSharp/
demo地址
https://github.com/maxzhang1985/ASPNETCore_Captcha_Skia
GitHub:https://github.com/maxzhang1985/YOYOFx 如果覺還可以請Star下, 歡迎一起交流。
.NET Core 開源學習群:214741894