如何在.NetCore中實現(xiàn)一個圖片驗證碼功能-創(chuàng)新互聯(lián)

本篇文章給大家分享的是有關(guān)如何在.Net Core中實現(xiàn)一個圖片驗證碼功能,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

創(chuàng)新互聯(lián)自2013年起,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務公司,擁有項目網(wǎng)站建設(shè)、做網(wǎng)站網(wǎng)站策劃,項目實施與項目整合能力。我們以讓每一個夢想脫穎而出為使命,1280元德保做網(wǎng)站,已為上家服務,為德保各地企業(yè)和個人服務,聯(lián)系電話:18980820575

第一步:生成隨機數(shù)


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[] { ',' });//拆分成數(shù)組  
      string code = "";//產(chǎn)生的隨機數(shù) 
      int temp = -1;//記錄上次隨機數(shù)值,盡量避避免生產(chǎn)幾個一樣的隨機數(shù) 

      Random rand = new Random();
      //采用一個簡單的算法以保證生成隨機數(shù)的不同 
      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);//獲取隨機數(shù) 
        if (temp != -1 && temp == t)
        {
          return RndNum(VcodeNum);//如果獲取的隨機數(shù)重復,則遞歸調(diào)用 
        }
        temp = t;//把本次產(chǎn)生的隨機數(shù)記錄起來 
        code += VcArray[t];//隨機數(shù)的位數(shù)加一 
      }
      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);//背景設(shè)為白色

          //在隨機位置畫背景點 
          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();//生成內(nèi)存流對象 
          img.Save(ms, ImageFormat.Jpeg);//將此圖像以Png圖像文件的格式保存到流中 
        }
      }

      return ms;
    }

第三步:控制器調(diào)用方法生成隨機數(shù)圖片之后,進行隨機數(shù)的保存

 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


這個百度上的搜索結(jié)果沒有一個是給了可用代碼的。ε=(&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中實現(xiàn)一個圖片驗證碼功能,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學到更多知識。更多詳情敬請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

文章名稱:如何在.NetCore中實現(xiàn)一個圖片驗證碼功能-創(chuàng)新互聯(lián)
新聞來源:http://bm7419.com/article14/hcide.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供云服務器、虛擬主機自適應網(wǎng)站、響應式網(wǎng)站標簽優(yōu)化、網(wǎng)頁設(shè)計公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司