首页 > 代码库 > 验证码-WebVcode

验证码-WebVcode

验证码的实现

 

<img src=http://www.mamicode.com/"../Common/WebVcode.aspx" title="看不清?点此更换" alt="看不清?点此更换" onclick="this.src=http://www.mamicode.com/‘/Common/WebVcode.aspx?a=‘+Math.random();" />         protected void Page_Load(object sender, EventArgs e)        {            if (!IsPostBack)            {                Session["Vcode"] = CreateImage(5, VerificationType.Numeric);            }        }        /// <summary>        /// 验证码的类型        /// </summary>        public enum VerificationType        {            /// <summary>            /// 只有数字            /// </summary>            Numeric,            /// <summary>            /// 数字和英文字符            /// </summary>            NumericAndChar,            /// <summary>            /// 中文字符            /// </summary>            ChineseChar        }        /// <summary>        /// 生成一个随机文字图片,保存在 Session["code1"]        /// </summary>        /// <param name="count">图片中字的个数</param>        /// <returns>生成的文字</returns>        public string CreateImage(int count, VerificationType type)        {            string ValidCode = GenCode(count, type);            switch (type)            {                case VerificationType.Numeric:                    CreateCheckCodeImage(ValidCode, 13.5);                    break;                case VerificationType.NumericAndChar:                    CreateCheckCodeImage(ValidCode, 14);                    break;                case VerificationType.ChineseChar:                    CreateCheckCodeImage(ValidCode, 22.5);                    break;                default:                    break;            }            return ValidCode;        }        /// <summary>        /// 产生随机字符串        /// </summary>        /// <param name="num">随机出几个字符</param>        /// <returns>随机出的字符串</returns>        private string GenCode(int num, VerificationType type)        {            string str = string.Empty;            switch (type)            {                case VerificationType.Numeric:                    str = "0123456789";                    break;                case VerificationType.NumericAndChar:                    str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";                    break;                case VerificationType.ChineseChar:                    break;                default:                    str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";                    break;            }            char[] chastr = str.ToCharArray();            string code = "";            Random rd = new Random();            int i;            for (i = 0; i < num; i++)            {                code += str.Substring(rd.Next(0, str.Length), 1);            }            return code;        }        /// <summary>        /// 生成图片(增加背景噪音线、前景噪音点)        /// </summary>        /// <param name="checkCode">随机出字符串</param>        private void CreateCheckCodeImage(string checkCode, double codeWidth)        {            if (checkCode.Trim() == "" || checkCode == null)                return;            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)(checkCode.Length * codeWidth), 22);            Graphics g = Graphics.FromImage(image);            try            {                //生成随机生成器                Random random = new Random();                //清空图片背景色                g.Clear(Color.White);                //画图片的背景噪音线                int i;                for (i = 0; i < 25; 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.Silver), x1, y1, x2, y2);                }                Font font = new System.Drawing.Font("Verdana", 12, (System.Drawing.FontStyle.Bold));                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2F, true);                g.DrawString(checkCode, font, brush, 2, 2, new System.Drawing.StringFormat());                //画图片的前景噪音点                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.Jpeg);                HttpContext.Current.Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);                //清除该页输出缓存,设置该页无缓存                Response.Buffer = true;                Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);                Response.Expires = 0;                Response.CacheControl = "no-cache";                Response.AppendHeader("Pragma", "No-Cache");                HttpContext.Current.Response.ClearContent();                HttpContext.Current.Response.ContentType = "image/JPEG";                HttpContext.Current.Response.BinaryWrite(ms.ToArray());                g.Dispose();                image.Dispose();            }            catch            {                g.Dispose();                image.Dispose();            }        }