标签:server ges erb 背景颜色 分享 raw img rip family
做一个图片验证码 界面中的代码
1 验证码:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:Image ID="Image1" ImageUrl="YZM.aspx" runat="server" /> 2 <asp:Button ID="Button1" runat="server" Text="验证" /><asp:Label ID="Label1" runat="server" Text=""></asp:Label> 3
image控件指向YZM.aspx
<asp:Image ID="Image1" ImageUrl="YZM.aspx" runat="server" />
创建YZM.aspx在后台把验证码画出来代码如下
1 //引用 using System.Drawing 命名空间 2 3 // 创建画布 4 Bitmap map = new Bitmap(100, 50); 5 //指定在那个画布上绘制 6 Graphics g = Graphics.FromImage(map); 7 //随机数类 8 Random r = new Random(); 9 //绘制背景色 10 11 //准备好背景颜色放入集合中去 12 List<Color> clist = new List<Color>(); 13 clist.Add(Color.Azure); 14 clist.Add(Color.LightGray); 15 clist.Add(Color.CornflowerBlue); 16 clist.Add(Color.SlateBlue); 17 clist.Add(Color.MediumBlue); 18 clist.Add(Color.SteelBlue); 19 clist.Add(Color.DarkGreen); 20 clist.Add(Color.GreenYellow); 21 clist.Add(Color.SlateBlue); 22 //绘制背景颜色 23 g.FillRectangle(new SolidBrush(clist[r.Next(0, clist.Count)]), 0, 0, 100, 50); 24 25 //绘制干扰线 26 for(int i =0 ;i<10;i++)//循环绘制I条干扰线 27 { 28 //创建 Pen 对象 pen 29 Pen pen= new Pen(new SolidBrush(clist[r.Next(0, clist.Count)]),r.Next(0,10)); 30 //绘制干扰线 31 g.DrawLine(pen, r.Next(0, 100), r.Next(0, 50), r.Next(0, 100), r.Next(0, 50)); 32 } 33 //验证码绘制内容 34 string ss = "ABCDEFHIJKLMNOPQRSTUVWXYZabxdefghijklmnopqrstuvwxyz1234567890"; 35 string s = ""; 36 for (int i = 0; i < 4; i++)//随机出四位验证码 37 { 38 s += ss.Substring((r.Next(0, ss.Length)), 1); 39 } 40 Session["yzm"] = s; 41 //绘制的字体 42 Font f = new Font("黑体", 30); 43 //绘制的画刷 44 Brush b = new SolidBrush(Color.Brown); 45 //开始绘制验证码 46 g.DrawString(s, f, b, 0, 0); 47 48 //保存绘制的验证码 49 //Response.OutputStream输出流 50 //System.Drawing.Imaging.ImageFormat.Jpeg 保存的格式 51 map.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); 52 Response.End();
页面显示
验证验证码方法
//注册验证按钮点击事件 Button1.Click += Button1_Click;
void Button1_Click(object sender, EventArgs e) { string t1 = TextBox1.Text; string t2 = Session["YZM"].ToString(); if (t1.ToUpper() == t2.ToUpper()) { Label1.Text = "验证成功!"; } else { Label1.Text = "验证失败!"; } }
看不清除点击图片更换验证码 用js 方法
<script type="text/javascript"> var a = 0; document.getElementById("Image1").onclick = function () { this.setAttribute("src", "yzm.aspx?id=" + a); a++; } </script>
标签:server ges erb 背景颜色 分享 raw img rip family
原文地址:http://www.cnblogs.com/fuze/p/6370927.html