asp.net 验证码

 private void GenerateCheckCodeImage()
        {
            // generate random 4 digit check code 
            string checkCode = (new object()).GetHashCode().ToString().Substring(0, 4);

            Bitmap image = new Bitmap(60, 22);
            Graphics g = Graphics.FromImage(image);
            Brush brush = new SolidBrush(Color.Black);
            Pen pen = new Pen(brush);

            try
            {
                g.Clear(Color.White);

                // draw check code 
                g.DrawString(checkCode, new Font("Arial", 14, FontStyle.Bold, GraphicsUnit.Pixel), brush, new PointF(8, 4));

                // draw lines
                Random random = new Random();
                brush = new SolidBrush(Color.Silver);
                pen = new Pen(brush);

                for (int i = 0; i < 4; i++)
                {
                    int x1 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int x2 = random.Next(image.Width);
                    int y2 = random.Next(image.Height);

                    g.DrawLine(pen, new Point(x1, y1), new Point(x2, y2));
                }

                brush = new SolidBrush(Color.Gray);
                pen = new Pen(brush, 1);

                // draw border 
                g.DrawRectangle(pen, 0, 0, image.Width - 2, image.Height - 2);

                MemoryStream ms = new MemoryStream();
                image.Save(ms, ImageFormat.Png);

                Response.Clear();
                Response.ContentType = "image/png";
                Response.BinaryWrite(ms.ToArray());

                // use sesssion to save and validate.
                Session["checkCode"] = checkCode;
            }
            finally
            {
                brush.Dispose();
                pen.Dispose();
                image.Dispose();
                g.Dispose();
            }
        }

 

posted @ 2014-02-21 15:44  记忆的森林  阅读(146)  评论(0)    收藏  举报