『.NET』.Net Core在Linux中生成验证码的实现封装


📣读完这篇文章里你能收获到

  • .Net跨平台在Linux中及Windows中都可生成验证码
  • 两套已验证过的实现方案代码封装,即Copy即用
  • 快速在Centos 7.x中安装Linux字体

请添加图片描述

一、安装Linux字体

我以Centos 7.x为例,其他系统自行百度:xx系统安装字体

1. 查看字体库

如果没数据的话就继续往下走,先把字体库安装好
如果有数据的话,则跳过,直接进入第二点使用代码

fc-list

2. 运行安装字体库

yum -y install fontconfig

image.png

3. 安装ttmkfdir

用来搜索目录中所有的字体信息,并汇总生成fonts.scale文件

yum -y install ttmkfdir

image.png

4. 查看字体库是否已安装成功

fc-list

image.png

二、.NET 代码实现封装

1. SixLabors.ImageSharp方案

1.1 效果

1.jpg

1.2 源码链接

https://github.com/SixLabors/ImageSharp

1.3 Nuget依赖

<!--Nuget依赖-->
<PackageReference Include="SixLabors.ImageSharp" Version="2.1.3" />
<PackageReference Include="SixLabors.ImageSharp.Drawing" Version="1.0.0-beta15" />

1.4 Helper代码封装

using SixLabors.ImageSharp;
using SixLabors.Fonts;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Drawing.Processing;
using System;
using System.Linq;

namespace VertifyCode
{
    public class VerifyCodeHelper
    {
        private static readonly Color[] Colors = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown,
                                                  Color.Brown,Color.DarkBlue};
        private static readonly char[] Chars = { '2','3','4','5','6','8','9',
                                                'A','B','C','D','E','F','G','H','J','K', 'L','M','N','P','R','S','T','W','X','Y' };
        //private static readonly int Width = 90;
        //private static readonly int Height = 35;

        private static string GenCode(int num)
        {
            var code = string.Empty;
            var r = new Random();

            for (int i = 0; i < num; i++)
            {
                code += Chars[r.Next(Chars.Length)].ToString();
            }

            return code;
        }

        public static (string code, byte[] bytes) CreateValidateGraphic(int CodeLength, int Width = 80, int Height = 40, int FontSize = 14)
        {
            var code = GenCode(CodeLength);
            var r = new Random();
            using var image = new Image<Rgba32>(Width, Height);
            // 字体
            var font = SystemFonts.CreateFont(SystemFonts.Families.First().Name, FontSize, FontStyle.Bold);
            image.Mutate(ctx =>
                         {
                             // 白底背景
                             ctx.Fill(Color.White);

                             // 画验证码
                             for (int i = 0; i < code.Length; i++)
                {
                    ctx.DrawText(code[i].ToString()
                                 , font
                                 , Colors[r.Next(Colors.Length)]
                                 , new PointF(20 * i + 10, r.Next(2, 12)));
                }

                             // 画干扰线
                             for (int i = 0; i < 6; i++)
                {
                    var pen = new Pen(Colors[r.Next(Colors.Length)], 1);
                    var p1 = new PointF(r.Next(Width), r.Next(Height));
                    var p2 = new PointF(r.Next(Width), r.Next(Height));

                    ctx.DrawLines(pen, p1, p2);
                }

                             // 画噪点
                             for (int i = 0; i < 60; i++)
                {
                    var pen = new Pen(Colors[r.Next(Colors.Length)], 1);
                    var p1 = new PointF(r.Next(Width), r.Next(Height));
                    var p2 = new PointF(p1.X + 1f, p1.Y + 1f);

                    ctx.DrawLines(pen, p1, p2);
                }
                         });
            using var ms = new System.IO.MemoryStream();

            //  格式 自定义
            image.SaveAsPng(ms);
            return (code, ms.ToArray());
        }
    }
}

2. SkiaSharp方案

2.1 效果

1.png

2.2 源码链接

https://github.com/mono/SkiaSharp

2.3 Nuget依赖

<!--Nuget依赖-->
<PackageReference Include="SkiaSharp" Version="2.88.3" />
<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="2.88.3" />

2.4 Helper代码封装

using SkiaSharp;
using System;

namespace VertifyCode
{

    public class VerifyCodeImageSharpHelper
    {

        private static readonly char[] Chars = { '2','3','4','5','6','8','9',
       'A','B','C','D','E','F','G','H','J','K', 'L','M','N','P','R','S','T','W','X','Y' };

        private static string GenCode(int num)
        {
            var code = string.Empty;
            var r = new Random();

            for (int i = 0; i < num; i++)
            {
                code += Chars[r.Next(Chars.Length)].ToString();
            }

            return code;
        }

        public static (string code, byte[] bytes) CreateValidateGraphic(int codeLength, int width = 80, int height = 40, int fontSize = 20)
        {
            var code = GenCode(codeLength);

            byte[] imageBytes = null;
            int image2d_x = 0;
            int image2d_y = 0;
            SKRect size;
            int compensateDeepCharacters = 0;
            using (SKPaint drawStyle = CreatePaint(fontSize))
            {
                size = MeasureText(code, drawStyle);
                image2d_x = width;
                image2d_y = height;
            }

            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(fontSize))
                    {
                        canvas.DrawText(code, 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 (code,imageBytes);
            }
        }

        private static SKPaint CreatePaint(int fontSize)
        {
            string font = @"";
            font = @"Arial";
            font = @"Liberation Serif";
            font = @"Segoe Script";
            font = @"Consolas";
            font = @"Comic Sans MS";
            font = @"SimSun";
            font = @"Impact";

            return CreatePaint(SKColors.White, font, fontSize, SKTypefaceStyle.Normal);
        }


        private static SKPaint CreatePaint(SKColor color, string fontName, float fontSize, SKTypefaceStyle fontStyle)
        {
            SKTypeface font = SKTypeface.FromFamilyName(fontName, fontStyle);

            SKPaint paint = new SKPaint();

            paint.IsAntialias = true;
            paint.Color = color;
            // paint.StrokeCap = SKStrokeCap.Round;
            paint.Typeface = font;
            paint.TextSize = fontSize;

            return paint;
        }

        // MeasureText("Impact", 12, SKTypefaceStyle.Bold);
        internal static SKRect MeasureText(string text, SKPaint paint)
        {
            SKRect rect = new SKRect();
            paint.MeasureText(text, ref rect);
            return rect;
        } // End Function MeasureText 

    }
}

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇

)">
下一篇>>