asp.net webform代码生成验证码


      

新增建一个页面Page,后台代码如下

public partial class CheckCode : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string data = "0123456789" +
                "abcdefghijklmnopqrstuvwxyz" +
                "abcdefghijklmnopqrstuvwxyz".ToUpper();

            Random random = new Random((int)DateTime.Now.Ticks);
            StringBuilder sData = new StringBuilder();
            Bitmap bitmap = new Bitmap(130, 48);
            Graphics g = Graphics.FromImage(bitmap);
            Font font = new Font("宋体", 20,FontStyle.Bold);
            int x = 10;
            string[] colors = Enum.GetNames(typeof(KnownColor));
            for (int i = 0; i < 5; i++)
            {
                int p = random.Next(1, data.Length);
                int pc = new Random((int)DateTime.Now.Ticks).Next(0, colors.Length - 1);
                Thread.Sleep(10);
                string color = colors[pc];
                var brush = new SolidBrush( Color.FromName(color));
                sData.Append(data[p - 1].ToString());
                g.DrawString(data[p - 1].ToString(), font, brush, x, 10);
                x += 20;
            }

            g.Flush();
            bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
            Session["YZM"] = sData.ToString();
            Response.End();
            
        }
    }

效果图如下: