登录实现校验验证码
1、思路:首先写一个生成验证码的接口,接口传出就是验证码的唯一id和验证码图片的base64, 把验证码的id当做缓存的key,再把生成的验证码code当做值存到缓存中。
2、登录:输入用户名、密码、验证码唯一id和用户输入的验证码值。用验证码唯一id获取到缓存中的验证码值,再和用户输入的值相比较。。就简单实现了
3、验证码生成代码
1 public class VerifyCodeHelper 2 { 3 public static string BuildCode(out string code) 4 { 5 code = string.Empty; 6 Random rand = new Random(); 7 Bitmap bitmap = new Bitmap(85, 30);//设置宽高 8 Graphics graphics = Graphics.FromImage(bitmap);//生成画布 9 graphics.Clear(Color.White);//清空画布 10 11 string letters = "023456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";//去除 1 I l 12 Random random = new Random(); 13 //生成四位验证码 14 for (int i = 0; i < 4; i++) 15 { 16 code += letters[random.Next(0, letters.Length)]; 17 } 18 19 //画5条干扰线 20 for (int i = 0; i < 5; i++) 21 { 22 int x1 = random.Next(bitmap.Width); 23 int y1 = random.Next(bitmap.Height); 24 int x2 = random.Next(bitmap.Width); 25 int y2 = random.Next(bitmap.Height); 26 graphics.DrawLine(new Pen(Color.Coral), x1, y1, x2, y2); 27 } 28 //画150个干扰点 29 for (int i = 0; i < 150; i++) 30 { 31 int x1 = random.Next(bitmap.Width); 32 int y1 = random.Next(bitmap.Height); 33 bitmap.SetPixel(x1, y1, Color.FromArgb(random.Next()));//随机颜色填充 34 } 35 //画个边框 36 graphics.DrawRectangle(new Pen(Color.Black), new Rectangle(0, 0, bitmap.Width - 1, bitmap.Height - 1)); 37 38 int randAngle = 45;//随机转动角度 //验证码旋转,防止机器识别 39 char[] chars = code.ToCharArray();//拆散字符串成单字符数组 40 //文字居中 41 StringFormat format = new StringFormat(StringFormatFlags.NoClip); 42 format.Alignment = StringAlignment.Center; 43 format.LineAlignment = StringAlignment.Center; 44 //定义颜色 45 Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple }; 46 //定义字体 47 string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" }; 48 for (int i = 0; i < chars.Length; i++) 49 { 50 int cindex = rand.Next(7); 51 int findex = rand.Next(5); 52 //字体样式(参数2为字体大小) 53 Font f = new System.Drawing.Font(font[findex], 13, System.Drawing.FontStyle.Bold); 54 Brush b = new System.Drawing.SolidBrush(c[cindex]); 55 Point dot = new Point(16, 16); 56 57 float angle = rand.Next(-randAngle, randAngle);//转动的度数 58 graphics.TranslateTransform(dot.X, dot.Y);//移动光标到指定位置 59 graphics.RotateTransform(angle); 60 graphics.DrawString(chars[i].ToString(), f, b, 1, 1, format); 61 62 graphics.RotateTransform(-angle);//转回去 63 graphics.TranslateTransform(2, -dot.Y);//移动光标到指定位置 64 } 65 string strbaser64 = string.Empty; 66 using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) 67 { 68 bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); 69 byte[] arr = new byte[stream.Length]; 70 stream.Position = 0; 71 stream.Read(arr, 0, (int)stream.Length); 72 strbaser64 = Convert.ToBase64String(arr); 73 } 74 return strbaser64; 75 } 76 }
标签:C#,验证码,bitmap,int,Color,new,校验,Next From: https://www.cnblogs.com/heidashuaiGo/p/17661878.html