Implementation example of picture captcha implemented by. Net core

Time:2020-9-9

Record their own learning, refer to the technology of the big guys on the Internet, often need to use the verification code to carry out a simple verification when logging in. Here we use the. Net core to generate image QR code

The idea is very simple = “generate a random number -” save to the server session – “generate the image corresponding to the random code to the front-end -” check when logging in (you can also encrypt the random code token in the back-end and store it in cooick for verification in the front-end)

Step 1: generate random numbers

private static string RndNum(int VcodeNum)
    {
      //The set of characters that captcha can display 
      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 [] {','}); // split into arrays  
      String code = "; // generated random number 
      Int temp = - 1; // record the last random value and try to avoid producing several identical random numbers 

      Random rand = new Random();
      //A simple algorithm is used to ensure the difference of generating random numbers 
      for (int i = 1; i < VcodeNum + 1; i++)
      {
        if (temp != -1)
        {
          rand = new Random(i * temp * unchecked((int) DateTime.Now.Ticks )); // initialize random class 
        }
        int t =  rand.Next (61); // get random number 
        if (temp != -1 && temp == t)
        {
          Return rndnum (vcodenum); // if the random number obtained is repeated, it will be called recursively 
        }
        Temp = t; // record the random number generated this time 
        Code + = vcarray [t]; // the number of digits of random number plus one 
      }
      return code;
    }

Step 2: generate captcha image

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();
      //Captcha color set 
      Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };

      //Captcha font collection
      String [] fonts = {Verdana "," Microsoft sans serif "," Comic Sans MS "," Arial "," Tahoma "};


      using (var img = new Bitmap((int)code.Length * 18, 32))
      {
        using (var g = Graphics.FromImage(img))
        {
          g.Clear( Color.White ); // the background is set to white

          //Draw background points at random locations 
          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);
          }
          //Captcha is drawn in G 
          for (int i = 0; i < code.Length; i++)
          {
            int cindex =  random.Next (7) ; // random color index value 
            int findex =  random.Next (5) ; // random font index value 
            Font f = new Font(fonts[findex], 15,  FontStyle.Bold ); // font 
            Brush B = new solidbrush (C [cindex]); // color 
            int ii = 4;
            If ((I + 1)% 2 = = 0) // the control captcha is not at the same height 
            {
              ii = 2;
            }
            g.DrawString( code.Substring (I, 1), F, B, 3 + (I * 12), II); // draw a verification character 
          }
          Ms = new memorystream(); // generate memory stream object 
          img.Save (ms,  ImageFormat.Jpeg ); // save this image to the stream in the format of PNG image file 
        }
      }

      return ms;
    }

Step 3: after the controller calls the method to generate the random number picture, the random number is saved


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

Note: when using session, register the session service

In configureservices services.AddSession ();

In configure app.UseSession ();

Finally, the captcha image is bound in the front end


<img style="justify-content:center" src="/Users/Login/GetVerifyCode" />

Click the picture to refresh the verification code


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

SkiaSharp

None of the search results on Baidu are given the available code. (ε = (‘ο ‘*))) well, most of the code is released by one person. OK, start doing it yourself. Code first

public IActionResult Code()
    {
      #Region reflects all colors supported by 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))
      {
        //Background color
        canvas.DrawColor(SKColors.White);
        
        using (SKPaint sKPaint = new SKPaint())
        {         
          sKPaint.TextSize  =16; // font size
          sKPaint.IsAntialias  =True; // enable anti aliasing          
          sKPaint.Typeface  = SKTypeface.FromFamilyName (Microsoft YaHei), SKTypefaceStyle.Bold ); // font
          SKRect size = new SKRect();
          sKPaint.MeasureText (Zu [0]. Tostring(), ref size); // calculates the text width and height
          
          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, sktain); // draw text
          }   
          //Interference line
          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);
          }
        }       
        //Page display picture
        using (SKImage img = SKImage.FromBitmap(bmp))
        {
          using (SKData p = img.Encode())
          {
            return File(p.ToArray(), "image/Png");
          }
        }
      }
    }

This article on the implementation of. Net core image captcha implementation examples to introduce this, more related. Net core image captcha content please search the previous articles or continue to browse the related articles below, I hope you can support developeppaer more in the future!

source: https://www.cnblogs.com/net-open/