Install-Package SkiaSharp

 

第2步:编写生成图片验证码的代码

 

using SkiaSharp; //在类文件头部添加引用

 

public IActionResult Code()

{

    string CodeText = "3bm7"; //实际的项目中不能写死

    var charList = CodeText.ToList();

    SKBitmap bmp = new SKBitmap(80,30);

    using (SKCanvas canvas = new SKCanvas(bmp))

    {

        //背景色

        canvas.DrawColor(SKColors.White);

 

        using (SKPaint sKPaint = new SKPaint())

        {

            sKPaint.TextSize = 16;//字体大小

            sKPaint.IsAntialias = true;//开启抗锯齿                  

            sKPaint.Typeface = SKTypeface.FromFamilyName("微软雅黑");

            SKRect size = new SKRect();

//计算文字宽度以及高度

            sKPaint.MeasureText(charList[0].ToString(), ref size);

            float temp = (bmp.Width / 4 - size.Size.Width) / 2;

            float temp1 = bmp.Height - (bmp.Height - size.Size.Height) / 2;

            Random random = new Random();

 

            //画文字

            for (int i = 0; i < 4; i++)

            {

               sKPaint.Color = new SKColor((byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255));

                        canvas.DrawText(charList[i].ToString(), temp + 20 * i, temp1, sKPaint);

           }

            //画干扰线

            for (int i = 0; i < 5; i++)

            {

                sKPaint.Color = new SKColor((byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255));

                        canvas.DrawLine(random.Next(0, 40), random.Next(1, 29), random.Next(41, 80), random.Next(1, 29), sKPaint);

            }

        }

        //页面展示图片

        using (SKImage img = SKImage.FromBitmap(bmp))

        {

            using (SKData p = img.Encode())

            {

                return File(p.ToArray(), "image/Png");

            }

        }

    }

}

 

第3步:运行测试

 在.net core web项目中生成图片验证码

 

相关文章:

  • 2022-01-01
  • 2021-06-26
  • 2021-09-18
  • 2022-12-23
  • 2021-07-04
  • 2022-01-16
猜你喜欢
  • 2021-11-22
  • 2022-12-23
  • 2021-12-26
  • 2018-05-13
  • 2022-12-23
相关资源
相似解决方案