这是一个包含两个数字,两个小写字母,两个大写字母并包含一些噪音线和噪音点的简单验证码的例子。- /// <summary>
- /// 生成验证码字符串
- /// </summary>
- /// <returns>验证码</returns>
- private string GenerateCode()
- {
- int number;
- string result = "";
- char[] code = new char[6];
- Random random = new Random();
- //通过这个for循环, 获取两个数字,两个小写字母和两个大写字符,并按顺序存到code数组中
- for (int i = 0; i < 6; i++)
- {
- number = random.Next();
- switch (i)
- {
- case 0:
- case 1:
- code[i] = (char)('0' + (char)(number % 10));
- break;
- case 2:
- case 3:
- code[i] = (char)('a' + (char)(number % 26));
- break;
- case 4:
- case 5:
- code[i] = (char)('A' + (char)(number % 26));
- break;
- }
- }
- //通过这个for循环,打乱验证码的顺序
- for (int i = 0; i < 6; i++)
- {
- number = random.Next() % 6;
- char k;
- k = code[i];
- code[i] = code[number];
- code[number] = k;
- }
- //这里不能直接code.ToString(), code.ToString()的结果为System.Char[]
- foreach (char Ch in code)
- {
- result += Ch;
- }
- string security = result.ToLower();
- return result;
- }
- /// <summary>
- /// 将验证码输出为图片,并添加一些噪音线和噪音点
- /// </summary>
- /// <param name="code">验证码</param>
- private void DrawSecurityImage(string code)
- {
- if (code == null || code.Trim() == "")
- {
- return;
- }
- Bitmap image = new Bitmap((int)Math.Ceiling(code.Length * 12.5), 22);
- Graphics g = Graphics.FromImage(image);
- try
- {
- Random random = new Random();
- g.Clear(Color.White);
- for (int i = 0; i < 5; i++)
- {
- int x1 = random.Next(image.Width);
- int x2 = random.Next(image.Width);
- int y1 = random.Next(image.Height);
- int y2 = random.Next(image.Height);
- g.DrawLine(new Pen(Color.Blue), x1, x2, y1, y2);
- }
- Font font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic);
- System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Black, Color.DarkRed, 1.2f, true);
- g.DrawString(code, font, brush, 2, 2);
- for (int i = 0; i < 99; i++)
- {
- int x = random.Next(image.Width);
- int y = random.Next(image.Height);
- image.SetPixel(x, y, Color.FromArgb(random.Next()));
- }
- g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
- System.IO.MemoryStream ms = new System.IO.MemoryStream();
- image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
- Response.ClearContent();
- Response.ContentType = "image/Gif";
- Response.BinaryWrite(ms.ToArray());
- }
- catch (Exception) { }
- finally
- {
- g.Dispose();
- image.Dispose();
- }
- }
复制代码 |