c# 验证码类

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Web;

namespace Demo
{
    /// <summary>
    /// Captcha
    /// </summary>
    public class Captcha
    {
        #region Private Field
        /// <summary>
        /// 随机种子
        /// </summary>
        private Random objRandom = new Random();
        #endregion

        #region Public Property

        #region 验证码长度
        /// <summary>
        /// 验证码长度
        /// </summary>
        private int length = 4;
        /// <summary>
        /// 验证码长度(默认为4)
        /// </summary>
        public int Length
        {
            get { return this.length; }
            set { this.length = value; }
        }
        #endregion

        #region 验证码字符串
        /// <summary>
        /// 验证码字符串
        /// </summary>
        private string verifyCodeText = null;

        /// <summary>
        /// 验证码字符串
        /// </summary>
        public string VerifyCodeText
        {
            get { return this.verifyCodeText; }
            set { this.verifyCodeText = value; }
        }
        #endregion

        #region 是否加入小写字母
        /// <summary>
        /// 是否加入小写字母
        /// </summary>
        private bool addLowerLetter = false;

        /// <summary>
        /// 是否加入小写字母(不包括o)
        /// </summary>
        public bool AddLowerLetter
        {
            get { return this.addLowerLetter; }
            set { this.addLowerLetter = value; }
        }
        #endregion

        #region 是否加入大写字母
        /// <summary>
        /// 是否加入大写字母
        /// </summary>
        private bool addUpperLetter = false;

        /// <summary>
        /// 是否加入大写字母(不包括O)
        /// </summary>
        public bool AddUpperLetter
        {
            get { return this.addUpperLetter; }
            set { this.addUpperLetter = value; }
        }
        #endregion

        #region 字体大小
        /// <summary>
        /// 字体大小
        /// </summary>
        private int fontSize = 18;

        /// <summary>
        /// 字体大小(默认为18)
        /// </summary>
        public int FontSize
        {
            get { return this.fontSize; }
            set { this.fontSize = value; }
        }
        #endregion

        #region 字体颜色
        /// <summary>
        /// 字体颜色
        /// </summary>
        private Color fontColor = Color.Blue;

        /// <summary>
        /// 字体颜色(默认为Blue)
        /// </summary>
        public Color FontColor
        {
            get { return this.fontColor; }
            set { this.fontColor = value; }
        }
        #endregion

        #region 字体类型
        /// <summary>
        /// 字体类型
        /// </summary>
        private string fontFamily = "Verdana";

        /// <summary>
        /// 字体类型(默认为Verdana)
        /// </summary>
        public string FontFamily
        {
            get { return this.fontFamily; }
            set { this.fontFamily = value; }
        }
        #endregion

        #region 背景色
        /// <summary>
        /// 背景色
        /// </summary>
        private Color backgroundColor = Color.AliceBlue;

        /// <summary>
        /// 背景色(默认为AliceBlue)
        /// </summary>
        public Color BackgroundColor
        {
            get { return this.backgroundColor; }
            set { this.backgroundColor = value; }
        }
        #endregion

        #region 前景噪点数量
        /// <summary>
        /// 前景噪点数量
        /// </summary>
        private int foreNoisePointCount = 2;

        /// <summary>
        /// 前景噪点数量(默认为2)
        /// </summary>
        public int ForeNoisePointCount
        {
            get { return this.foreNoisePointCount; }
            set { this.foreNoisePointCount = value; }
        }
        #endregion

        #region 随机码的旋转角度
        /// <summary>
        /// 随机码的旋转角度
        /// </summary>
        private int randomAngle = 45;

        /// <summary>
        /// 随机码的旋转角度(默认为40度)
        /// </summary>
        public int RandomAngle
        {
            get { return this.randomAngle; }
            set { this.randomAngle = value; }
        }
        #endregion

        #endregion

        #region Constructor Method
        /// <summary>
        /// 构造方法
        /// </summary>
        public Captcha()
        {
            this.GetText();
        }
        #endregion

        #region Private Method
        /// <summary>
        /// 得到验证码字符串
        /// </summary>
        private void GetText()
        {
            //没有外部输入验证码时随机生成
            if (String.IsNullOrEmpty(this.verifyCodeText))
            {
                StringBuilder objStringBuilder = new StringBuilder();

                //加入数字1-9
                for (int i = 1; i <= 9; i++)
                {
                    objStringBuilder.Append(i.ToString());
                }

                //加入大写字母A-Z,不包括O
                if (this.addUpperLetter)
                {
                    char temp = ‘ ‘;

                    for (int i = 0; i < 26; i++)
                    {
                        temp = Convert.ToChar(i + 65);

                        //如果生成的字母不是‘O‘
                        if (!temp.Equals(‘O‘))
                        {
                            objStringBuilder.Append(temp);
                        }
                    }
                }

                //加入小写字母a-z,不包括o
                if (this.addLowerLetter)
                {
                    char temp = ‘ ‘;

                    for (int i = 0; i < 26; i++)
                    {
                        temp = Convert.ToChar(i + 97);

                        //如果生成的字母不是‘o‘
                        if (!temp.Equals(‘o‘))
                        {
                            objStringBuilder.Append(temp);
                        }
                    }
                }

                //生成验证码字符串
                {
                    int index = 0;

                    for (int i = 0; i < length; i++)
                    {
                        index = objRandom.Next(0, objStringBuilder.Length);

                        this.verifyCodeText += objStringBuilder[index];

                        objStringBuilder.Remove(index, 1);
                    }
                }
            }
        }
        /// <summary>
        /// 得到验证码图片
        /// </summary>
        private Bitmap GetImage()
        {
            Bitmap result = null;

            //创建绘图
            result = new Bitmap(this.verifyCodeText.Length * 16, 25);

            using (Graphics objGraphics = Graphics.FromImage(result))
            {
                objGraphics.SmoothingMode = SmoothingMode.HighQuality;

                //清除整个绘图面并以指定背景色填充
                objGraphics.Clear(this.backgroundColor);

                //创建画笔
                using (SolidBrush objSolidBrush = new SolidBrush(this.fontColor))
                {
                    this.AddForeNoisePoint(result);

                    this.AddBackgroundNoisePoint(result, objGraphics);

                    //文字居中
                    StringFormat objStringFormat = new StringFormat(StringFormatFlags.NoClip);

                    objStringFormat.Alignment = StringAlignment.Center;
                    objStringFormat.LineAlignment = StringAlignment.Center;

                    //字体样式
                    Font objFont = new Font(this.fontFamily, objRandom.Next(this.fontSize - 3, this.fontSize), FontStyle.Regular);

                    //验证码旋转,防止机器识别
                    char[] chars = this.verifyCodeText.ToCharArray();

                    for (int i = 0; i < chars.Length; i++)
                    {
                        //转动的度数
                        float angle = objRandom.Next(-this.randomAngle, this.randomAngle);

                        objGraphics.TranslateTransform(12, 12);
                        objGraphics.RotateTransform(angle);
                        objGraphics.DrawString(chars[i].ToString(), objFont, objSolidBrush, -2, 2, objStringFormat);
                        objGraphics.RotateTransform(-angle);
                        objGraphics.TranslateTransform(2, -12);
                    }
                }
            }

            return result;
        }
        /// <summary>
        /// 添加前景噪点
        /// </summary>
        /// <param name="objBitmap"></param>
        private void AddForeNoisePoint(Bitmap objBitmap)
        {
            for (int i = 0; i < objBitmap.Width * this.foreNoisePointCount; i++)
            {
                objBitmap.SetPixel(objRandom.Next(objBitmap.Width), objRandom.Next(objBitmap.Height), this.fontColor);
            }
        }
        /// <summary>
        /// 添加背景噪点
        /// </summary>
        /// <param name="objBitmap"></param>
        /// <param name="objGraphics"></param>
        private void AddBackgroundNoisePoint(Bitmap objBitmap, Graphics objGraphics)
        {
            using (Pen objPen = new Pen(Color.Azure, 0))
            {
                for (int i = 0; i < objBitmap.Width * 2; i++)
                {
                    objGraphics.DrawRectangle(objPen, objRandom.Next(objBitmap.Width), objRandom.Next(objBitmap.Height), 1, 1);
                }
            }
        }
        #endregion

        #region Public Method
        public void Output(HttpResponse objHttpResponse)
        {
            using (Bitmap objBitmap = this.GetImage())
            {
                if (objBitmap != null)
                {
                    using (MemoryStream objMS = new MemoryStream())
                    {
                        objBitmap.Save(objMS, ImageFormat.Jpeg);

                        HttpContext.Current.Response.ClearContent();
                        HttpContext.Current.Response.ContentType = "image/Jpeg";
                        HttpContext.Current.Response.BinaryWrite(objMS.ToArray());
                        HttpContext.Current.Response.Flush();
                        HttpContext.Current.Response.End();
                    }
                }
            }
        }
        #endregion
    }
}
时间: 2024-10-12 04:38:29

c# 验证码类的相关文章

ThinkPHP 3.2.3 加减乘法验证码类

ThinkPHP 3.2.3 自带的验证码类位于 /ThinkPHP/Library/Think/Verify.class.php,字体文件位于 /ThinkPHP/Library/Think/Verify/ 可以在 Verify.class.php 文件内进行修改,也可以单独写一个类继承自带的验证码类.如果单独写一个继承的类,可以重用父类的属性和方法,但是要注意的是父类中有一些属性和方法是私有(private)的,可以修改这些私有的属性和方法为保护(protected)的,如果不希望修改框架自

建立一个漂亮的PHP验证码类文件及调用方式

//验证码类class ValidateCode { private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';//随机因子 private $code;//验证码 private $codelen = 4;//验证码长度 private $width = 130;//宽度 private $height = 50;//高度 private $img;//图形资源句柄 private $font;//指定的字体

PHP之验证码类

<?php /** * Created by PhpStorm. * User: Administrator * Date: 2016/6/20 * Time: 14:29 */ Class captcha{ //验证码类 protected $str="xaaxqwe556232assd"; //随机数 protected $code; //验证码 protected $length=4; //验证码长度 protected $width=80; //验证码宽度 protect

包装一个php的验证码类

验证码是我们开发的时候经常用到的功能,所以在此本人包装了一个验证码类,应该可以作为php的类插件用,在此分享给各位博客园的读友. 实现的原理也是很简单,就是利用画布的几个元素,再加上一些字符串的获取,东凑西凑就构成了,呵呵. 这里大概写一下思路吧,其实这个类已经注释的非常清楚了,不过,个人还是在行文前啰嗦一下. 首先是关于一些函数的解释,这里的解释纯属个人体会,有什么错误的地方,还请读者指正. 1.创建画布函数:imagecreatetruecolor(w,h); 说明:用于创建一个画布. w

2、载入验证码类及$_SESSION处理

1.载入验证码类,并验证 (1)下载定义好的code验证码类,放置到resources目录下 (2) 添加路由 Route::get('/admin/code','Admin\[email protected]'); (3)添加方法 LoginController.php public function code() { $code = new \Code(); $code->make(); } 注意: 不要忘记引入Code类,不加'\',会引入App\Http\Controllers\Admi

PHP-解析验证码类--学习笔记

1.开始 在 网上看到使用PHP写的ValidateCode生成验证码码类,感觉不错,特拿来分析学习一下. 2.类图 3.验证码类部分代码 3.1  定义变量 //随机因子 private $charset = 'abcdefghjkmnprstuvwxyzABCDEFGJKMNPRSTUVWXYZ23456789'; private $code; private $codeLen = 4; private $width = 130; private $heigh = 50; private $

面向对象中的验证码类

<?php /** * 验证码类 */ class Verify { //成员属性 private $width; //宽 private $height; //高 private $verify_code; //验证码字符串 private $verify_nums; //验证码个数 private $verify_type; //验证码字符类型 private $image_type; //图片类型(JPG/PNG) private $res; //图片资源 //构造函数来执行需要初始化的成

laravel之引入验证码类

1.将验证码类文件夹放入到指定的位置,放入位置可以自定义 2.在控制器中引入验证码文件 3.在验证码文件中可以根据自己的需要,对验证码的内容进行编辑(包括背景,画线,边框,内容) 4.在入口文件中开启session 5.验证码调用 6.验证码验证

PHP编写的图片验证码类文件分享方法

适用于自定义的验证码类! <?php /* * To change this license header, choose License Headers in Project Properties.* To change this template file, choose Tools | Templates* and open the template in the editor.*/Class Image{ private $img;public $width = 85;public $h

漂亮的 PHP 验证码类

<?php //验证码类 class ValidateCode { private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';    //随机因子     private $code;                            //验证码     private $codelen = 4;                    //验证码长度     private $width = 130;