验证码 代码
??驗證碼詳細代碼 已通過測試
?
例一:
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Drawing;public partial class _Default : System.Web.UI.Page {protected void Page_Load(object sender, EventArgs e){//生成隨機碼string code = "";Random rand = new Random();for (int i = 0; i < 4; i++){int num = rand.Next();string letter = "";switch (num % 3){case 1:letter = Convert.ToChar(rand.Next(48, 58)).ToString();break;case 2:letter = Convert.ToChar(rand.Next(65, 91)).ToString();break;default:letter = Convert.ToChar(rand.Next(97, 123)).ToString();break;}code += letter;}//Response.Write(code); //生成圖形Bitmap img = new Bitmap(80, 40);Graphics g = Graphics.FromImage(img);g.Clear(Color.GreenYellow);//Brush brush = new SolidBrush(Color.FromArgb(233,133,33));System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, img.Width - 1, img.Height - 1), Color.Red, Color.Green, 2.0F);//加矩形框g.DrawRectangle(new Pen(Color.Blue, 1), 0, 0, img.Width - 1, img.Height - 1);//畫線g.DrawString(code, new Font("Comic Sans MS", 22), brush, 0, 0);//加雪花for (int i = 0; i < 10; i++){int x1 = rand.Next(0, img.Width);int y1 = rand.Next(0, img.Height);img.SetPixel(x1, y1, Color.Gray);}//加亂線for (int i = 0; i < 5; i++){int x1 = rand.Next(0, img.Width);int y1 = rand.Next(0, img.Height);int x2 = rand.Next(0, img.Width);int y2 = rand.Next(0, img.Height);g.DrawLine(new Pen(Color.SeaGreen, 1), x1, y1, x2, y2);}Response.ContentType = "image/gif";img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);Session["code"] = code;brush.Dispose();g.Dispose();img.Dispose();} }
?
?
例二:
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Drawing;public partial class CreateCode : System.Web.UI.Page {protected void Page_Load(object sender, EventArgs e){CreateCheckCodeImage(GenerateCheckCode());}/// <summary>/// 生成5位驗證碼的字母和數字/// </summary>/// <returns>驗證碼的字符串</returns>private string GenerateCheckCode(){int number;char code;string strCheckCode = String.Empty;System.Random random = new Random();for (int iCount = 0; iCount < 5; iCount++){number = random.Next();if (number % 2 == 0){code = (char)('0' + (char)(number % 10));}else{code = (char)('A' + (char)(number % 26));}strCheckCode += code.ToString();}//Response.Cookies.Add(new HttpCookie("checkcode",strCheckCode)); Session["CheckCode"] = strCheckCode;return strCheckCode;}/// <summary>/// 創建驗證碼圖片,并將其寫入內存流中/// </summary>/// <param name="CheckCode"></param>private void CreateCheckCodeImage(string CheckCode){if (CheckCode == null || CheckCode.Trim() == String.Empty){return;}Bitmap img = new Bitmap((int)Math.Ceiling((CheckCode.Length * 12.5)), 22);Graphics g = Graphics.FromImage(img);try{//生成隨機生成器Random random = new Random();//清空圖片背景色g.Clear(Color.White);//畫圖片的背景噪音線for (int iCount = 0; iCount < 25; iCount++){int x1 = random.Next(img.Width);int x2 = random.Next(img.Width);int y1 = random.Next(img.Height);int y2 = random.Next(img.Height);g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);}Font font = new Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, img.Width, img.Height), Color.Blue, Color.DarkRed, 1.2f, true);g.DrawString(CheckCode, font, brush, 2, 2);//畫圖片的前景噪音點for (int i = 0; i < 100; i++){int x = random.Next(img.Width);int y = random.Next(img.Height);img.SetPixel(x, y, Color.FromArgb(random.Next()));}//畫圖片的邊框線g.DrawRectangle(new Pen(Color.Silver), 0, 0, img.Width - 1, img.Height - 1);System.IO.MemoryStream ms = new System.IO.MemoryStream();img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);Response.ClearContent();Response.ContentType = "image/Gif";Response.BinaryWrite(ms.ToArray());}catch (Exception exp){throw exp;}finally{g.Dispose();img.Dispose();}} }
?
例三:
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Threading; using System.Drawing;/// <summary> /// 生成驗證碼圖片的頁面 /// </summary> public partial class ImageCode : System.Web.UI.Page {/// <summary>/// 檢查指定的文本是否匹配驗證碼/// </summary>/// <param name="text">要判斷的文本</param>/// <returns>是否匹配</returns>public static bool CheckCode(string text){string txt = System.Web.HttpContext.Current.Session["code"] as string;return text == txt;}protected void Page_Load(object sender, System.EventArgs e){// 創建一個包含隨機內容的驗證碼文本System.Random rand = new Random();int len = rand.Next(4, 6);char[] chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();System.Text.StringBuilder myStr = new System.Text.StringBuilder();for (int iCount = 0; iCount < len; iCount++){myStr.Append(chars[rand.Next(chars.Length)]);}string text = myStr.ToString();// 保存驗證碼到 session 中以便其他模塊使用this.Session["code"] = text;Size ImageSize = Size.Empty;Font myFont = new Font("MS Sans Serif", 20);// 計算驗證碼圖片大小using (Bitmap bmp = new Bitmap(10, 10)){using (Graphics g = Graphics.FromImage(bmp)){SizeF size = g.MeasureString(text, myFont, 10000);ImageSize.Width = (int)size.Width + 8;ImageSize.Height = (int)size.Height + 8;}}// 創建驗證碼圖片using (Bitmap bmp = new Bitmap(ImageSize.Width, ImageSize.Height)){// 繪制驗證碼文本using (Graphics g = Graphics.FromImage(bmp)){g.Clear(Color.White);using (StringFormat f = new StringFormat()){f.Alignment = StringAlignment.Near;f.LineAlignment = StringAlignment.Center;f.FormatFlags = StringFormatFlags.NoWrap;g.DrawString(text,myFont,Brushes.Black,new RectangleF(0,0,ImageSize.Width,ImageSize.Height),f);}//using}//using// 制造噪聲 雜點面積占圖片面積的 30%int num = ImageSize.Width * ImageSize.Height * 30 / 100;for (int iCount = 0; iCount < num; iCount++){// 在隨機的位置使用隨機的顏色設置圖片的像素int x = rand.Next(ImageSize.Width);int y = rand.Next(ImageSize.Height);int r = rand.Next(255);int g = rand.Next(255);int b = rand.Next(255);Color c = Color.FromArgb(r, g, b);bmp.SetPixel(x, y, c);}//for// 輸出圖片System.IO.MemoryStream ms = new System.IO.MemoryStream();bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);this.Response.ContentType = "image/png";ms.WriteTo(this.Response.OutputStream);ms.Close();}myFont.Dispose();} }
?
?
?
?
中文驗證碼
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Drawing; using System.IO;public partial class CreateCode : System.Web.UI.Page {protected void Page_Load(object sender, EventArgs e){// 生成驗證碼string code = "";Random rand = new Random();for (int i = 0; i < 4; i++){int row = rand.Next(16, 86);int col = rand.Next(0, 94);byte[] bts = new byte[2];bts[0] = (byte)(160 + row);bts[1] = (byte)(160 + col);code += System.Text.Encoding.Default.GetString(bts);}// Response.Write(code);Bitmap bmp = new Bitmap(100, 30);Graphics g = Graphics.FromImage(bmp);g.Clear(Color.AntiqueWhite);g.DrawLine(new Pen(Color.Red), 0, 0, bmp.Width - 1, bmp.Height - 1);for (int i = 0; i < 600; i++){int x = rand.Next(0, bmp.Width);int y = rand.Next(0, bmp.Height);bmp.SetPixel(x, y, Color.SeaShell);}// System.Drawing.Drawing2D.LinearGradientBrushg.DrawString(code, new Font("黑體", 16F, FontStyle.Bold), Brushes.Red, new Point(4, 4));Response.ContentType = "image/gif";// bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);MemoryStream ms = new MemoryStream();bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);Response.BinaryWrite(ms.ToArray());} } ?
?
?
?
一些方法:
/**//// <summary>/// 產生隨機的數字和字母混合字符/// </summary>/// <param name="length">字符串長度</param>/// <param name="sleep"></param>/// <returns></returns>public static string NumChar(int length, bool sleep){if (sleep)Thread.Sleep(2);char[] Patten = new char[] { '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' };string result = "";int n = Patten.Length;Random random = new Random(~unchecked((int)DateTime.Now.Ticks));for (int i = 0; i < length; i++){int rnd = random.Next(0, n);result += Patten[rnd];}return result;}/**//// <summary>/// 產生隨機的數字字符/// </summary>/// <param name="length"></param>/// <param name="sleep"></param>/// <returns></returns>public static string Num(int length, bool sleep){if (sleep)Thread.Sleep(2);char[] Patten = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };string result = "";int n = Patten.Length;Random random = new Random(~unchecked((int)DateTime.Now.Ticks));for (int i = 0; i < length; i++){int rnd = random.Next(0, n);result += Patten[rnd];}return result;}/**//// <summary>/// 產生隨機的字母混合字符/// </summary>/// <param name="length"></param>/// <param name="sleep"></param>/// <returns></returns>public static string Char(int length, bool sleep){if (sleep)Thread.Sleep(2);char[] Patten = new char[] { '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' };string result = "";int n = Patten.Length;Random random = new Random(~unchecked((int)DateTime.Now.Ticks));for (int i = 0; i < length; i++){int rnd = random.Next(0, n);result += Patten[rnd];}return result;}
?
總結
- 上一篇: 在搜索引擎的搜索结果中屏蔽CSDN
- 下一篇: 空中网第四季度净利润477万美元 同比降