首页 > 代码库 > C# 生成简单验证码

C# 生成简单验证码

网站登录总是会用到验证码,生成验证码对于C#来说很简单。因为有专门封装好的GDI+类可以直接调用使用具体代码如下

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.UI; 6 using System.Web.UI.WebControls; 7 using System.Drawing; 8  9 namespace Ajax.验证码10 {11     public partial class Yanma : System.Web.UI.Page12     {13         private int CodeNum = 4;14         private string codeNum = "";15         protected void Page_Load(object sender, EventArgs e)16         {17             VeriflcationCode();18             HuaCode(codeNum);19         }20 21         private void VeriflcationCode()22         {23             //生成验证码24             string AllChar = "1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z";25             string[] StrChar = AllChar.Split(,);26             Random rd = new Random();27             string Codes = "";28             for (int i = 0; i < CodeNum; i++)29             {30                 Codes += StrChar[rd.Next(0, 35)];31             }32             codeNum = Codes;33             Session["VerCode"] = Codes; 34         }35 36         private void HuaCode(string Codes)37         {38             int iwidth = (int)(Codes.Length * 17);//定义画布的宽39             System.Drawing.Bitmap images = new System.Drawing.Bitmap(iwidth, 25);//声明一个画布类,初始化图片的宽和高40 41             Graphics g = Graphics.FromImage(images);42             Font f = new Font("Arial", 14);//定义文字类型43             Brush b = new System.Drawing.SolidBrush(Color.Black);//文字颜色 黑色44             Brush r = new System.Drawing.SolidBrush(Color.FromArgb(166, 8, 8));//文字颜色 45             g.Clear(System.Drawing.ColorTranslator.FromHtml("#99C1CB"));//背景色46 47             char[] ch = Codes.ToCharArray();48             for (int i = 0; i < ch.Length; i++)49             {50                 if (ch[i] >= 0 && ch[i] <= 9)51                 {52                     //数字用红色显示 53                     g.DrawString(ch[i].ToString(), f, r, 3 + (i * 14), 3);//将文字画出 文字、字体类型、字体颜色、字体间距、字体于顶部间距54                 }55                 else56                 {   //字母用黑色显示57                     g.DrawString(ch[i].ToString(), f, b, 3 + (i * 14), 3);58                 }59             }60 61             //for循环用来生成一些随机的水平线62             Pen blackPen = new Pen(Color.Black, 0);63             Random rand = new Random();64             for (int i = 0; i < 5; i++)65             {66                 int y = rand.Next(images.Height);67                 g.DrawLine(blackPen, 0, y, images.Width, y);68             }69 70 71             System.IO.MemoryStream ms = new System.IO.MemoryStream();72             images.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);73             //history back 不重复 74             Response.Cache.SetNoStore();//这一句         75             Response.ClearContent();76             Response.ContentType = "image/Jpeg";77             Response.BinaryWrite(ms.ToArray());78             g.Dispose();79             images.Dispose();80         }

效果为: