asp.net如何生成图片验证码(简单)
新建一个页面image.aspx,添加命名空间:
usingSystem.Drawing.Imaging;
usingSystem.IO;
然后在Page_load事件拷入如下代码:
//生成4位的验证码
stringtmp=RndNum(4);
HttpCookiea=newHttpCookie("ImageV",tmp);
Response.Cookies.Add(a);
this.ValidateCode(tmp);
接下来向该页面添加两个方法:
privatevoidValidateCode(stringVNum)
{
BitmapImg=null;
Graphicsg=null;
MemoryStreamms=null;
intgheight=VNum.Length*12;
Img=newBitmap(gheight,25);
g=Graphics.FromImage(Img);
//背景颜色
g.Clear(Color.White);
//文字字体
Fontf=newFont("ArialBlack",10);
//文字颜色
SolidBrushs=newSolidBrush(Color.Black);
g.DrawString(VNum,f,s,3,3);
ms=newMemoryStream();
Img.Save(ms,ImageFormat.Jpeg);
Response.ClearContent();
Response.ContentType="image/Jpeg";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
Img.Dispose();
Response.End();
}
privatestringRndNum(intVcodeNum)
{
stringVchar="0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p"+
",q,r,s,t,u,v,w,x,y,z";
string[]VcArray=Vchar.Split(newChar[]{','});
stringVNum="";
inttemp=-1;
Randomrand=newRandom();
for(inti=1;i<VcodeNum+1;i++)
{
if(temp!=-1)
{
rand=newRandom(i*temp*unchecked((int)DateTime.Now.Ticks));
}
intt=rand.Next(35);
if(temp!=-1&&temp==t)
{
returnRndNum(VcodeNum);
}
temp=t;
VNum+=VcArray[t];
}
returnVNum;
}
如果要在页面a.aspx生成验证码,则在该页面添加一个图片控件,假设命名为:ImageButton1,然后在page_Load事件中写如下代码:
ImageButton1.ImageUrl="image.aspx";
这样就可以生成验证码了,image.aspx页面可以随便放在哪里,不过要注意ImageButton1.ImageUrl要写对,同级可以直接写image.aspx,上一级写../image.aspx,很方便吧