验证码生成

using System;
using System.Drawing;
using System.Text;

namespace Wisdom.JPClient.WeiXin.Utility
{
    public class VerifyCode
    {
        // 供验证码生成汉字时选取的汉字集,若为空则按照《GB2312简体中文编码表》编码规则构造汉字
        private const string ChineseChars = "";
        // 英文与数字串
        private const string EnglishOrNumChars = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
        private const double PI = 3.1415926535897932384626433832795;
        private const double PI2 = 6.283185307179586476925286766559;
        // 全局随机数生成器
        private Random rnd;

        public VerifyCode()
        {
            rnd = new Random(unchecked((int)DateTime.Now.Ticks));
        }

        /// <summary>
        /// 生成随机字符码
        /// </summary>
        /// <param name="codeLen">字符串长度</param>
        /// <param name="zhCharsCount">中文字符数</param>
        /// <returns></returns>
        public string CreateVerifyCode(int codeLen, int zhCharsCount)
        {
            char[] chs = new char[codeLen];
            int index = 0;
            for (int i = 0; i < zhCharsCount; i++)
            {
                index = rnd.Next(0, codeLen);
                if (chs[index] == '')
                {
                    chs[index] = CreateZhChar();
                }
                else
                {
                    --i;
                }
            }
            for (int i = 0; i < codeLen; i++)
            {
                if (chs[i] == '')
                {
                    chs[i] = CreateEnOrNumChar();
                }
            }
            return new string(chs, 0, chs.Length);
        }

        /// <summary>
        /// 生成随机字符码 默认6位
        /// </summary>
        /// <returns></returns>
        public string CreateVerifyCode()
        {
            return CreateVerifyCode(4, 0);
        }

        /// <summary>
        /// 生成校验码图片
        /// </summary>
        /// <param name="verifyCode"></param>
        /// <returns></returns>
        public Bitmap CreateImage(string verifyCode, int width, int height, int fontSize)
        {
            if (string.IsNullOrEmpty(verifyCode))
            {
                return null;
            }

            System.Drawing.Bitmap image = new System.Drawing.Bitmap(width, height);
            Graphics g = Graphics.FromImage(image);

            try
            {
                //生成随机生成器
                Random random = new Random();

                //清空图片背景色
                g.Clear(Color.White);

                //画图片的背景噪音线
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);

                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }

                Font font = new System.Drawing.Font("Verdana", fontSize, (System.Drawing.FontStyle.Italic));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(verifyCode, font, brush, 5, 5);

                //画图片的前景噪音点
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }

                //画图片的边框线
                g.DrawRectangle(new Pen(Color.White), 0, 0, image.Width - 1, image.Height - 1);
            }
            catch
            {
                return null;
            }
            return image;
        }

        /// <summary>
        /// 生成英文或数字字符
        /// </summary>
        /// <returns></returns>
        public char CreateEnOrNumChar()
        {
            return EnglishOrNumChars[rnd.Next(0, EnglishOrNumChars.Length)];
        }

        /// <summary>
        /// 生成汉字字符
        /// </summary>
        /// <returns></returns>
        public char CreateZhChar()
        {
            //若提供了汉字集,查询汉字集选取汉字
            if (ChineseChars.Length > 0)
            {
                return ChineseChars[rnd.Next(0, ChineseChars.Length)];
            }
            //若没有提供汉字集,则根据《GB2312简体中文编码表》编码规则构造汉字
            else
            {
                byte[] bytes = new byte[2];

                //第一个字节值在0xb0, 0xf7之间
                bytes[0] = (byte)rnd.Next(0xb0, 0xf8);
                //第二个字节值在0xa1, 0xfe之间
                bytes[1] = (byte)rnd.Next(0xa1, 0xff);

                //根据汉字编码的字节数组解码出中文汉字
                string str1 = Encoding.GetEncoding("gb2312").GetString(bytes);
                return str1[0];
            }
        }

        /// <summary>
        /// 正弦曲线Wave扭曲图片(Edit By 51aspx.com)
        /// </summary>
        /// <param name="srcBmp">图片路径</param>
        /// <param name="bXDir">如果扭曲则选择为True</param>
        /// <param name="nMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param>
        /// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param>
        /// <returns></returns>
        public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
        {
            System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);

            // 将位图背景填充为白色
            System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);
            graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height);
            graph.Dispose();

            double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;

            for (int i = 0; i < destBmp.Width; i++)
            {
                for (int j = 0; j < destBmp.Height; j++)
                {
                    double dx = 0;
                    dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;
                    dx += dPhase;
                    double dy = Math.Sin(dx);

                    // 取得当前点的颜色
                    int nOldX = 0, nOldY = 0;
                    nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
                    nOldY = bXDir ? j : j + (int)(dy * dMultValue);

                    System.Drawing.Color color = srcBmp.GetPixel(i, j);
                    if (nOldX >= 0 && nOldX < destBmp.Width
                        && nOldY >= 0 && nOldY < destBmp.Height)
                    {
                        destBmp.SetPixel(nOldX, nOldY, color);
                    }
                }
            }
            return destBmp;
        }


        #region 生成验证码图片
        /*
        protected void GenerateVerifyImage()
        {
            VerifyCode vc = new VerifyCode();
            string verifyCode = vc.CreateVerifyCode(4, 0);
            Response.Clear();
            System.Drawing.Bitmap img = vc.CreateImage(verifyCode);
            if (img != null)
            {
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                Response.ContentType = "image/jpeg";
                Response.BinaryWrite(ms.GetBuffer());
                img.Dispose();
                ms.Close();
                Response.End();
            }
        }*/
        #endregion

        #region 产生6位手机验证码
        /// <summary>
        /// 产生6位数字手机验证码
        /// </summary>
        /// <returns></returns>
        public string GeneratePhoneVerifyCode()
        {
            const int CodeLen = 6;
            int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            string Code = string.Empty;
            int randomNum;
            Random random = new Random();
            for (int i = 0; i < CodeLen; i++)
            {
                randomNum = random.Next(array.Length);
                Code += array[randomNum];
            }
           // return "111111";
           return Code;

        }
        #endregion
    }
}
原文地址:https://www.cnblogs.com/muxueyuan/p/5593224.html