验证码实现方法

来源:互联网 发布:源代码公开的软件 编辑:程序博客网 时间:2024/06/06 13:14
  protected void Page_Load(object sender, EventArgs e)    {         string checkCode = CreateRandomCode(4);          Session["CheckCode"] = checkCode;          CreateImage(checkCode);    }     private string CreateRandomCode(int codeCount)    {        // 函数功能:产生数字和字符混合的随机字符串        string allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";        char[] allCharArray = allChar.ToCharArray();        string randomCode = "";        Random rand = new Random();        for (int i = 0; i < codeCount; i++)        {           int r=rand.Next(61);           randomCode+=allCharArray.GetValue(r);        }         return randomCode;             }             private void CreateImage(string checkCode)    {        // 生成图象验证码函数       int iwidth = (int)(checkCode.Length * 11.5);        System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);        Graphics g = Graphics.FromImage(image);        Font f = new System.Drawing.Font("Arial", 10, System.Drawing.FontStyle.Bold);        Brush b = new System.Drawing.SolidBrush(Color.Azure);//字母白色        //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);        g.Clear(Color.Brown);//背景灰色        g.DrawString(checkCode, f, b, 3, 3);        Pen blackPen = new Pen(Color.Black, 0);        Random rand = new Random();        System.IO.MemoryStream ms = new System.IO.MemoryStream();        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);        Response.ClearContent();        Response.ContentType = "image/Jpeg";        Response.BinaryWrite(ms.ToArray());        g.Dispose();        image.Dispose();    }


0 0
原创粉丝点击