新建一般处理程序:veify.ashx
<%@ WebHandler Language="C#" Class="verify" %> using System;
using System.Web; using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging; public class verify : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{ public void ProcessRequest(HttpContext context)
{
Code gif = new Code();//初始化验证码生成类
string valid = "";//定义随机数
MemoryStream ms = gif.Create(out valid);//获取包括验证码图片的内存流
context.Session["gif"] = valid;//验证码存储在Session中,供验证。
context.Response.ClearContent();//清空输出流
context.Response.ContentType = "image/png";//输出流的格式
context.Response.BinaryWrite(ms.ToArray());//输出
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
} } public class Code
{
/// <summary>
/// 该方法用于生成指定位数的随机数
/// </summary>
/// <param name="VcodeNum">参数是随机数的位数</param>
/// <returns>返回一个随机数字符串</returns>
private string RndNum(int VcodeNum)
{
//验证码可以显示的字符集合
//string Vchar = "1,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,p,p" +
// ",q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,P,Q" +
// ",R,S,T,U,V,W,X,Y,Z";
string Vchar = "1,2,3,4,5,6,7,8,9";//=================================================这里使用纯数字
string[] VcArray = Vchar.Split(new Char[] { ',' });//拆分成数组
string VNum = "";//产生的随机数
int temp = -;//记录上次随机数值,尽量避避免生产几个一样的随机数 Random rand = new Random();
//采用一个简单的算法以保证生成随机数的不同
for (int i = ; i < VcodeNum + ; i++)
{
if (temp != -)
{
rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));//初始化随机类
}
//int t = rand.Next(61);//获取随机数
int t = rand.Next();//======================================================与VcArray定义的长度匹配
if (temp != - && temp == t)
{
return RndNum(VcodeNum);//如果获取的随机数重复,则递归调用
}
temp = t;//把本次产生的随机数记录起来
VNum += VcArray[t];//随机数的位数加一
}
return VNum;
} /// <summary>
/// 该方法是将生成的随机数写入图像文件
/// </summary>
/// <param name="VNum">VNum是一个随机数</param>
public MemoryStream Create(out string VNum)
{
VNum = RndNum();
Bitmap Img = null;
Graphics g = null;
MemoryStream ms = null;
System.Random random = new Random();
//验证码颜色集合
Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
//验证码字体集合
string[] fonts ={ "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" }; //定义图像的大小,生成图像的实例
Img = new Bitmap((int)VNum.Length * , ); g = Graphics.FromImage(Img);//从Img对象生成新的Graphics对象 g.Clear(Color.White);//背景设为白色 //在随机位置画背景点
for (int i = ; i < ; i++)
{
int x = random.Next(Img.Width);
int y = random.Next(Img.Height);
g.DrawRectangle(new Pen(Color.LightGray, ), x, y, , );
}
//验证码绘制在g中
for (int i = ; i < VNum.Length; i++)
{
int cindex = random.Next();//随机颜色索引值
int findex = random.Next();//随机字体索引值
Font f = new System.Drawing.Font(fonts[findex], , System.Drawing.FontStyle.Bold);//字体======================字体大小
Brush b = new System.Drawing.SolidBrush(c[cindex]);//颜色
int ii = ;
if ((i + ) % == )//控制验证码不在同一高度
{
ii = ;
}
g.DrawString(VNum.Substring(i, ), f, b, + (i * ), ii);//绘制一个验证字符
}
ms = new MemoryStream();//生成内存流对象
Img.Save(ms, ImageFormat.Jpeg);//将此图像以Png图像文件的格式保存到流中 //回收资源
g.Dispose();
Img.Dispose();
return ms;
} }
html代码:
<asp:TextBox ID="txtVerify" runat="server" MaxLength="4" Width="100px" CssClass="txtin2" Height="18px"></asp:TextBox>
<img src='verify.ashx' style="width:100px;height:30px" id="verify"/>
<a href='javascript:verify();'>看不清,换一张</a>
js换一张代码:
function verify(){
$("#verify").attr("src","verify.ashx");
}
后台代码:
if (txtVerify.Text == "")
{
this.ClientScript.RegisterStartupScript(this.GetType(), "scriptKey", "alert('验证码不能为空!')", true);
}
else if (String.Compare(Session["gif"].ToString(), txtVerify.Text, true) != )
{
txtVerify.Text = "";
this.ClientScript.RegisterStartupScript(this.GetType(), "scriptKey", "alert('验证码有误,请重新输入正确的验证码!')", true);
}
else
{
//通过验证
}
如图,可以自定义字符