我的c#版通用验证码处理程序

下午没事事情做,整理了下自己的验证码处理程序,代码using System;
using System.Web;
using System.Drawing;
namespace BusLover.Ajax
{
    /// <summary>
    
/// AuthCode 验证码类;
    
/// 作者:冯际成;
    
/// QQ:604756218
    
/// e-mail:caoxiancc@live.cn
    
/// </summary>
    public class AuthCode : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/jpeg";
            context.Response.Buffer = false;
            context.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
            context.Response.Expires = 0;
            context.Response.CacheControl = "no-cache";
            context.Response.AppendHeader("Pragma""No-Cache");
            //字符串长度;
            int len;
            try
            {
                string str=context.Request.QueryString["Len"].ToString();
                len = int.Parse(str);
            }
            catch (Exception ex)
            {
                len = 4;
            }
            //中文;
            int type;
            try
            {
                string str = context.Request.QueryString["Lan"].ToString();
                if (str.ToUpper() == "CN")
                {
                    type = 1;
                }
                else
                {
                    type = 0;
                }
            }
            catch (Exception ex)
            {
                //如果想不通过传递参数直接生成中文验证码,请把此处更改为1;
                type = 0;
            }
            //计算图片高度;
            int height=35;
            //计算图片宽度;
            int with=(type==1)?len*27:len*18;
            using (Bitmap map = new Bitmap(with,height))
            {
                using (Graphics gr=Graphics.FromImage(map))
                {
                    string str = (type == 1) ? GetCnstring(len) : GetString(len);
                    HttpCookie cookie = new HttpCookie("ckkd");
                    cookie.Value = str;
                    cookie.Expires = DateTime.Now.AddMinutes(5);
                    context.Response.Cookies.Add(cookie);
                    //清空白色;
                    gr.Clear(Color.White);
                    Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };//定义随机颜色
                    string[] font = { "Verdana""Microsoft Sans Serif""Comic Sans MS""Arial""宋体" };
                    //画干扰线;
                    Random rand = new Random();
                    for (int i=0; i < 3; i++)
                    {
                        Pen pen = new Pen(c[rand.Next(c.Length)],1);
                        int x1 = rand.Next(0,15);
                        int x2 = rand.Next(map.Width-4,map.Width);
                        int y1 = rand.Next(map.Height);
                        int y2 = rand.Next(map.Height);
                        gr.DrawBezier(pen, x1, y1, x1, y2, x2, y1, x2, y2); 
                    }
                    //画字符;
                    for (int i = 0; i < len; i++)
                    {
                        int x1, y1;
                        if (type == 1)
                        {
                            x1 = rand.Next(i * 27 + 5, i * 27 + 19)-14;
                        }
                        else
                        {
                            x1 = rand.Next(i * 16 + 5, i * 16 + 11);
                        }
                        y1 = rand.Next(5,map.Height-24);
                        Brush b = new System.Drawing.SolidBrush(c[rand.Next(c.Length)]);
                        gr.DrawString(str.Substring(i, 1), new Font(font[rand.Next(font.Length)], 14, FontStyle.Bold), b, new PointF(x1, y1));
                    }
                    //画干燥点;
                    for (int i = 0; i < 100; i++)
                    {
                        int x = rand.Next(map.Width);
                        int y = rand.Next(map.Height);
                        map.SetPixel(x, y, c[rand.Next(c.Length)]);
                    }
                    gr.DrawRectangle(new Pen(Color.Black, 0), 00, map.Width - 1, map.Height - 1);
                    map.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
        }
        /// <summary>
        
/// 获得随机字符串;
        
/// </summary>
        
/// <param name="len">长度</param>
        
/// <returns></returns>
        private string GetString(int len)
        {
            string strArr = "abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ1234560";
            Random rand = new Random();
            string str = string.Empty;
            for (int i = 0; i < len; i++)
            {
                str += strArr[rand.Next(strArr.Length)];
            }
            return str;
        }
        /// <summary>
        
/// 获得中文字符
        
/// </summary>
        
/// <param name="len">长度</param>
        
/// <returns></returns>
        private string GetCnstring(int len)
        {
            System.Text.Encoding gb = System.Text.Encoding.Default;//获取GB2312编码;
            object[] bytes = CreateRegionCode(len);//调用函数产生4个随机中文汉字编码;
            string[] str = new string[len];
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            for (int i = 0; i < len; i++)
            {
                //根据汉字编码的字节数组解码出中文汉字
                str[i] = gb.GetString((byte[])Convert.ChangeType(bytes[i], typeof(byte[])));
                sb.Append(str[i].ToString());
            }
            return sb.ToString();
        }
        private object[] CreateRegionCode(int len)
        { 
            //定义一个字符串数组储存汉字编码的组成元素
            string[] Base = new String[16] { "0""1""2""3""4""5""6""7""8""9""a""b""c""d""e""f" }; 
            Random rnd = new Random();
            object[] bytes = new object[len];
            for (int i = 0; i < len; i++)
            {
                //获得区位码第一位;
                int r1 = rnd.Next(11,14);
                string str1 = Base[r1].Trim();
                //获得区位码第二位;
                rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i);//改变随机数种子;
                int r2 = (r1 == 13) ? rnd.Next(07) : rnd.Next(016);
                string str2 = Base[r2].Trim();
                //获得区位码第三位;
                rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i);
                int r3 = rnd.Next(1016);
                string str3 = Base[r3].Trim();
                //获得区位码第四位;
                rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i);
                int r4;
                if (r3 == 10)
                {
                    r4 = rnd.Next(116);
                }
                else if (r3 == 15)
                {
                    r4 = rnd.Next(015);
                }
                else
                {
                    r4 = rnd.Next(016);
                }
                string str4 = Base[r4].Trim();
                //定义两个字节变量存储产生的随机汉字区位码
                byte byte1 = Convert.ToByte(str1 + str2, 16);
                byte byte2 = Convert.ToByte(str3 + str4, 16);
                //将两个字节变量存储在字节数组中
                byte[] str_r = new byte[] { byte1, byte2 };
                //将产生的一个汉字的字节数组放入object数组中
                bytes.SetValue(str_r, i);
            }
            return bytes;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 

posted @ 2012-04-11 21:06  冯际成  阅读(352)  评论(0)    收藏  举报

返回顶部