首页 > 代码库 > C# 登录验证码

C# 登录验证码

      基于字符的图片验证码是系统在用户访问页面时随机产生的一个图像,图像中包含数字、字母或其他文字。其中字符序列与背景图像进行信息融合,添加干扰噪声,或对图像进行混杂、扭曲、粘连、变形等处理,以增加图像识别的难度。

      图片验证码的生成主要分成两个步骤:

1、生成随机字符串;

2、生成验证码图片。

  1     public partial class CheckCodeImageExt : System.Web.UI.Page  2     {  3         protected void Page_Load(object sender, EventArgs e)  4         {  5             CreateCheckCodeImage(GenarateCheckCode());  6         }  7   8         private string GenarateCheckCode()  9         { 10             int number; 11             char code; 12             string CheckCode = string.Empty; 13  14             System.Random random = new Random(); 15             // 验证码由 5 个字符组成 16             for (int i = 0; i < 5; i++) 17             { 18                 number = random.Next(); 19                 if (number % 2 == 0) 20                     code = (char)(0 + (char)(number % 10)); 21                 else 22                     code = (char)(A + (char)(number % 26)); 23                 CheckCode += code.ToString(); 24             } 25             // 把生成的验证码存入session 26             Session["CheckCode"] = CheckCode; 27             return CheckCode; 28         } 29          30         /// <summary> 31         /// 生成验证码图片,并输出 32         /// </summary> 33         /// <param name="checkCode"></param> 34         private void CreateCheckCodeImage(string checkCode) 35         { 36             if (checkCode == null || checkCode.Trim() == String.Empty) return; 37             // 定义几何变换 38             Matrix m = new Matrix(); 39             // 图片前景色,即生成背景透明的随机字符串图片 40             Bitmap charbmp = new Bitmap(90, 30);             41             // 定义字体 42             Font[] fonts =  43             {                                44                 new Font(new FontFamily("Times New Roman"), 17, FontStyle.Regular), 45                 new Font(new FontFamily("Georgia"), 17, FontStyle.Regular), 46                 new Font(new FontFamily("Arial"), 17, FontStyle.Regular), 47                 new Font(new FontFamily("Comic Sans MS"), 17, FontStyle.Regular) 48             }; 49  50             // 定义图片背景色 51             System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 22.5)), 30); 52  53             // 开始描绘 54             Graphics g = Graphics.FromImage(image); 55             g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed; 56  57             // 定义背景色为白色 58             g.Clear(Color.White); 59  60             try 61             { 62                 Random random = new Random();       // 生成随机生成器 63                 g.Clear(Color.White);               // 清空图片背景色 64  65                 // 画图片的背景噪音线,i表示画多少条噪音线 66                 for (int i = 0; i < 2; i++)               67                 { 68                     int x1 = random.Next(image.Width); 69                     int x2 = random.Next(image.Width); 70                     int y1 = random.Next(image.Height); 71                     int y2 = random.Next(image.Height); 72  73                     g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2); 74                 } 75                 // 开始描绘前景图 76                 Graphics charg = Graphics.FromImage(charbmp); 77                 SolidBrush drawBrush = new SolidBrush(Color.FromArgb(random.Next(101), random.Next(101), random.Next(101))); 78                 float charx = -18; 79                  80                 // 把随机字符串,逐个写入前景图 81                 for (int i = 0; i < checkCode.Length; i++) 82                 { 83                     m.Reset(); 84                     m.RotateAt(random.Next(31) - 25, new PointF(random.Next(4) + 7, random.Next(4) + 7)); 85  86                     charg.Clear(Color.Transparent);//定义前景图为透明 87                     charg.Transform = m; 88  89                     // 定义前景色为黑色 90                     drawBrush.Color = Color.Black; 91                     charx = charx + 20 + random.Next(3); 92  93                     PointF drawPoint = new PointF(charx, 0.1F); 94                     // 通过特定的几何变换,旋转或变形随机字符,写入前景图 95                     charg.DrawString(checkCode[i].ToString(), fonts[random.Next(fonts.Length)], drawBrush, new PointF(0, 0)); 96                     charg.ResetTransform(); 97                     g.DrawImage(charbmp, drawPoint); 98                 } 99                 // 画图片的前景噪音点100                 for (int i = 0; i < 25; i++)101                 {102                     int x = random.Next(image.Width);103                     int y = random.Next(image.Height);104                     image.SetPixel(x, y, Color.FromArgb(random.Next()));105                 }106                 // 画图片的边框线107                 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);108                 // 输出109                 System.IO.MemoryStream ms = new System.IO.MemoryStream();110                 image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);111                 Response.ClearContent();112                 Response.ContentType = "image/Gif";113                 Response.BinaryWrite(ms.ToArray());114             }115             finally116             {117                 g.Dispose();118                 image.Dispose();119             }120         }121         /*122         private void CreateCheckCodeImage(string checkCode)123         {124             if (checkCode == null || checkCode.Trim() == string.Empty)125                 return;126 127             System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling(checkCode.Length * 12.5), 24);//宽度,高度128             Graphics g = Graphics.FromImage(image);129 130             try131             {132                 Random random = new Random();133                 //清空图片背景色,并用白色填充134                 g.Clear(Color.White);135                 //画图片的背景噪音线136                 for (int i = 0; i < 25; i++)137                 {138                     int x1 = random.Next(image.Width);139                     int x2 = random.Next(image.Width);140                     int y1 = random.Next(image.Height);141                     int y2 = random.Next(image.Height);142 143                     g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);144                 }145 146                 Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));147                 System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);148                 g.DrawString(checkCode, font, brush, 2, 2);149 150 151                 //画图片的前景噪音点152                 for (int i = 0; i < 100; i++)153                 {154                     int x = random.Next(image.Width);155                     int y = random.Next(image.Height);156 157                     image.SetPixel(x, y, Color.FromArgb(random.Next()));158                 }159                 //画图片的边框线160                 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);161                 System.IO.MemoryStream ms = new System.IO.MemoryStream();162                 image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);163                 Response.ClearContent();164                 Response.ContentType = "image/Gif";165                 Response.BinaryWrite(ms.ToArray());166             }167             catch168             {169                 g.Dispose();170                 image.Dispose();171             }172         }*/173     }
View Code

在登录页面的登录按钮的处理事件中使用以下代码判断验证码: 

 1         private void btnLogin_Click(object sender, System.Web.UI.ImageClickEventArgs e)  2         {  3             if(Request.Cookies["CheckCode"] == null)  4             {  5                 lblMessage.Text = "您的浏览器设置已被禁用 Cookies,您必须设置浏览器允许使用 Cookies 选项后才能使用本系统。";  6                 lblMessage.Visible = true;  7                 return;  8             }   9             if(String.Compare(Request.Cookies["CheckCode"].Value, txtCheckCode.Text, true) != 0) 10             { 11                 lblMessage.Text = "验证码错误,请输入正确的验证码。"; 12                 lblMessage.Visible = true; 13                 return; 14             } 15         }
View Code