`
无恨星晨
  • 浏览: 31203 次
  • 性别: Icon_minigender_1
  • 来自: 石家庄
文章分类
社区版块
存档分类
最新评论

彩色验证码

阅读更多
1   protected void Page_Load(object sender, EventArgs e)
2     {
3         Bitmap bitmap = CreateBitmap(GetRandomDigit(2)+GetRandomNumbers(2));
4         bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
5         bitmap.Dispose();
6     }
7     #region 数字验证
8     public string GetRandomDigit(int len)
9     {
10         string str = "1234567890";
11         string strResult = "";
12         Random random = new Random(unchecked((int)DateTime.Now.Ticks));
13         for (int i = 0; i < len; i++)
14         {
15             strResult +=str[random.Next(0,10)].ToString();
16         }
17         return strResult;
18     }
19     #endregion
20
21
22     #region 字母验证
23     public string GetRandomNumbers(int len)
24     {
25         string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
26         String strResult = "";
27         Random random = new Random();
28         for (int i = 0; i < len; i++)
29         {
30             strResult += str[random.Next(0, 10)].ToString();
31         }
32         return strResult;
33     }
34
35     #endregion
36
37
38     public Bitmap CreateBitmap(string check)
39     {
40         int width = (int)(check.Length * 12);
41         Bitmap bitmap = new Bitmap(width, 20);
42         Graphics graphics = Graphics.FromImage(bitmap);
43         graphics.Clear(Color.White);
44         Color[] c ={ Color.Black,Color.Red, Color.DarkBlue, Color.Green, Color.Brown, Color.DarkCyan,Color.Purple};
45         string[] font = { "Verdana","Microsoft Sans Serif","Comic Sans MS","Arial","宋体"};
46         Random random = new Random();
47         for (int i = 0; i < 30; i++)
48         {
49             int x1 = random.Next(bitmap.Width);
50             int x2 = random.Next(bitmap.Width);
51             int y1 = random.Next(bitmap.Height);
52             int y2 = random.Next(bitmap.Height);
53             graphics.DrawLine(new Pen(Color.LightGray, 1), new Point(x1, y1), new Point(x2, y2));
54
55         }
56         for (int i = 0; i < check.Length; i++)
57         {
58             int cIndex = random.Next(c.Length-1);
59             int fIndex = random.Next(font.Length);
60             Font f = new Font(font[fIndex].ToString(),10,  FontStyle.Regular);
61             Brush b = new SolidBrush(c[cIndex]);
62             int ii = 4;
63             if ((i +1)% 2 == 0)
64             {
65                 ii = 2;
66             }
67             graphics.DrawString(check.Substring(i, 1), f, b, new PointF(3 + (i * 12 ), ii));
68         }
69         graphics.Flush();
70       
71         return bitmap;
72     }



前台: <img src="Default.aspx" onclick="this.src=this.src+'?'" alt="验证码" />
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics