当前位置:编程学习 > C#/ASP.NET >>

C# 产生验证码 利用背景图片绘制

/// <summary>  
       /// 获取验证码【字符串】  
       /// </summary>  
       /// <param name="Length">验证码长度【必须大于0】</param>  
       /// <returns></returns>  
       public static string VerficationText(int Length)  
       {  
           char[] _verfication=new char[Length];  
           Random _random = new Random();  
           char[] _dictionary = { '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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };  
           for (int i = 0; i < Length; i++)  
           {  
               _verfication[i] = _dictionary[_random.Next(_dictionary.Length - 1)];  
           }  
           return new string(_verfication);  
       }  

 
 
/// <summary>  
       /// 产生验证码方法  
       /// </summary>  
       /// <returns></returns>  
       public void VerificationCode()  
       {  
           int _verificationLength = 6;  
           int _width = 100, _height = 20;  
           SizeF _verificationTextSize;  
           string path = Server.MapPath("~/Skins/Commmon/Texture.jpg");//使用一张背景图  
           Bitmap _bitmap = new Bitmap(path);  
           TextureBrush _brush = new TextureBrush(_bitmap);  
           //获取验证码  
           string _verificationText = VerficationText(_verificationLength);  
           //储存验证码  
           Session["VerificationCode"] = _verificationText.ToUpper();  
           Font _font = new Font("Arial", 14, FontStyle.Bold);  
           Bitmap _image = new Bitmap(_width, _height);  
           Graphics _g = Graphics.FromImage(_image);  
           //清空背景色  
           _g.Clear(Color.White);  
           //绘制验证码  
           _verificationTextSize = _g.MeasureString(_verificationText, _font);  
           _g.DrawString(_verificationText, _font, _brush, (_width - _verificationTextSize.Width) / 2, (_height - _verificationTextSize.Height) / 2);  
           _image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);  
       }  

 

 
补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,