ASP.NET Core使用SkiaSharp实现验证码的示例代码

2025-05-29 0 76

前言

本文并没有实现一个完成的验证码样例,只是提供了在当前.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和平台特定的绑定:

  1. .NET Core / .NET Standard 1.3
  2. Xamarin.Android
  3. Xamarin.iOS
  4. Xamarin.tvOS
  5. Xamarin.Mac
  6. Windows Classic Desktop (Windows.Forms / WPF)
  7. Windows UWP (Desktop / Mobile / Xbox / HoloLens)

使用SkiaSharp

?

1
dotnet add package SkiaSharp --version 1.59.3

ASP.NET验证码

前使用SkiaSharp实现文本绘图功能,代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37
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输出图像:

?

1

2

3

4

5

6
[HttpGet("/api/captcha")]

public IActionResult Captcha()

{

var bytes = SkiaCaptcha.Captcha.GetCaptcha("hello world");

return File(bytes, "image/png");

}

参考

https://skia.org/index_zh

https://github.com/mono/SkiaSharp

https://developer.xamarin.com/api/namespace/SkiaSharp/

demo地址:https://github.com/maxzhang1985/ASPNETCore_Captcha_Skia

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:http://www.cnblogs.com/maxzhang1985/p/8137199.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 ASP.NET Core使用SkiaSharp实现验证码的示例代码 https://www.kuaiidc.com/97888.html

相关文章

发表评论
暂无评论