ASP.NET字母加数字验证码,纯字母和纯数字验证码的生成以及利用Session验证
演示地址:http://www.pengyaou.com/ValidateCodeHandler.aspx
原文出处:http://www.pengyaou.com/LegendsZ/File/2014/08/21/20140821092249684.html
?
class="c#" name="code"> 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; }
?
?