随机生成验证码

 public class ValidationCodeImageGenerator
    {
        //private string _charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        private string _charset = "1234567890";

        //private string[] _fontNames = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
        private string fontName = "Comic Sans MS";

        Color[] _colorNames = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };

        private string _validationCode = string.Empty;
        public string ValidationCode
        {
            get { return this._validationCode; }
        }

        private const int ValidationCodeLength = 4;
        private const int MinFontSize = 12;
        private const int MaxFontSize = 16;

        private Random random = null;

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        private string GenerateValidationCode()
        {
            string code = String.Empty;
            for (int i = 0; i < ValidationCodeImageGenerator.ValidationCodeLength; i++)
            {
                int idx = random.Next(this._charset.Length);
                code += this._charset[idx].ToString();
            }
            return code;
        }

        private Brush GetBrush()
        {
            Color color = this._colorNames[random.Next(this._colorNames.Length)];
            return new SolidBrush(color);
        }

        /// <summary>
        /// 获取字体
        /// </summary>
        /// <returns></returns>
        private Font GetFont()
        {
            //string fontName = this._fontNames[random.Next(this._fontNames.Length)];
            int size = random.Next(ValidationCodeImageGenerator.MaxFontSize - ValidationCodeImageGenerator.MinFontSize) +
                ValidationCodeImageGenerator.MinFontSize;
            return new Font(fontName, (float)size);
        }

        /// <summary>
        /// 生成图片
        /// </summary>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        public Image GenerateImage(int width, int height)
        {
            Bitmap img = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(img);
            g.Clear(Color.Snow);
           
            ////随机输出噪点
            //for (int i = 0; i < 4; i++)
            //{
            //    int x = random.Next(width);
            //    int y = random.Next(height);
            //    g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
            //}

            int pos = 10;
            for (int i = 0; i < this.ValidationCode.Length; i++)
            {
                string s = this.ValidationCode[i].ToString();
                Font f = this.GetFont();
                g.DrawString(s, f, this.GetBrush(), pos, 0F);
                pos += 20;
            }
            g.DrawRectangle(new Pen(Color.White, 0), 0, 0, width, height);
            g.Save();
            return img;
        }

        public ValidationCodeImageGenerator()
        {
            this.random = new Random();
            this._validationCode = this.GenerateValidationCode();
        }
    }

public class ValidationCode : IHttpHandler, IRequiresSessionState
{
  
    public void ProcessRequest (HttpContext context)
    {
        if (context.Request.UrlReferrer == null)
        {
            context.Response.Redirect("../Login.html");
        }
        else
        {
            ValidationCodeImageGenerator generator = new ValidationCodeImageGenerator();
            Image img = generator.GenerateImage(100, 25);
            CookieManager.ValidCode = generator.ValidationCode;
            CommonAndCalss.SetCookie(CookieManager.validCodeName, generator.ValidationCode);
            MemoryStream ms = new MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            img.Dispose();
            ms.Position = 0;
            context.Response.ContentType = "image/jpeg";
            context.Response.BinaryWrite(ms.ToArray());
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

posted @ 2014-01-15 14:52  silence逢场作戏  阅读(213)  评论(0编辑  收藏  举报