在yzm.aspx页面中:
Bitmap img = new Bitmap(100, 50); Graphics g = Graphics.FromImage(img); 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); //验证码内容 Random r = new Random(); string ss = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; string s = ""; Color bkcolor = clist[r.Next(0, clist.Count)]; clist.Remove(bkcolor); g.FillRectangle(new SolidBrush(bkcolor), 0, 0, 100, 50); for (int i = 0; i < 4; i++) { s += ss[r.Next(0, ss.Length)]; } Font f = new Font("微软雅黑", 20); Brush b = new SolidBrush(clist[r.Next(0, clist.Count)]); g.DrawString(s, f, b, 5, 5); Session["YZM"] = s; for (var i = 0; i < 5; i++) { Pen pp = new Pen(new SolidBrush(clist[r.Next(0, clist.Count)]), r.Next(1, 3)); Point p1 = new Point(r.Next(0, 100), r.Next(0, 50)); Point p2 = new Point(r.Next(0, 100), r.Next(0, 50)); g.DrawLine(pp, p1, p2); } img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
在另一个aspx页面中:
<img id="yzm" src="YZM.aspx" />
JS端点击更换图片:
a = 0; document.getElementById("yzm").onclick = function () { a++; this.src = "YZM.aspx?a="+a; }
验证验证码正误时,用session:
if (TextBox1.Text.ToUpper() == Session["YZM"].ToString().ToUpper()) 正确 else 错误