⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 validatecode.cs

📁 精通SQL Server2005项目开发
💻 CS
字号:
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;

namespace HRManager.CommonComponent
{
    /// <summary>
    /// 生成验证码图象类
    /// </summary>
    public class ValidateCode
    {
        private const int CODELEN = 4;  //4位验证码
        
        public string code;             //生成的验证码
        public string imgFilePath ;     //生成的图象路径
        public string imgFileName;      //生成的图象文件名

        /// <summary>
        /// 构造函数,得到保存图象的路径
        /// </summary>
        public ValidateCode(string imgFilePath)
        {
            this.imgFilePath = imgFilePath;
        }

        /// <summary>
        /// 析构函数,删除生成的图象文件
        /// </summary>
        ~ValidateCode()
        {
            File.Delete(this.imgFilePath+this.imgFileName);	//使用File的Delete静态方法,删除临时图象
        }

        /// <summary>
        /// 生成验证码图象文件,并存储在服务器中
        /// </summary>
        public void GenerateCodeImage()
        {
            this.GetCode();
            Bitmap img = null;
            Graphics g = null;            

            int gHeight = code.Length * 12;
            img = new Bitmap(gHeight, 25);
            g = Graphics.FromImage(img);

            g.Clear(Color.AliceBlue);                       //背景颜色            
            Font font = new Font("Arial Black", 10);        //文字字体
            SolidBrush brush = new SolidBrush(Color.Black); //文字颜色
           
            g.DrawString(this.code, font, brush, 3, 3);
            
            this.imgFileName = this.code + ".Png";
            img.Save(this.imgFilePath+this.imgFileName, ImageFormat.Png);

            g.Dispose();
            img.Dispose();
        }

        /// <summary>
        /// 生成随即的四位字母、数字混合串
        /// </summary>
        /// <returns>四位字母、数字混合串</returns>
        public void GetCode()
        {
            char[] allChars = 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',
                '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'
            };
            
            Random rand = new Random();

            for (int i = 0; i < CODELEN; i++)
            {
                rand = new Random((i+1) * (int)DateTime.Now.Ticks);
                this.code+= allChars[rand.Next(allChars.Length - 1)];
            }
        }      
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -