一、造一个验证码的图片
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.UI; 6 using System.Web.UI.WebControls; 7 using System.Drawing; 8 public partial class YZM : System.Web.UI.Page 9 { 10 protected void Page_Load(object sender, EventArgs e) 11 { 12 //造一个图片 13 Bitmap img = new Bitmap(60, 30); 14 //生成个随机数 15 string str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; 16 Random rand = new Random(); 17 string code = ""; 18 for (int i = 0; i < 4; i++) 19 { 20 int start = rand.Next(str.Length); 21 code += str.Substring(start, 1); 22 } 23 Session["yzm"] = code; 24 //把随机数画到图片上 25 SolidBrush brush = new SolidBrush(Color.White); 26 Font font = new Font("Lucida Sans Unicode", 14); 27 Graphics g = Graphics.FromImage(img); 28 29 //a.把图片背景涂白 30 g.FillRectangle(brush, 0, 0, 60, 30); 31 //b.给画笔换个颜色 32 brush.Color = Color.Red; 33 34 35 g.DrawString(code, font, brush, 0, 0); 36 37 //把图片保存到输出流中去 38 img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); 39 40 Response.End(); 41 } 42 }
二、建立一个验证的界面并实现
需要控件textbox,image,button
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.UI; 6 using System.Web.UI.WebControls; 7 8 public partial class Default5 : System.Web.UI.Page 9 { 10 protected void Page_Load(object sender, EventArgs e) 11 { 12 13 } 14 protected void Button1_Click(object sender, EventArgs e) 15 { 16 if (Session["yzm"].ToString() == TextBox1.Text) 17 { 18 19 } 20 } 21 }
1 <script language="javascript"> 2 function changePIC() { 3 var img = document.getElementById("Image1"); 4 img.setAttribute("src","yzm.aspx?id="+Math.random()); 5 } 6 </script>