以前在網上找到了很多關于中文驗證碼的文章(園子里也有,大家自己去找吧),但是都沒有調測成功,總出現 The target '__Page' for the callback could not be found or did not implement ICallbackEventHandler不能ICallbackEventHandler回掉的錯誤,我進行了一下修正并整理,現在可以實現了中文驗證碼無刷新的操作,現特把全部源碼分享給大家
 核心源碼
1 public partial class Image : System.Web.UI.Page 2 { 3 protected void Page_Load(object sender, EventArgs e) 4 { 5 CreateCheckCodeImage(GenCode(4)); 6 } 7 /**//**//**//// <summary> 8 /// '產生隨機字符串 9 /// </summary> 10 /// <param name="num">隨機出幾個字符</param> 11 /// <returns>隨機出的字符串</returns> 12 private string GenCode(int num) 13 { 14 string str = "的一是在不了有和人這中大為上個國我以要他時來用們..."; 15 char[] chastr = str.ToCharArray(); 16 17 string code = ""; 18 Random rd = new Random(); 19 int i; 20 for (i = 0; i < num; i++) 21 { 22 //code += source[rd.Next(0, source.Length)]; 23 code += str.Substring(rd.Next(0, str.Length), 1); 24 } 25 return code; 26 27 } 28 29 /**//**//**//// <summary> 30 /// 生成圖片(增加背景噪音線、前景噪音點) 31 /// </summary> 32 /// <param name="checkCode">隨機出字符串</param> 33 private void CreateCheckCodeImage(string checkCode) 34 { 35 if (checkCode.Trim() == "" || checkCode == null) 36 return; 37 Session["Code"] = checkCode; //將字符串保存到Session中,以便需要時進行驗證 38 System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)(checkCode.Length * 21.5), 22); 39 Graphics g = Graphics.FromImage(image); 40 try 41 { 42 //生成隨機生成器 43 Random random = new Random(); 44 45 //清空圖片背景色 46 g.Clear(Color.White); 47 48 // 畫圖片的背景噪音線 49 int i; 50 for (i = 0; i < 25; i++) 51 { 52 int x1 = random.Next(image.Width); 53 int x2 = random.Next(image.Width); 54 int y1 = random.Next(image.Height); 55 int y2 = random.Next(image.Height); 56 g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); 57 } 58 59 Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold)); 60 System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2F, true); 61 g.DrawString(checkCode, font, brush, 2, 2); 62 63 //畫圖片的前景噪音點 64 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); 65 System.IO.MemoryStream ms = new System.IO.MemoryStream(); 66 image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); 67 Response.ClearContent(); 68 Response.ContentType = "image/Gif"; 69 Response.BinaryWrite(ms.ToArray()); 70 71 } 72 catch 73 { 74 g.Dispose(); 75 image.Dispose(); 76 } 77 78 }
希望該源碼只是一個拋磚引玉的作用,你可以進行修改,比如說改中文字庫,字體背景噪音等等 默認帳號密碼均為51aspx,這里用戶登錄只是一個驗證的例子,沒有其他功能
作者51aspx 完整源碼下載地址http://www.51aspx.com/CV/ZhongWenYanZhengMa
|