资源描述:
《asp.net简单的图片验证码》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、简单的图片验证码前几天在网上找了关于图片验证码的一些资料,经过整理,已经能实现简单的图片验证码,以下代码为实现图片验证码的详细代码,帖出来共享下,哈哈!整个思路大概是:首先生成一个验证码的随机数,并用cookies保存产生的随机数,后面我们验证的时候得用到,生成随机数后就是画图片了,具体的代码如下:(有更好的办法还望大家指教!)//首先创建一个CheckImage.aspx页面,前台没代码,后台代码如下:usingSystem;usingSystem.Data;usingSystem.Configuration;usingSystem.Collections;usin
2、gSystem.Web;usingSystem.Web.Security;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.Web.UI.WebControls.WebParts;usingSystem.Web.UI.HtmlControls;usingSystem.IO;usingSystem.Drawing;usingSystem.Drawing.Imaging;publicpartialclassCheckImage:System.Web.UI.Page{protectedvoidPage
3、_Load(objectsender,EventArgse){//在page_load事件中调用Generate()和CreateCheckCodeImage()函数stringstr=GenerateCheckCode();CreateCheckCodeImage(str);}privatestringGenerateCheckCode(){//利用random()随机产生四位大写的字符串(包含数字和字母)intnumber;charcode;stringcheckCode=string.Empty;Randomrandom=newRandom();for(inti
4、=0;i<4;i++){number=random.Next();//下面也可以用其他的方法构思if(number%2==0)code=(char)('0'+(char)(number%10));elsecode=(char)('A'+(char)(number%26));checkCode+=code.ToString();}//用cookies保存刚刚产生的随机字符串Response.Cookies.Add(newHttpCookie("CheckCode",checkCode));returncheckCode;}privatevoidCreateCheckCo
5、deImage(stringcheckCode){//该函数主要是画背景色的if(checkCode==null
6、
7、checkCode.Trim()==string.Empty)return;System.Drawing.Bitmapimage=newSystem.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length*12.5)),22);Graphicsg=Graphics.FromImage(image);try{//生成随机生成器Randomrandom=newRandom();//清空背景色g.Clear(Col
8、or.White);//画图片的背景for(inti=0;i<2;i++){intx1=random.Next(image.Width);intx2=random.Next(image.Width);inty1=random.Next(image.Height);inty2=random.Next(image.Height);g.DrawLine(newPen(Color.Black),x1,y1,x2,y2);}Fontfont=newSystem.Drawing.Font("Arial",12,(System.Drawing.FontStyle.Bold));Sy
9、stem.Drawing.Drawing2D.LinearGradientBrushbrush=newSystem.Drawing.Drawing2D.LinearGradientBrush(newRectangle(60,60,image.Width,image.Height),Color.Blue,Color.DarkRed,1.2f,true);g.DrawString(checkCode,font,brush,2,2);//画图片的前景for(inti=0;i<100;i++){intx=random.Next(image.Width);in