1、创建一个网站,只使用后台生成验证码,并输出图片流跟图片验证码的字符
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Drawing; public partial class YZM : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //一、引用using System.Drawing;类 //二、准备画布 Bitmap img = new Bitmap(60,30); //三、往图片上画验证码 //1、准备绘制类,相当于铺好画布准备绘画 Graphics g = Graphics.FromImage(img); //2、准备绘画的内容与工具 string all = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";//验证内容 Random r = new Random();//实例化随机类 string aa = ""; for(int i=0;i<4;i++) { aa += all.Substring(r.Next(all.Length), 1);//随机截取字符组成验证码 } Session["YZM"] = aa;//验证的数据用session传过去 Font f = new Font("微软雅黑",16);//字体格式 SolidBrush b = new SolidBrush(Color.Green);//准备画刷 //3、绘制验证码 g.DrawString(aa, f, b, 0, 0); //四、输出验证码到页面上 img.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Png);//数据流,输出格式 } }
2、图片验证码需要验证的界面
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PMShtml.aspx.cs" Inherits="PMShtml" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:Image ID="Image1" runat="server" ImageUrl="~/YZM.aspx" /><br /> <asp:Button ID="Button1" runat="server" Text="验证" /><asp:Label ID="Label1" runat="server" Text="" ForeColor="Red"></asp:Label> </div> </form> </body> </html> <script type="text/javascript"> //验证图片的点击事件,点击图片重新换一张图片 var bb = 0; document.getElementById("Image1").onclick = function () { this.setAttribute("src", "yzm.aspx?aa=" + bb ); bb++; } </script>
界面后台
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class PMShtml : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Button1.Click += Button1_Click;//验证按钮事件 } //验证按钮开始 void Button1_Click(object sender, EventArgs e) { if (Session["YZM"] != null) { if (TextBox1.Text == Session["YZM"].ToString()) { Label1.Text = "验证成功!"; } else { Label1.Text = "验证失败!"; } } } //验证按钮结束 }