.net 验证码
页面:
1 <html xmlns="http://www.w3.org/1999/xhtml"> 2 <head runat="server"> 3 <title>验证码</title> 4 <script type="text/javascript"> 5 //换一张 6 function change() { 7 var img = document.getElementById("ValidateCode"); 8 img.src = img.src + '?'; 9 } 10 </script> 11 </head> 12 <body> 13 <form id="form1" runat="server"> 14 <div> 15 <table> 16 <tr> 17 <th> 18 验证码 19 </th> 20 <td> 21 <asp:TextBox runat="server" ID="tbCheckCode" CssClass="Small" MaxLength="4"></asp:TextBox> 22 </td> 23 <td> 24 <img src="VerifyCode.aspx" id="ValidateCode" alt="换一张" onclick="javascript:change()" /> 25 </td> 26 <td> 27 <a id="ChangeCode" href="#" onclick="javascript:change()">换一张</a> 28 </td> 29 </tr> 30 <tr> 31 <td> 32 <asp:Button runat="server" ID="LoginSubmit" OnClick="LoginSubmits" Text="登录" /> 33 </td> 34 </tr> 35 </table> 36 </div> 37 </form> 38 </body> 39 </html>
后台代码:
1 /// <summary> 2 /// 登录 3 /// </summary> 4 /// <param name="sender"></param> 5 protected void LoginSubmits(object sender, EventArgs e) 6 { 7 CheckLogin(); 8 } 9 10 #region 私有方法 11 #region 12 public static Boolean IsNotNull(Object str) 13 { 14 return !IsNull(str); 15 } 16 public static Boolean IsNull(Object str) 17 { 18 return str == null; 19 } 20 public static void Show(System.Web.UI.Page page, string msg) 21 { 22 page.ClientScript.RegisterStartupScript(page.GetType(), "message", 23 "<script language='javascript' defer>alert('" + msg.ToString() + "');</script>"); 24 } 25 #endregion 26 27 private void CheckLogin() 28 { 29 if (tbCheckCode.Text.Trim() == "") 30 { 31 Show(this, "验证码不能为空!"); 32 return; 33 } 34 else 35 { 36 if (IsNotNull(Session["ValidateCheckCode"])) 37 { 38 if (tbCheckCode.Text.Trim() != Session["ValidateCheckCode"].ToString()) 39 { 40 Show(this, "验证码填写不正确!"); 41 tbCheckCode.Text = ""; 42 return; 43 } 44 } 45 else 46 { 47 Show(this, "请刷新验证码!"); 48 return; 49 } 50 } 51 } 52 #endregion 53 } 54 }
生成验证码:
1 using System; 2 using System.Drawing; 3 using System.Text; 4 using System.Web; 5 6 namespace Web.TEXT 7 { 8 public partial class VerifyCode : System.Web.UI.Page 9 { 10 public Encoding GB = Encoding.GetEncoding("GB2312"); 11 12 protected void Page_Load(object sender, EventArgs e) 13 { 14 VerifyCode v = new VerifyCode(); 15 16 v.Length = this.length; 17 v.FontSize = this.fontSize; 18 v.Chaos = this.chaos; 19 v.BackgroundColor = this.backgroundColor; 20 v.ChaosColor = this.chaosColor; 21 v.CodeSerial = this.codeSerial; 22 v.Colors = this.colors; 23 v.Fonts = this.fonts; 24 v.Padding = this.padding; 25 string code = v.CreateVerifyCode(); //取随机码 26 v.CreateImageOnPage(code, this.Context); // 输出图片 27 Response.Cookies.Add(new HttpCookie("CheckCode", code.ToUpper())); // 使用Cookies取验证码的值 28 29 System.Web.HttpContext.Current.Session["ValidateCheckCode"] = code; 30 //return checkCode; 31 } 32 33 #region 验证码长度(默认4个验证码的长度) 34 35 private int length = 4; 36 37 public int Length 38 { 39 get { return length; } 40 set { length = value; } 41 } 42 43 #endregion 44 45 #region 验证码字体大小(为了显示扭曲效果,默认40像素,可以自行修改) 46 47 private int fontSize = 12; 48 49 public int FontSize 50 { 51 get { return fontSize; } 52 set { fontSize = value; } 53 } 54 55 #endregion 56 57 #region 边框补(默认1像素) 58 59 private int padding = 1; 60 61 public int Padding 62 { 63 get { return padding; } 64 set { padding = value; } 65 } 66 67 #endregion 68 69 #region 是否输出燥点(默认不输出) 70 71 private bool chaos = true; 72 73 public bool Chaos 74 { 75 get { return chaos; } 76 set { chaos = value; } 77 } 78 79 #endregion 80 81 #region 输出燥点的颜色(默认灰色) 82 83 private Color chaosColor = Color.LightGray; 84 85 public Color ChaosColor 86 { 87 get { return chaosColor; } 88 set { chaosColor = value; } 89 } 90 91 #endregion 92 93 #region 自定义背景色(默认白色) 94 95 private Color backgroundColor = Color.White; 96 97 public Color BackgroundColor 98 { 99 get { return backgroundColor; } 100 set { backgroundColor = value; } 101 } 102 103 #endregion 104 105 #region 自定义随机颜色数组 106 107 private Color[] colors = 108 { 109 Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, 110 Color.DarkCyan, Color.Purple 111 }; 112 113 public Color[] Colors 114 { 115 get { return colors; } 116 set { colors = value; } 117 } 118 119 #endregion 120 121 #region 自定义字体数组 122 123 private string[] fonts = {"Arial", "Georgia"}; 124 125 public string[] Fonts 126 { 127 get { return fonts; } 128 set { fonts = value; } 129 } 130 131 #endregion 132 133 #region 自定义随机码字符串序列(使用逗号分隔) 134 135 private string codeSerial = "0,1,2,3,4,5,6,7,8,9"; 136 // string codeSerial = "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,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"; 137 // string codeSerial = "殃,央,鸯,秧,杨,扬,佯,疡,羊,洋,阳,氧,仰,痒,养,样,漾,邀,腰,妖,瑶,摇,尧,遥,窑,谣,姚,咬,舀,药,要,耀,椰,噎,耶,爷,野,冶,也,页,掖,业,叶,曳,腋,夜,液,一,壹,医,揖,铱,依,伊,衣,颐,夷,遗,移,仪,胰,疑,沂,宜,姨,彝,椅,蚁,倚,已,乙,矣,以,艺,抑,易,邑,屹,亿,役,臆,逸,肄,疫,亦,裔,意,毅,忆,义,益,溢,诣,议,谊,译,异,翼,翌,绎,茵,荫,因,殷,音,阴,姻,吟,银,淫,寅,饮,尹,引,隐,印,英,樱,婴,鹰,应,缨,莹,萤,营,荧,蝇,迎,赢,盈,影,颖,硬,映,哟,拥,佣,臃,痈,庸,雍,踊,蛹,咏,泳,涌,永,恿,勇,用,幽,优,悠,忧,尤,由,邮,铀,犹,油,游,酉,有,友,右,佑,釉,诱,又,幼,迂,淤,于,盂,榆,虞,愚,舆,余,俞,逾,鱼,愉,渝,渔,隅,予,娱,雨,与,屿,禹,株,蛛,朱,猪,诸,诛,逐,竹,烛,煮,拄,瞩,嘱,主,著,柱,助,蛀,贮,铸,筑,住,注,祝,驻,抓,爪,拽,专,砖,转,撰,赚,篆,桩,庄,装,妆,撞,壮,状,椎,锥,追,赘,坠,缀,谆,准,捉,拙,卓,桌,琢,茁,酌,啄,着,灼,浊,兹,咨,资,姿,滋,淄,孜,紫,仔,籽,滓,子,自,渍,字,鬃,棕,踪,宗,综,总,纵,邹,走,奏,揍,租,足,卒,族,祖,诅,阻,组,钻,纂,嘴,醉,最,罪,尊,遵,昨,左,佐,柞,做,作,坐,座"; 138 public string CodeSerial 139 { 140 get { return codeSerial; } 141 set { codeSerial = value; } 142 } 143 144 #endregion 145 146 //产生波形滤镜效果 147 148 #region 产生波形滤镜效果 149 150 private const double PI = 3.1415926535897932384626433832795; 151 private const double PI2 = 6.283185307179586476925286766559; 152 153 /**/ 154 155 /// <summary> 156 /// 正弦曲线Wave扭曲图片(Edit By 51aspx.com) 157 /// </summary> 158 /// <param name="srcBmp">图片路径</param> 159 /// <param name="bXDir">如果扭曲则选择为True</param> 160 /// <param name="nMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param> 161 /// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param> 162 /// <returns></returns> 163 public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase) 164 { 165 System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height); 166 167 // 将位图背景填充为白色 168 System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp); 169 graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height); 170 graph.Dispose(); 171 172 double dBaseAxisLen = bXDir ? (double) destBmp.Height : (double) destBmp.Width; 173 174 for (int i = 0; i < destBmp.Width; i++) 175 { 176 for (int j = 0; j < destBmp.Height; j++) 177 { 178 double dx = 0; 179 dx = bXDir ? (PI2*(double) j)/dBaseAxisLen : (PI2*(double) i)/dBaseAxisLen; 180 dx += dPhase; 181 double dy = Math.Sin(dx); 182 183 // 取得当前点的颜色 184 int nOldX = 0, nOldY = 0; 185 nOldX = bXDir ? i + (int) (dy*dMultValue) : i; 186 nOldY = bXDir ? j : j + (int) (dy*dMultValue); 187 188 System.Drawing.Color color = srcBmp.GetPixel(i, j); 189 if (nOldX >= 0 && nOldX < destBmp.Width 190 && nOldY >= 0 && nOldY < destBmp.Height) 191 { 192 destBmp.SetPixel(nOldX, nOldY, color); 193 } 194 } 195 } 196 197 return destBmp; 198 } 199 200 201 202 #endregion 203 204 #region 生成校验码图片 205 206 public Bitmap CreateImageCode(string code) 207 { 208 int fSize = FontSize; 209 int fWidth = fSize + Padding; 210 211 int imageWidth = (int) (code.Length*fWidth) + 4 + Padding*2; 212 int imageHeight = fSize*2 + Padding; 213 214 System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth, imageHeight); 215 216 Graphics g = Graphics.FromImage(image); 217 218 g.Clear(BackgroundColor); 219 220 Random rand = new Random(); 221 222 //给背景添加随机生成的燥点 223 if (this.Chaos) 224 { 225 226 Pen pen = new Pen(ChaosColor, 0); 227 int c = Length*10; 228 229 for (int i = 0; i < c; i++) 230 { 231 int x = rand.Next(image.Width); 232 int y = rand.Next(image.Height); 233 234 g.DrawRectangle(pen, x, y, 1, 1); 235 } 236 } 237 238 int left = 0, top = 0, top1 = 1, top2 = 1; 239 240 int n1 = (imageHeight - FontSize - Padding*2); 241 int n2 = n1/4; 242 top1 = n2; 243 top2 = n2*2; 244 245 Font f; 246 Brush b; 247 248 int cindex, findex; 249 250 #region 随机字体和颜色的验证码字符 251 252 for (int i = 0; i < code.Length; i++) 253 { 254 cindex = rand.Next(Colors.Length - 1); 255 findex = rand.Next(Fonts.Length - 1); 256 257 f = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold); 258 b = new System.Drawing.SolidBrush(Colors[cindex]); 259 260 if (i%2 == 1) 261 { 262 top = top2; 263 } 264 else 265 { 266 top = top1; 267 } 268 269 left = i*fWidth; 270 271 g.DrawString(code.Substring(i, 1), f, b, left, top); 272 } 273 274 //画一个边框 边框颜色为Color.Gainsboro 275 g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1); 276 g.Dispose(); 277 278 //产生波形 279 //image = TwistImage(image, true, 8, 4); 280 281 return image; 282 } 283 284 #endregion 285 286 //将创建好的图片输出到页面 287 public void CreateImageOnPage(string code, HttpContext context) 288 { 289 System.IO.MemoryStream ms = new System.IO.MemoryStream(); 290 Bitmap image = this.CreateImageCode(code); 291 292 image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 293 294 context.Response.ClearContent(); 295 context.Response.ContentType = "image/Jpeg"; 296 context.Response.BinaryWrite(ms.GetBuffer()); 297 298 ms.Close(); 299 ms = null; 300 image.Dispose(); 301 image = null; 302 } 303 304 #endregion 305 306 #region 生成随机字符码 307 308 public string CreateVerifyCode(int codeLen) 309 { 310 if (codeLen == 0) 311 { 312 codeLen = Length; 313 } 314 315 string[] arr = CodeSerial.Split(','); 316 317 string code = ""; 318 319 int randValue = -1; 320 321 Random rand = new Random(unchecked((int) DateTime.Now.Ticks)); 322 323 for (int i = 0; i < codeLen; i++) 324 { 325 randValue = rand.Next(0, arr.Length - 1); 326 327 code += arr[randValue]; 328 } 329 330 return code; 331 } 332 333 public string CreateVerifyCode() 334 { 335 return CreateVerifyCode(0); 336 } 337 338 #endregion 339 } 340 }
效果: