ITPub博客

首页 > Linux操作系统 > Linux操作系统 > 验证码 生成 二三例(一般处理程序,封装一个类)

验证码 生成 二三例(一般处理程序,封装一个类)

原创 Linux操作系统 作者:iDotNetSpace 时间:2009-10-22 15:33:40 0 删除 编辑

第一种方法:使用一般处理程序Handler  

第一步:准备工作, 做一张验证码底图图片,放在程序的一个文件夹内,例如app_data内

第二步:添加一般处理程序ImageHandler,继承IHttpHandler,System.Web.SessionState.IRequiresSessionState

第三步:添加处理程序,代码如下


<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Web;
 5
 6namespace AA
 7{
 8   /// 
 9   /// 生成验证码程序
10   /// 

11
12    public class ImageHandler : IHttpHandler,System.Web.SessionState.IRequiresSessionState
13    {
14
15        public void ProcessRequest(HttpContext context)
16        {
17            context.Response.ContentType = "image/jpeg";
18            string path = "~/app_data/code.jpg";
19            string filepath = context.Server.MapPath(path);
20            System.Drawing.Image image = System.Drawing.Image.FromFile(filepath);
21            // 使用随机数生成随机数
22            //System.Random random = new Random();
23            //int code = random.Next(1000, 10000);
24            //string codeString = code.ToString();
25            // 借助 Guid 生成随机验证码
26            System.Guid guid = System.Guid.NewGuid();
27           string codeString = guid.ToString().Substring(0, 4); //截取四位
28           // 使用会话状态
29            context.Session["Code"] = codeString;
30            using (System.Drawing.Graphics g
31            = System.Drawing.Graphics.FromImage(image))
32            {
33                g.DrawString(
34                codeString,
35                new System.Drawing.Font("Arial", 14),
36                System.Drawing.Brushes.Blue,
37                3, 3);
38            }
 //将验证码写到图片上
39            context.Response.ContentType = "image/jpeg";
40            image.Save(
41            context.Response.OutputStream,
42            System.Drawing.Imaging.ImageFormat.Jpeg
43            );
44        }

45
46        public bool IsReusable
47        {
48            get
49            {
50                return false;
51            }

52        }

53    }

54}

第四步:页面添加引用,注意Form必须有runat="server"标记

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><asp:Image ID="Image1" ImageUrl="~/ImageHandler.ashx" runat="server" />

 

第二种方法 使用验证码类,可以自由定义长度,字体等

第一步:定义一个验证码类,封装验证码的各个属性,代码如下


<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->  1using System;
  2using System.Collections.Generic;
  3using System.Linq;
  4using System.Text;
  5using System.Drawing;
  6using System.Web;
  7
  8public class VerifyCode
  9{
 10    #region 验证码长度(默认5个验证码的长度)
 11    int length = 5;
 12    public int Length
 13    {
 14        get { return length; }
 15        set { length = value; }
 16    }

 17    #endregion

 18
 19    #region 验证码字体大小(默认10像素)
 20    int fontSize = 10;
 21    public int FontSize
 22    {
 23        get { return fontSize; }
 24        set { fontSize = value; }
 25    }

 26    #endregion

 27
 28    #region 边框补(默认1像素)
 29    int padding = 1;
 30    public int Padding
 31    {
 32        get { return padding; }
 33        set { padding = value; }
 34    }

 35    #endregion

 36
 37    #region 是否输出燥点(默认不输出)
 38    bool chaos = true;
 39    public bool Chaos
 40    {
 41        get { return chaos; }
 42        set { chaos = value; }
 43    }

 44    #endregion

 45
 46    #region 输出燥点的颜色(默认灰色)
 47    Color chaosColor = Color.LightGray;
 48    public Color ChaosColor
 49    {
 50        get { return chaosColor; }
 51        set { chaosColor = value; }
 52    }

 53    #endregion

 54
 55    #region 自定义背景色(默认白色)
 56    Color backgroundColor = Color.White;
 57    public Color BackgroundColor
 58    {
 59        get { return backgroundColor; }
 60        set { backgroundColor = value; }
 61    }

 62    #endregion

 63
 64    #region 自定义随机颜色数组
 65    Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
 66    public Color[] Colors
 67    {
 68        get { return colors; }
 69        set { colors = value; }
 70    }

 71    #endregion

 72
 73    #region 自定义字体数组
 74    string[] fonts = { "Arial", "Georgia" };
 75    public string[] Fonts
 76    {
 77        get { return fonts; }
 78        set { fonts = value; }
 79    }

 80    #endregion

 81
 82
 83
 84    #region 自定义随机码字符串序列(使用逗号分隔)
 85    string codeSerial = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
 86    public string CodeSerial
 87    {
 88        get { return codeSerial; }
 89        set { codeSerial = value; }
 90    }

 91    #endregion

 92
 93    #region 生成校验码图片
 94    public Bitmap CreateImageCode(string code)
 95    {
 96        int fSize = FontSize;
 97        int fWidth = fSize + Padding;
 98        int imageWidth = (int)(code.Length * fWidth) + 4 + Padding * 2;
 99        int imageHeight = fSize * 2 + Padding;
100        System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth, imageHeight);
101        Graphics g = Graphics.FromImage(image);
102        g.Clear(BackgroundColor);
103        Random rand = new Random();
104        //给背景添加随机生成的燥点
105        if (this.Chaos)
106        {
107            Pen pen = new Pen(ChaosColor, 0);
108            int c = Length * 10;
109            for (int i = 0; i < c; i++)
110            {
111                int x = rand.Next(image.Width);
112                int y = rand.Next(image.Height);
113                g.DrawRectangle(pen, x, y, 1, 1);
114            }

115        }

116        int left = 0, top = 0, top1 = 1, top2 = 1;
117        int n1 = (imageHeight - FontSize - Padding * 2);
118        int n2 = n1 / 4;
119        top1 = n2;
120        top2 = n2 * 2;
121        Font f;
122        Brush b;
123        int cindex, findex;
124        //随机字体和颜色的验证码字符
125        for (int i = 0; i < code.Length; i++)
126        {
127            cindex = rand.Next(Colors.Length - 1);
128            findex = rand.Next(Fonts.Length - 1);
129            f = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);
130            b = new System.Drawing.SolidBrush(Colors[cindex]);
131            if (i % 2 == 1)
132            {
133                top = top2;
134            }

135            else
136            {
137                top = top1;
138            }

139            left = i * fWidth;
140            g.DrawString(code.Substring(i, 1), f, b, left, top);
141        }

142        //画一个边框 边框颜色为Color.Gainsboro 
143        g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);
144        g.Dispose();
145        return image;
146    }

147    #endregion

148
149    #region 将创建好的图片输出到页面
150    public void CreateImageOnPage(string code, HttpContext context)
151    {
152        System.IO.MemoryStream ms = new System.IO.MemoryStream();
153        Bitmap image = this.CreateImageCode(code);
154        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
155        context.Response.ClearContent();
156        context.Response.ContentType = "image/Jpeg";
157        context.Response.BinaryWrite(ms.GetBuffer());
158        ms.Close();
159        ms = null;
160        image.Dispose();
161        image = null;
162    }

163    #endregion

164
165    #region 生成随机字符码
166    public string CreateVerifyCode(int codeLen)
167    {
168        if (codeLen == 0)
169        {
170            codeLen = Length;
171        }

172        string[] arr = CodeSerial.Split(',');
173        string code = "";
174        int randValue = -1;
175        Random rand = new Random(unchecked((int)DateTime.Now.Ticks));
176        for (int i = 0; i < codeLen; i++)
177        {
178            randValue = rand.Next(0, arr.Length - 1);
179            code += arr[randValue];
180        }

181        return code;
182    }

183    public string CreateVerifyCode()
184    {
185        return CreateVerifyCode(0);
186    }

187    #endregion

188}

 

第三步:添加一个验证码页面Code.aspx,添加引用VerifyCode类的程序集,注意命名空间的是否添加了没有

后台代码添加如下:


<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Web;
 5using System.Web.UI;
 6using System.Web.UI.WebControls;
 7using System.Drawing;
 8using VerifyCode类的命名空间;
 9
10public partial class Code: System.Web.UI.Page
11{ 
12    #region 验证码长度(默认5个验证码的长度)
13    int length = 5;
14    #endregion

15
16    #region 验证码字体大小(默认10像素)
17    int fontSize = 12;
18    #endregion

19
20    #region 边框补(默认1像素)
21    int padding = 1; 
22    #endregion

23
24    #region 是否输出燥点(默认输出)
25    bool chaos = true;  
26    #endregion

27
28    #region 输出燥点的颜色(默认灰色)
29    Color chaosColor = System.Drawing.Color.Pink;
30    #endregion
 
31
32    #region 自定义背景色(默认白色)
33    Color backgroundColor = Color.White;
34    #endregion

35
36    #region 自定义随机颜色数组
37    Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
38    #endregion

39
40
41    #region 自定义字体数组
42    string[] fonts = { "Arial", "Georgia" }; 
43    #endregion

44
45    #region 自定义随机码字符串序列(使用逗号分隔)
46    string codeSerial = "1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z";
47    #endregion
 
48
49    protected void Page_Load(object sender, EventArgs e)
50    {
51        VerifyCode v = new VerifyCode();
52        v.Length = this.length;
53        v.FontSize = this.fontSize;
54        v.Chaos = this.chaos;
55        v.BackgroundColor = this.backgroundColor;
56        v.ChaosColor = this.chaosColor;
57        v.CodeSerial = this.codeSerial;
58        v.Colors = this.colors;
59        v.Fonts = this.fonts;
60        v.Padding = this.padding;
61        string code = v.CreateVerifyCode();            //取随机码
62        v.CreateImageOnPage(code, this.Context);       // 输出图片
63        Session["CheckCode"] = code.ToLower();            // 使用Session["CheckCode"]取验证码的值
64        //Response.Cookies.Add(new HttpCookie("CheckCode", code.ToLower()));// 使用Cookies取验证码的值
65    }

66}

67

 

第三步:在验证码引用页面添加代码

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><asp:Image id="Image1" runat="server" ImageUrl="~/Code.aspx">asp:Image>

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/12639172/viewspace-617173/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-01-04

  • 博文量
    2376
  • 访问量
    5766208