自己动手写验证码

*******************************************处理程序(CheckCode.ashx)***************************/ public class CheckCode : IHttpHandler,System.Web.SessionState.IRequiresSessionState //注意处理程序应用session需要的System.Web.SessionState.IRequiresSessionState接口 {

public void ProcessRequest (HttpContext context) {

context.Response.ContentType = "image/jpeg";

using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(80, 30)) {

using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap)) {

g.DrawString("你好吗",new System.Drawing.Font("宋体",20), System.Drawing.Brushes.Green ,new System.Drawing.PointF(0,0) );

 System.Drawing.Pen pen= (System.Drawing.Pen)System.Drawing.Pens.Red.Clone();

 pen.Width=5;

g.DrawEllipse(pen,new System.Drawing.Rectangle(10,10,10,10)); bitmap.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);//上面是自己手写的图片

Random r = new Random();

int random=r.Next(0,9999);

string code = random.ToString();

HttpContext.Current.Session["code"] = code;//数字验证码

byte[] bytes = new byte[100];

Random randObj = new Random();

int code;

for (int i = 0; i < 4; i++) {

code = randObj.Next(44, 122); bytes[i] = Convert.ToByte(code);

}

System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();

string validateCode = ascii.GetString(bytes, 0, 4);

string strcode= validateCode.ToString();//根据ASCII码随机获取的验证码

g.DrawString(code,new System.Drawing.Font("宋体",20),System.Drawing.Brushes.Green,new System.Drawing.PointF(0,0)); bitmap.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);

}

} }

/*******************************************页面对验证码的应用***************************/

<form id="form1" runat="server"> <div> <img src="CheckCode.ashx" onclick="this.src='CheckCode.ashx?date='+new Date()" />//点击验证码一次回传给ashx一次,刷新一下验证码(注意参数为时间不会一样的) <br />

</div>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="确定" onclick="Button1_Click" />

</form>

protected void Button1_Click(object sender, EventArgs e) {

if (TextBox1.Text == Session["code"].ToString()) { Response.Write("验证通过!"); } else { Response.Write("验证失败!");

}

}

posted @ 2013-01-16 18:35  创业男生  阅读(275)  评论(0编辑  收藏  举报