aspnet2014-08-21 17:22:49 6960
ASP.NET字母加数字验证码,纯字母和纯数字验证码的生成以及利用Session验证。
代码:
public class VCHandler : System.Web.UI.Page { string strs = ""; public string GetValidatePath(int type) { Bitmap bitmap = new Bitmap(70, 30);//生成bitmap图像 string validateCode = NumAndLetter(type);//生成验证码 DisturbBitmap(bitmap); return DrawValidateCode(bitmap, validateCode); //绘制验证码图像 } public string NumAndLetter(int type) { //定义一个包括数字、大写英文字母和小写英文字母的字符串 string strchar = ""; switch (type) { case 0: strchar = "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"; break; case 1: strchar = "0,1,2,3,4,5,6,7,8,9"; break; case 2: strchar = "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"; break; } //将strchar字符串转化为数组 string[] VcArray = strchar.Split(','); string validateCode = ""; //采用一个简单的算法以保证生成的随机数不同 Random rand = new Random(); //验证码长度 for (int i = 1; i < 5 ; i ) { int t = rand.Next(VcArray.Length); validateCode = VcArray[t]; } Session["validatecode"] = validateCode.ToUpper();//可将其保存在Session中 return validateCode; //返回生成的随机数 } private void DisturbBitmap(Bitmap bitmap)//图象背景 { Random random = new Random(); for (int i = 0; i < bitmap.Width; i ) { for (int j = 0; j < bitmap.Height; j ) { if (random.Next(100) <= 100) bitmap.SetPixel(i, j, Color.DarkGreen); } } } private string DrawValidateCode(Bitmap bitmap, string validateCode)//绘制验证码图像 { Graphics g = Graphics.FromImage(bitmap); Font font = new Font("微软雅黑", 14, FontStyle.Bold); g.DrawString(validateCode, font, Brushes.White, 10, 0); System.Drawing.Image mImage = new Bitmap(70, 30); g.DrawImage(bitmap, new Rectangle(0, 0, 64, 30)); string id = DateTime.Now.ToString("yyyyMMddHHmmssfff"); string path = System.Web.HttpContext.Current.Server.MapPath("Validate/" id ".jpg"); bitmap.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg); return "Validate/" id ".jpg"; } public string VC(string str) { string returnString = ""; if (str == strs) returnString = "1"; returnString = "0"; return returnString; } }
彭亚欧个人博客原创文章,转载请注明出处
文章关键词:ASP.NET验证码生成与验证,ASP.NET生成验证码
文章固定链接:https://www.pengyaou.com/legendsz/server/aspnet/OTM=.html
上一篇 Javascript圆盘计速表