温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在.Net Core中实现一个图片验证码功能

发布时间:2021-02-08 17:37:05 来源:亿速云 阅读:250 作者:Leah 栏目:开发技术

本篇文章给大家分享的是有关如何在.Net Core中实现一个图片验证码功能,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

第一步:生成随机数

private static string RndNum(int VcodeNum)
    {
      //验证码可以显示的字符集合 
      string Vchar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,p" +
        ",q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,P,Q" +
        ",R,S,T,U,V,W,X,Y,Z";
      string[] VcArray = Vchar.Split(new Char[] { ',' });//拆分成数组  
      string code = "";//产生的随机数 
      int temp = -1;//记录上次随机数值,尽量避避免生产几个一样的随机数 

      Random rand = new Random();
      //采用一个简单的算法以保证生成随机数的不同 
      for (int i = 1; i < VcodeNum + 1; i++)
      {
        if (temp != -1)
        {
          rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));//初始化随机类 
        }
        int t = rand.Next(61);//获取随机数 
        if (temp != -1 && temp == t)
        {
          return RndNum(VcodeNum);//如果获取的随机数重复,则递归调用 
        }
        temp = t;//把本次产生的随机数记录起来 
        code += VcArray[t];//随机数的位数加一 
      }
      return code;
    }

第二步:生成验证码图片

public static MemoryStream Create(out string code, int numbers = 4)
    {
      code = RndNum(numbers);
      //Bitmap img = null;
      //Graphics g = null;
      MemoryStream ms = null;
      Random random = new Random();
      //验证码颜色集合 
      Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };

      //验证码字体集合
      string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };


      using (var img = new Bitmap((int)code.Length * 18, 32))
      {
        using (var g = Graphics.FromImage(img))
        {
          g.Clear(Color.White);//背景设为白色

          //在随机位置画背景点 
          for (int i = 0; i < 100; i++)
          {
            int x = random.Next(img.Width);
            int y = random.Next(img.Height);
            g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
          }
          //验证码绘制在g中 
          for (int i = 0; i < code.Length; i++)
          {
            int cindex = random.Next(7);//随机颜色索引值 
            int findex = random.Next(5);//随机字体索引值 
            Font f = new Font(fonts[findex], 15, FontStyle.Bold);//字体 
            Brush b = new SolidBrush(c[cindex]);//颜色 
            int ii = 4;
            if ((i + 1) % 2 == 0)//控制验证码不在同一高度 
            {
              ii = 2;
            }
            g.DrawString(code.Substring(i, 1), f, b, 3 + (i * 12), ii);//绘制一个验证字符 
          }
          ms = new MemoryStream();//生成内存流对象 
          img.Save(ms, ImageFormat.Jpeg);//将此图像以Png图像文件的格式保存到流中 
        }
      }

      return ms;
    }

第三步:控制器调用方法生成随机数图片之后,进行随机数的保存

 HttpContext.Session.SetString("LoginValidateCode", code);

备注:在使用Session的时候要进行Session服务的注册

在ConfigureServices中services.AddSession();

在Configure中app.UseSession();

最后在前端进行验证码图片的绑定

<img  id="code" src="/Users/Login/GetVerifyCode" />
function GetCode() {
    $.ajax({
      type: "GET",
      url: "/Users/Login/GetVerifyCode",
      data: {},
      dataType: "json",
      success: function (data) {
      },
      complete: function () {
        $("#code").attr('src', '/Users/Login/GetVerifyCode')
      }
    });
  }

SkiaSharp

这个百度上的搜索结果没有一个是给了可用代码的。ε=(&acute;ο`*)))唉 而且大部分都是一个人放出来的代码 好吧开始自己整。先上代码

public IActionResult Code()
    {
      #region 反射SK支持的全部颜色
      //List<SKColor> colors = new List<SKColor>();      
      //var skcolors = new SKColors();
      //var type = skcolors.GetType();
      //foreach (FieldInfo field in type.GetFields())
      //{
      //  colors.Add( (SKColor)field.GetValue(skcolors));
      //}
      #endregion

      //int maxcolorindex = colors.Count-1;
      string text = "1A3V";
      var zu = text.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("微软雅黑", SKTypefaceStyle.Bold);//字体
          SKRect size = new SKRect();
          sKPaint.MeasureText(zu[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(zu[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");
          }
        }
      }
    }

以上就是如何在.Net Core中实现一个图片验证码功能,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI