验证码详细代码 已通过测试 例一: 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.LinearGradientBrush g.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; }