生成验证码

引命名空间using System.Drawing; 

在yzm.aspx页面中:

        Bitmap img = new Bitmap(200, 160);
        Graphics g = Graphics.FromImage(img);
        string y = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        string yzm = "";
        Random r = new Random();
        List<Color> clist = new List<Color>();
        clist.Add(Color.Red);
        clist.Add(Color.Yellow);
        clist.Add(Color.Blue);
        clist.Add(Color.Green);
        clist.Add(Color.Aqua);
        clist.Add(Color.Orange);
        clist.Add(Color.Pink);

        for (int x = 0; x < 4; x++)
        {
            yzm += y[r.Next(0, y.Length)];
        }
        Session["yzm"] = yzm;
        Font f = new Font("微软雅黑", 25);
        Brush b = new SolidBrush(clist[r.Next(0,clist.Count)]);
        Point p = new Point(50, 50);
        g.DrawString(yzm, f, b, p);

        for(int x = 0; x < 4; x++)
        {
            Pen pe = new Pen(new SolidBrush(clist[r.Next(0, clist.Count)]), r.Next(1, 3));
            Point p1 = new Point(r.Next(0, 200), r.Next(0, 160));
            Point p2 = new Point(r.Next(0, 200), r.Next(0, 160));
            g.DrawLine(pe, p1, p2);
        }

        img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);

在另一个aspx页面中:

<img id="yzm" src="YZM.aspx" />

点击图片更换验证码:

a = 0;
document.getElementById("yzm").onclick = function () {
  a++;
  this.src = "YZM.aspx?a="+a;
}

 验证验证码正误时,用session:

if (TextBox1.Text.ToUpper() == Session["YZM"].ToString().ToUpper()) 正确
else  错误
原文地址:https://www.cnblogs.com/m110/p/8283606.html