Seven blog

天行健,君子以自强不息

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

ASP.NET中实现随机验证码

实现了随机大小写字母的生成,随机躁点,随机顶距,随机字间距,随机角度效果。
代码如下:

 1【生成验证码的核心代码】
 2Random rndNum = new Random();
 3        int intX, intY, intW, intH;
 4
 5        //读取图像
 6        Bitmap img = new Bitmap(8020);
 7
 8        //绘制图形边框
 9        Graphics g = Graphics.FromImage(img);
10        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
11        g.FillRectangle(new SolidBrush(Color.White), new Rectangle(00, img.Width - 1, img.Height - 1));
12
13        //绘制躁点
14        for (int i = 0; i < 30; i++)
15        {
16            intX = rndNum.Next(0, img.Width);
17            intY = rndNum.Next(0, img.Height);
18            intW = rndNum.Next(13);
19            intH = rndNum.Next(13);
20
21            g.DrawEllipse(new Pen(Color.Cyan), intX, intY, intW, intH);
22        }

23       
24
25        g.DrawRectangle(new Pen(Color.DarkCyan), 00, img.Width - 1, img.Height - 1);
26        g.DrawRectangle(new Pen(Color.White), 11, img.Width - 3, img.Height - 3);
27
28        //绘制文字
29        string strValidate = "";
30
31        for (int i = 0; i < 4; i++)
32        {
33            Int32 intChar;
34            intChar = rndNum.Next(6591);
35            if (rndNum.Next(02== 0)
36            {
37                intChar += 32;
38            }

39            strValidate += Convert.ToChar(intChar).ToString();
40        }

41        Session["RandomNumber"= strValidate;
42        string CopyRightString = strValidate;
43        Color CopyRightStringColor = Color.DarkCyan;
44        StringFormat sf = new StringFormat();
45        sf.Alignment = StringAlignment.Center;
46        sf.LineAlignment = StringAlignment.Center;
47       
48        int intNewX = 0;
49        int intNewY = 0;
50        Font fontDrawFont=new Font("宋体"16, FontStyle.Bold, GraphicsUnit.Pixel);
51        for (int i = 0; i < CopyRightString.Length; i++)
52        {
53            intNewY = rndNum.Next(0, img.Height - (int)fontDrawFont.Size);
54            string sTemp = CopyRightString[i].ToString();
55            g.RotateTransform(rndNum.Next(-1,2));
56            g.DrawString(sTemp, fontDrawFont, new SolidBrush(CopyRightStringColor), new RectangleF(intNewX + rndNum.Next(-1,2* img.Width / 16, intNewY, img.Width / 4, (int)fontDrawFont.Size), sf);
57            intNewX += img.Width /4;
58       
59        }

60
61        //显示图像
62        System.IO.MemoryStream ms = new MemoryStream();
63        img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
64        Response.ContentType = "IMAGE/JPEG";
65        Response.BinaryWrite(ms.ToArray());
66
67        //清理资源
68        g.Dispose();
69        img.Dispose();
70
71
72【显示验证码部分】
73<asp:Image ID="img_Validated" runat="server" ImageUrl="RandomNumber.aspx" />
74
75
76
posted on 2007-08-30 14:13  china-seven  阅读(189)  评论(0)    收藏  举报