服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - ASP.NET教程 - ASP.NET Core使用SkiaSharp实现验证码的示例代码

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

2020-05-21 14:50YOYOFx ASP.NET教程

本篇文章主要介绍了ASP.NET Core使用SkiaSharp实现验证码的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

前言

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

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

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

延伸 · 阅读

精彩推荐