创建一个验证码图片类

 

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Drawing;

using System.Drawing.Imaging;

using System.Drawing.Drawing2D;

using System.IO;



namespace lishuhua

{



    public partial class Validator : System.Web.UI.Page

    {



        protected void Page_Load(object sender, EventArgs e)

        {

            //GenerateValidateCode();

            GenerateVerifyImage(4);//GenerateVerifyImage(int length)

        }



        #region 【无刷新仿google波形扭曲彩色】验证码样式0___GenerateValidateCode()

        private void GenerateValidateCode()

        {

            this.Length = this.length;

            this.FontSize = this.fontSize;

            this.Chaos = this.chaos;

            this.BackgroundColor = this.backgroundColor;

            this.ChaosColor = this.chaosColor;

            this.CodeSerial = this.codeSerial;

            this.Colors = this.colors;

            this.Fonts = this.fonts;

            this.Padding = this.padding;

            string VNum = this.CreateVerifyCode(); //取随机码

            Session["ValidateCode"] = VNum.ToUpper();//取得验证码,以便后来验证

            this.CreateImageOnPage(VNum, this.Context); // 输出图片

            //Cookie验证模式, 使用Cookies取验证码的值

            //Response.Cookies.Add(new HttpCookie("CheckCode", code.ToUpper()));

        }

        #endregion

        #region 验证码长度(默认4个验证码的长度)

        int length = 4;

        public int Length

        {

            get { return length; }

            set { length = value; }

        }

        #endregion

        #region 验证码字体大小(为了显示扭曲效果,默认40像素,可以自行修改)

        int fontSize = 22;

        public int FontSize

        {

            get { return fontSize; }

            set { fontSize = value; }

        }

        #endregion

        #region 边框补(默认1像素)

        int padding = 2;

        public int Padding

        {

            get { return padding; }

            set { padding = value; }

        }

        #endregion

        #region 是否输出燥点(默认不输出)

        bool chaos = true;

        public bool Chaos

        {

            get { return chaos; }

            set { chaos = value; }

        }

        #endregion

        #region 输出燥点的颜色(默认灰色)

        Color chaosColor = Color.LightGray;

        public Color ChaosColor

        {

            get { return chaosColor; }

            set { chaosColor = value; }

        }

        #endregion

        #region 自定义背景色(默认白色)

        Color backgroundColor = Color.White;

        public Color BackgroundColor

        {

            get { return backgroundColor; }

            set { backgroundColor = value; }

        }

        #endregion

        #region 自定义随机颜色数组

        Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };

        public Color[] Colors

        {

            get { return colors; }

            set { colors = value; }

        }

        #endregion

        #region 自定义字体数组

        string[] fonts = { "Arial", "Georgia" };

        public string[] Fonts

        {

            get { return fonts; }

            set { fonts = value; }

        }

        #endregion

        #region 自定义随机码字符串序列(使用逗号分隔)

        string codeSerial = "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";

        public string CodeSerial

        {

            get { return codeSerial; }

            set { codeSerial = value; }

        }

        #endregion

        #region 产生波形滤镜效果

        private const double PI = 3.1415926535897932384626433832795;

        private const double PI2 = 6.283185307179586476925286766559;

        /// <summary>

        /// 正弦曲线Wave扭曲图片

        /// </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 Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)

        {

            Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);

            // 将位图背景填充为白色

            System.Drawing.Graphics graph = Graphics.FromImage(destBmp);

            graph.FillRectangle(new SolidBrush(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;

        }

        #endregion

        #region 生成校验码图片

        public Bitmap CreateImageCode(string code)

        {

            int fSize = FontSize;

            int fWidth = fSize + Padding;

            int imageWidth = (int)(code.Length * fWidth) + 4 + Padding * 2;

            int imageHeight = fSize * 2 + Padding;

            System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth, imageHeight);

            Graphics g = Graphics.FromImage(image);

            g.Clear(BackgroundColor);

            Random rand = new Random();

            //给背景添加随机生成的燥点

            if (this.Chaos)

            {

                Pen pen = new Pen(ChaosColor, 0);

                int c = Length * 10;

                for (int i = 0; i < c; i++)

                {

                    int x = rand.Next(image.Width);

                    int y = rand.Next(image.Height);

                    g.DrawRectangle(pen, x, y, 1, 1);

                }

            }

            int left = 0, top = 0, top1 = 1, top2 = 1;

            int n1 = (imageHeight - FontSize - Padding * 2);

            int n2 = n1 / 4;

            top1 = n2;

            top2 = n2 * 2;

            Font f;

            Brush b;

            int cindex, findex;

            //随机字体和颜色的验证码字符

            for (int i = 0; i < code.Length; i++)

            {

                cindex = rand.Next(Colors.Length - 1);

                findex = rand.Next(Fonts.Length - 1);

                f = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);

                b = new System.Drawing.SolidBrush(Colors[cindex]);

                if (i % 2 == 1)

                {

                    top = top2;

                }

                else

                {

                    top = top1;

                }

                left = i * fWidth;

                g.DrawString(code.Substring(i, 1), f, b, left, top);

            }

            //画一个边框 边框颜色为Color.Gainsboro

            g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);

            g.Dispose();

            //产生波形(Add By 51aspx.com)

            image = TwistImage(image, true, 4, 4);

            return image;

        }

        #endregion

        #region 将创建好的图片输出到页面

        public void CreateImageOnPage(string code, HttpContext context)

        {

            Response.BufferOutput = true; //特别注意

            Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));//特别注意

            Response.Cache.SetCacheability(HttpCacheability.NoCache);//特别注意

            Response.AppendHeader("Pragma", "No-Cache"); //特别注意

            MemoryStream ms = new MemoryStream();

            Bitmap image = this.CreateImageCode(code);

            image.Save(ms, ImageFormat.Jpeg);

            Response.ClearContent();

            Response.ContentType = "image/JPEG";

            Response.BinaryWrite(ms.ToArray());

            Response.End();

            ms.Close();

            ms = null;

            image.Dispose();

            image = null;

        }

        #endregion

        #region 生成随机字符码

        public string CreateVerifyCode(int codeLen)

        {

            if (codeLen == 0)

            {

                codeLen = Length;

            }

            string[] arr = CodeSerial.Split(',');

            string code = "";

            int randValue = -1;

            Random rand = new Random(unchecked((int)DateTime.Now.Ticks));

            for (int i = 0; i < codeLen; i++)

            {

                randValue = rand.Next(0, arr.Length - 1);

                code += arr[randValue];

            }

            return code;

        }

        public string CreateVerifyCode()

        {

            return CreateVerifyCode(0);

        }

        #endregion

        #region 另一种验证码样式 GenerateVerifyImage(int length)

        /// <summary>

        /// 将创建好的图片输出到页面

        /// </summary>

        public void GenerateVerifyImage(int nLen)

        {

            string validateCode = "";//生成的验证码

            int nBmpWidth = GetImagewidth(nLen);

            int nBmpHeight = GetImageHeight();

            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(nBmpWidth, nBmpHeight);

            //对图像进行弯曲

            TwistImage(bmp, true, 12, 2);



            // 1. 生成随机背景颜色

            int nRed, nGreen, nBlue; // 背景的三元色

            System.Random rd = new Random((int)System.DateTime.Now.Ticks);

            nRed = rd.Next(255) % 128 + 128;

            nGreen = rd.Next(255) % 128 + 128;

            nBlue = rd.Next(255) % 128 + 128;

            // 2. 填充位图背景

            System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(bmp);

            graph.FillRectangle(new SolidBrush(System.Drawing.Color.FromArgb(nRed, nGreen, nBlue))

            , 0

            , 0

            , nBmpWidth

            , nBmpHeight);



            // 3. 绘制干扰线条,采用比背景略深一些的颜色

            int nLines = 3;

            System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.FromArgb(nRed - 17, nGreen - 17, nBlue - 17), 2);

            for (int a = 0; a < nLines; a++)

            {

                int x1 = rd.Next() % nBmpWidth;

                int y1 = rd.Next() % nBmpHeight;

                int x2 = rd.Next() % nBmpWidth;

                int y2 = rd.Next() % nBmpHeight;

                graph.DrawLine(pen, x1, y1, x2, y2);

            }

            // 采用的字符集,可以随即拓展,并可以控制字符出现的几率

            string strCode = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

            // 4. 循环取得字符,并绘制

            for (int i = 0; i < nLen; i++)

            {

                int x = (i * 13 + rd.Next(3));

                int y = rd.Next(4) + 1;

                // 确定字体

                System.Drawing.Font font = new System.Drawing.Font("Courier New",//文字字体类型

                12 + rd.Next() % 4,//文字字体大小

                System.Drawing.FontStyle.Bold);//文字字体样式

                char c = strCode[rd.Next(strCode.Length)]; // 随机获取字符

                validateCode += c.ToString();

                // 绘制字符

                graph.DrawString(c.ToString(),

                font,

                new SolidBrush(System.Drawing.Color.FromArgb(nRed - 60 + y * 3, nGreen - 60 + y * 3, nBlue - 40 + y * 3)),

                x,

                y);

            }

            Session["ValidateCode"] = validateCode;

            //对图像进行弯曲

            TwistImage(bmp, true, 4, 4);

            Response.BufferOutput = true; //特别注意

            Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));//特别注意

            Response.Cache.SetCacheability(HttpCacheability.NoCache);//特别注意

            Response.AppendHeader("Pragma", "No-Cache"); //特别注意

            // 5. 输出字节流

            MemoryStream bstream = new MemoryStream();

            bmp.Save(bstream, ImageFormat.Jpeg);

            Response.ClearContent();

            Response.ContentType = "image/JPEG";

            Response.BinaryWrite(bstream.ToArray());

            Response.End();

            bstream.Close();

            bstream = null;

            bmp.Dispose();

            bmp = null;

            graph.Dispose();

        }

        ///<summary>

        ///得到验证码图片的宽度

        ///</summary>

        ///<paramname="validateNumLength">验证码的长度</param>

        ///<returns></returns>

        public static int GetImagewidth(int validateNumLength)

        {

            return (int)(13 * validateNumLength + 5);

        }

        ///<summary>

        ///得到验证码的高度

        ///</summary>

        ///<returns></returns>

        public static int GetImageHeight()

        {

            return 25;

        }

        #endregion

    }

}



-------------------------------------------------

<script  language="javascript" type="text/javascript">

            function DoFresh() {

                var verify = document.getElementById("Image1");

                verify.setAttribute('src', 'Validator.aspx');

                

            } 

        </script>

</head>

<body>

    <form id="form1" runat="server">

    <div>验证码:<asp:TextBox runat="server" vf="require" ID="txtValidator"></asp:TextBox><asp:Image ID="Image1" runat="server" />

<a href="javascript:DoFresh()">看不清,换一张</a> 

 

 

因为代码较为经典,所以把它写一遍。供大家分享

注意,因为我是手打的,有些东西写的不完备。

 

另一版本

using System;

using System.Collections;

using System.Text;

using System.Web;

using System.Drawing;

using System.Web.Caching;

using System.Threading;

using System.Configuration;

using System.Collections.Specialized;

using System.Xml;

using System.IO;



namespace ICS.FacadeClass

{

    /// <summary>

    /// 验证码的生成处理类

    /// zhangqs

    /// 2007-11-16

    /// </summary>

    public class VerifyCode

    {

        #region 变量定义

        private int maxLength = 4;

        private int minLength = 4;

        private string SessionKey = "";

        #endregion



        #region 构造函数

        /// <summary>

        /// 构造函数,支持动态个数字符,若固定字符数,则min=max

        /// </summary>

        /// <param name="minLen"></param>

        /// <param name="maxLen"></param>

        public VerifyCode(int minLen, int maxLen, string sessionKey)

        {

            this.SessionKey = sessionKey;

            this.maxLength = maxLen;

            this.minLength = minLen;

            //生成验证码

            this.Code = createVerifyCode();

        }



        /// <summary>

        /// 构造函数,支持动态个数字符,若固定字符数,则min=max

        /// </summary>

        /// <param name="minLen"></param>

        /// <param name="maxLen"></param>

        public VerifyCode(int minLen, int maxLen)

        {

            this.SessionKey = "";

            this.maxLength = maxLen;

            this.minLength = minLen;

            //生成验证码

            this.Code = createVerifyCode();

        }

        #endregion



        #region 自定义随机码字符串序列(使用逗号分隔)

        string codeSerial = "3,4,5,6,7,8,A,B,C,E,F,H,K,M,P,Q,R,S,T,U,V,W,X,Y,a,b,c,d,e,f,h,k,m,p,q,s,t,u,v,w,x,y";

        public string CodeSerial

        {

            get { return codeSerial; }

            set { codeSerial = "3,4,5,6,7,8,A,B,C,E,F,H,K,M,P,Q,R,S,T,U,V,W,X,Y,a,b,c,d,e,f,h,k,m,p,q,s,t,u,v,w,x,y"; }

        }

        #endregion



        #region 生成随机字符码

        /// <summary>

        /// 生成随机字符码

        /// </summary>

        /// <returns></returns>

        private string createVerifyCode()

        {

            //int len = this.minLength;

            Random rand = new Random(unchecked((int)DateTime.Now.Ticks));

            //if (this.maxLength > this.minLength)

            //{

            //    len = rand.Next(this.minLength, this.maxLength + 1);

            //}



            //都用4字符

            int len = 4;

            string[] arr = CodeSerial.Split(',');

            string code = "";

            int randValue = -1;

            for (int i = 0; i < len; i++)

            {

                randValue = rand.Next(0, arr.Length - 1);



                code += arr[randValue];

            }

            return  code;

        }

        #endregion



        #region 验证码的值

        private string _Code;

        /// <summary>

        /// 验证码的值

        /// </summary>

        public string Code

        {

            get { return _Code; }

            set { _Code = value; }

        }

        #endregion



        #region 将创建好的图片输出到页面

        public void CreateImageOnPage(HttpContext context)

        {

            #region 对调用页进行校验

            System.Web.UI.Page page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;

            if (SessionKey != "")

            {

                if (!this.IsCheckReferer)

                {

                    page.Session[SessionKey] = this.Code;

                }

                else

                {

                    if (this.MyDomain != this.RefererDomain)

                    {

                        page.Session[SessionKey] = System.Guid.NewGuid().ToString();

                        page.Response.End();

                        return;

                    }

                    else

                    {

                        page.Session[SessionKey] = this.Code;

                    }

                }

            }

            #endregion

            Bitmap image = null;



            try

            {

                VerifyImg oVerifyImg = new VerifyImg();

                image = oVerifyImg.CreateImageCode(this.Code);

            }

            catch

            {

                page.Session[SessionKey] = System.Guid.NewGuid().ToString();

                page.Response.End();

            }





            System.IO.MemoryStream srMS = new System.IO.MemoryStream();

            image.Save(srMS, System.Drawing.Imaging.ImageFormat.Png);

            context.Response.ClearContent();

            context.Response.ContentType = "image/Png";

            context.Response.BinaryWrite(srMS.ToArray());

            if (srMS != null)

            {

                srMS.Close();

                srMS = null;

            }

            if (image != null)

            {

                image.Dispose();

                image = null;

            }

        }

        #endregion



        #region 校验用变量



        #region 是否对来源页面进行校验

        private bool _IsCheckReferer = false;

        /// <summary>

        /// 是否对来源页面进行校验

        /// </summary>

        public bool IsCheckReferer

        {

            get

            {

                return _IsCheckReferer;

            }

            set

            {

                _IsCheckReferer = true;

            }

        }

        #endregion



        #region 来源页面的url

        /// <summary>

        /// 来源页面的url

        /// </summary>

        private string RefererUrl

        {

            get

            {

                try

                {

                    string str = "";

                    System.Web.UI.Page page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;

                    object obj = page.Request.UrlReferrer;

                    str = obj == null ? "" : obj.ToString().Trim().ToLower();

                    if (str != "")

                    {

                        if (str.IndexOf("?") != -1)

                        {

                            string[] strA = str.Split('?');

                            str = strA[0];

                        }

                    }

                    return str;

                }

                catch { return ""; }

            }

        }

        #endregion



        #region 来源页面的域名

        /// <summary>

        /// 来源页面的域名

        /// </summary>

        private string RefererDomain

        {

            get

            {

                try

                {

                    string url = RefererUrl;

                    if (url == "") { return ""; }

                    if (url.Length >= 7)

                    {

                        url = url.Substring(7, url.Length - 7);

                    }

                    int index = url.IndexOf("/");

                    if (index != -1)

                    {

                        url = url.Substring(0, index);

                    }

                    return url;

                }

                catch { return ""; }

            }

        }

        #endregion



        #region 本页面的url



        /// <summary>

        /// 本页面的url

        /// </summary>

        private string MyUrl

        {

            get

            {

                try

                {

                    System.Web.UI.Page page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;

                    object obj = page.Request["PATH_INFO"];

                    string str = obj == null ? "" : obj.ToString().Trim().ToLower();

                    if (str != "")

                    {

                        if (str.IndexOf("?") != -1)

                        {

                            string[] strA = str.Split('?');

                            str = strA[0];

                        }

                    }

                    return "http://" + MyDomain + str;

                }

                catch { return ""; }

            }

        }



        #endregion



        #region 本页面域名

        /// <summary>

        /// 本页面域名

        /// </summary>

        private string MyDomain

        {

            get

            {

                try

                {

                    System.Web.UI.Page page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;

                    object obj = page.Request["SERVER_NAME"];

                    return obj == null ? "" : obj.ToString().Trim().ToLower();

                }

                catch { return ""; }

            }

        }

        #endregion



        #endregion



        #region 校验验证码是否通过

        /// <summary>

        /// 校验验证码是否通过

        /// </summary>

        /// <param name="sessionKey">SessionKey</param>

        /// <param name="InputCode">要校验的验证码</param>

        /// <returns>是否通过</returns>

        public static bool CheckIsPass(string sessionKey, string InputCode, out string Msg)

        {

            if ((InputCode == null) || (InputCode == string.Empty) || (InputCode.Trim() == ""))

            {

                Msg = "验证码为空!";

                return false;

            }

            InputCode = InputCode.Trim();

            InputCode = InputCode.ToUpper();

            System.Web.UI.Page page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;

            object oSession = page.Session[sessionKey];

            if (oSession == null)

            {

                Msg = "验证码超时!";

                return false;

            }

            string sSession = oSession == null ? "" : oSession.ToString();

            sSession = sSession.Trim();

            if (sSession == "")

            {

                Msg = "验证码超时!";

                return false;

            }

            sSession = sSession.ToUpper();

            if (InputCode != sSession)

            {

                Msg = "您输入的验证码不正确,请重新输入!";

                return false;

            }

            Msg = "";

            page.Session[sessionKey] = null;     //通过后,验证码作废

            return true;

        }

        #endregion

    }//ClassEnd



    /// <summary>

    /// 生成验证码图片类

    /// </summary>

    internal class VerifyImg

    {

        private string ConfigFilePath = HttpContext.Current.Server.MapPath("/SystemConfig/SmsSendLimit.xml");



        #region 变量定义

        private int MethodCount = 4;

        private static int iSeed = 0;

        #endregion



        #region 生成校验码图片

        public Bitmap CreateImageCode(string code)

        {



            string Index = "6";

            try

            {

                CachedXmlData XmlData = new CachedXmlData(this.ConfigFilePath);

                Index = XmlData.GetXmlNodeValue("//VerifyCode");

                if (Index == "6")

                {

                    return CreateImageCode_6(code);

                }

                else

                {

                    return CreateImageCode_7(code);

                }

            }

            catch

            {

                return CreateImageCode_6(code);

            }



            ////恢复原来的只有一种算法

            //int MethodIndex = GetCurrentMethodIndex();

            //switch (MethodIndex)

            //{

            //    case 1:

            //        return CreateImageCode_1(code);

            //    case 2:

            //        return CreateImageCode_2(code);

            //    case 3:

            //        return CreateImageCode_3(code);

            //    case 4:

            //        return CreateImageCode_4(code);

            //    default:

            //        return CreateImageCode_4(code);

            //}

        }

        #endregion



        #region 生成校验码图片方法6

        private Bitmap CreateImageCode_6(string Code)

        {

            //定义随即数

            Random Rand = new Random();

            //定义字体颜色

            Color[] Colors ={ Color.Black, Color.Red, Color.DarkBlue, Color.Blue, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };

            //Color[] srColors ={ Color.Black, Color.Black, Color.Black, Color.Black, Color.Black, Color.Black, Color.Black, Color.Black };

            Color UserColor = Colors[Rand.Next(7)];

            //定义字体

            string[] Fonts ={ "Arial Rounded MT Bold", "Baskerville Old Face", "Imprint MT Shadow", "Century Old Style Std", "Arial", " Arial Black", "Plantagenet Cherokee" };//"Verdana", "Microsoft Sans Serif", "Comic Sans MS","Arial", "宋体"

            //那前使用的字体

            Font UserFont = null;

            //字的大小

            int FontSize = 0;

            //前一个字体大小

            int FrontFontSize = 20;

            int PointY = 0;



            Bitmap image = null;

            Graphics Graph = null;



            Brush UserBrush = null;

            try

            {

                //定义图象 

                image = new Bitmap((Code.Length * 20 + 25), 40);

                //画图

                Graph = Graphics.FromImage(image);

                //清空图象

                Graph.Clear(Color.White);

                //给图象画边框

                //Graph.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1);



                //把验证码转换成字符数组

                char[] CharCode = Code.ToCharArray();



                Point UserPoint;



                #region 用于字体弯曲

                //定义图片弯曲的角度

                int Srseedangle = 20;

                float UserAngle;

                //封状文本 用于

                StringFormat srFormat = new StringFormat(StringFormatFlags.NoClip);

                //设置文本垂直居中

                srFormat.Alignment = StringAlignment.Center;

                //设置文本水平居中

                srFormat.LineAlignment = StringAlignment.Center;

                #endregion



                #region 生成弯线

                Pen UserPen = new Pen(UserColor);

                //线的大小

                Double RandDouble = Rand.NextDouble();

                if (RandDouble > 0.5)

                {

                    RandDouble = RandDouble - 0.5;

                }

                UserPen.Width = (float)(2 + RandDouble);

                int ImgHeight = image.Height;

                int ImgWidth = image.Width;



                int RandomPoint = 10;



                Point[] Points = new Point[RandomPoint];



                int RandomLength = ImgWidth / RandomPoint;

                int TempPointX = 0;



                for (int i = 0; i < RandomPoint; i++)

                {



                    TempPointX = Rand.Next((RandomLength * i) + (RandomLength / 5), (RandomLength * (i + 1)) - (RandomLength / 5));

                    Points[i] = new Point(TempPointX, Rand.Next(12, ImgHeight - 12));

                }



                Graph.DrawBeziers(UserPen, Points);



                #endregion



                for (int i = 0, j = CharCode.Length; i < j; i++)

                {

                    //定义字体 参数分别为字体样式 字体大小 字体字形

                    FontSize = Rand.Next(26, 28);

                    UserFont = new Font(Fonts[Rand.Next(Fonts.Length)], FontSize, FontStyle.Bold);



                    PointY = 22;// Rand.Next(22, 22);



                    //填充图形

                    UserBrush = new SolidBrush(UserColor);



                    //定义坐标

                    UserPoint = new Point(FrontFontSize - 4, PointY);

                    FrontFontSize = FontSize;



                    //定义倾斜角度

                    UserAngle = Rand.Next(-Srseedangle, Srseedangle);

                    ////倾斜

                    Graph.TranslateTransform(UserPoint.X, UserPoint.Y, System.Drawing.Drawing2D.MatrixOrder.Append);

                    Graph.RotateTransform(UserAngle);

                    //填充字符

                    Graph.DrawString(CharCode[i].ToString(), UserFont, UserBrush, 1, 1, srFormat);

                    //Graph.DrawString(CharCode[i].ToString(), UserFont, UserBrush, FrontFontSize, 1);

                    ////回归正常

                    Graph.RotateTransform(-UserAngle);

                    Graph.TranslateTransform(-1, -UserPoint.Y, System.Drawing.Drawing2D.MatrixOrder.Append);

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

            finally

            {



                if (Graph != null)

                {

                    Graph.Dispose();

                    Graph = null;

                }

                if (UserFont != null)

                {

                    UserFont.Dispose();

                    UserFont = null;

                }

                if (UserBrush != null)

                {

                    UserBrush.Dispose();

                    UserBrush = null;

                }

            }



            return image;

        }

        #endregion



        #region 生成校验码图片方法7

        private Bitmap CreateImageCode_7(string Code)

        {



            //定义随即数

            Random Rand = new Random();

            //定义字体颜色

            Color[] Colors ={ Color.Black, Color.Red, Color.DarkBlue, Color.Blue, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };

            //Color[] srColors ={ Color.Black, Color.Black, Color.Black, Color.Black, Color.Black, Color.Black, Color.Black, Color.Black };

            Color UserColor = Colors[Rand.Next(7)];

            //定义字体

            string[] Fonts ={ "Arial Rounded MT Bold", "Baskerville Old Face", "Imprint MT Shadow", "Century Old Style Std", "Arial", " Arial Black", "Plantagenet Cherokee" };

            //那前使用的字体

            Font UserFont = null;

            //字的大小

            int FontSize = 0;

            //前一个字体大小

            int FrontFontSize = 20;

            int PointY = 0;



            Bitmap image = null;

            Graphics Graph = null;



            Brush UserBrush = null;

            try

            {

                //定义图象 

                image = new Bitmap((Code.Length * 20 + 25), 40);

                //画图

                Graph = Graphics.FromImage(image);

                //清空图象

                Graph.Clear(Color.White);

                ////给图象画边框

                //Graph.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1);



                //把验证码转换成字符数组

                char[] CharCode = Code.ToCharArray();



                Point UserPoint;



                #region 用于字体弯曲

                //定义图片弯曲的角度

                int Srseedangle = 15;

                float UserAngle;

                //封状文本 用于

                StringFormat srFormat = new StringFormat(StringFormatFlags.NoClip);

                //设置文本垂直居中

                srFormat.Alignment = StringAlignment.Center;

                //设置文本水平居中

                srFormat.LineAlignment = StringAlignment.Center;

                #endregion



                #region 生成弯线

                Pen UserPen = new Pen(UserColor);

                //线的大小

                Double RandDouble = Rand.NextDouble();

                if (RandDouble > 0.5)

                {

                    RandDouble = RandDouble - 0.5;

                }

                UserPen.Width = (float)(2 + RandDouble);

                int ImgHeight = image.Height;

                int ImgWidth = image.Width;

                int RandomPoint = 10;



                Point[] Points = new Point[RandomPoint];



                int RandomLength = ImgWidth / RandomPoint;

                int TempPointX = 0;



                for (int i = 0; i < RandomPoint; i++)

                {



                    TempPointX = Rand.Next((RandomLength * i), (RandomLength * (i + 1)));

                    Points[i] = new Point(TempPointX, Rand.Next(5, ImgHeight - 5));

                }



                Graph.DrawBeziers(UserPen, Points);



                #endregion





                for (int i = 0, j = CharCode.Length; i < j; i++)

                {

                    //定义字体 参数分别为字体样式 字体大小 字体字形

                    FontSize = Rand.Next(26, 26);

                    UserFont = new Font(Fonts[Rand.Next(Fonts.Length)], FontSize, FontStyle.Regular);



                    PointY = Rand.Next(20, 24);



                    //填充图形

                    UserBrush = new SolidBrush(UserColor);



                    //定义坐标

                    UserPoint = new Point(FrontFontSize - 5, PointY);

                    FrontFontSize = FontSize;



                    //定义倾斜角度

                    UserAngle = Rand.Next(-Srseedangle, Srseedangle);

                    //倾斜

                    Graph.TranslateTransform(UserPoint.X, UserPoint.Y);

                    Graph.RotateTransform(UserAngle);

                    //填充字符

                    Graph.DrawString(CharCode[i].ToString(), UserFont, UserBrush, 1, 1, srFormat);

                    //回归正常

                    Graph.RotateTransform(-UserAngle);

                    Graph.TranslateTransform(1, -UserPoint.Y);

                }



                //产生波形(Add By 51aspx.com)

                image = TwistImage(image, true, Rand.NextDouble(), Rand.NextDouble());

            }

            catch (Exception ex)

            {

                throw ex;

            }

            finally

            {



                if (Graph != null)

                {

                    Graph.Dispose();

                    Graph = null;

                }

                if (UserFont != null)

                {

                    UserFont.Dispose();

                    UserFont = null;

                }

                if (UserBrush != null)

                {

                    UserBrush.Dispose();

                    UserBrush = null;

                }

            }



            return image;

        }

        #endregion



        #region 生成校验码图片方法五



        #region 获得图片所在目录地址



        /// <summary>

        /// 获得图片所在目录地址

        /// </summary>

        /// <returns></returns>

        private string GetImagePath()

        {

            NameValueCollection appSettings = System.Configuration.ConfigurationSettings.AppSettings;



            //Server.MapPath(

            if (appSettings != null)

            {

                try

                {

                    return System.Web.HttpContext.Current.Server.MapPath("/CodeImagePath/");

                    //return appSettings["CodeImagePath"].Trim();

                }

                catch

                {

                    return null;

                }

            }

            else

            {

                return null;

            }



        }

        #endregion



        #region 自定义随机码字符串序列 转成字符数组

        /// <summary>

        /// 自定义随机码字符串序列 转成字符数组

        /// </summary>

        /// <returns></returns>

        private char[] CodeSerialToChar()

        {

            string[] StrArr = new VerifyCode(1, 1).CodeSerial.Split(',');

            char[] CharArr = new char[StrArr.Length];

            for (int i = 0; i < StrArr.Length; i++)

            {

                CharArr[i] = Convert.ToChar(StrArr[i]);

            }

            return CharArr;

        }

        #endregion



        



        #region 缓存图片 如果改变图片 同时请修改RemoveCache.txt

        /// <summary>

        /// 缓存图片 如果改变图片 同时请修改RemoveCache.txt

        /// </summary>

        private void CacheImage(string CacheKey, ArrayList Image)

        {

            string ImagePath = GetImagePath();

            if (ImagePath != null)

            {

                HttpRuntime.Cache.Insert(CacheKey, Image, new CacheDependency(ImagePath + "\\RemoveCache.txt"));

                //HttpRuntime.Cache.Insert(CacheKey, Image, new CacheDependency(GetImagePath+"\\RemoveCache.txt"), DateTime.Now.AddMonths(1), Cache.NoSlidingExpiration, CacheItemPriority.Default, new CacheItemRemovedCallback(onRemove));

        

            }



        }

        #endregion



        #region 获得所有图片

        /// <summary>

        /// 获得所有图片

        /// </summary>

        /// <returns></returns>

        private ArrayList GetImage()

        {

            string VerifyCodeCacheKey = "VerifyCode_Cache_Image_Key";



            ArrayList ListImage = HttpRuntime.Cache[VerifyCodeCacheKey] as ArrayList;

            if (ListImage != null && ListImage.Count > 0)

            {

                return ListImage;

            }

            else

            {

                ListImage = new ArrayList();

                char[] CodeArr = CodeSerialToChar();

                string ImagePath;

                for (int i = 0; i < CodeArr.Length; i++)

                {

                    try

                    {



                        if (CodeArr[i] >= 65 && CodeArr[i] <= 90)

                        {

                            ImagePath = GetImagePath() + "U" + CodeArr[i] + ".gif";

                        }

                        else

                        {

                            ImagePath = GetImagePath() + CodeArr[i] + ".gif";

                        }

                        ListImage.Insert(i, new Bitmap(ImagePath));

                    }

                    catch

                    {

                    }

                }

                if (ListImage != null && ListImage.Count > 0)

                {

                    CacheImage(VerifyCodeCacheKey, ListImage);

                }



                return ListImage;

            }

        }

        #endregion





        #region 生成校验码图片

        /// <summary>

        /// 生成校验码图片

        /// </summary>

        /// <param name="Code"></param>

        /// <returns></returns>

        private Bitmap CreateImageCode_5(string Code)

        {

            Random Ran = new Random(unchecked((int)DateTime.Now.Ticks));

            Bitmap Image = new Bitmap((Code.Length * 20 + 12), 30);

            Graphics Graph = Graphics.FromImage(Image);

            Graph.Clear(Color.White);



            float Str_x;

            float Str_y;

            ArrayList ListImage = GetImage();

            char[] CodeArr = CodeSerialToChar();

            if (ListImage != null && ListImage.Count > 0)

            {

                for (int i = 0; i < Code.Length; i++)

                {

                    for (int j = 0; j < CodeArr.Length; j++)

                    {

                        if (CodeArr[j] == Code[i])

                        {

                            Str_x = (i * 20 + 6);

                            Str_y = Ran.Next(9) + (float)Ran.NextDouble();

                            Graph.DrawImage((Image)ListImage[j], Str_x, Str_y);

                            break;

                        }

                    }

                }

            }



            return Image;

        }

        #endregion



        #endregion



        #region 生成校验码图片方法四

        private Bitmap CreateImageCode_4(string code)

        {

            Random rnd;

            rnd = new Random(unchecked((int)DateTime.Now.Ticks));

            int fSize = 14;

            int Padding = 2;

            int fWidth = fSize + Padding;



            int imageWidth = (int)(code.Length * fWidth) + 4 + Padding * 2;

            int imageHeight = fSize * 2 + Padding * 1 - 5;



            System.Drawing.Bitmap image = new Bitmap(imageWidth, imageHeight);



            Graphics g = Graphics.FromImage(image);



            g.Clear(Color.White);



            #region 给背景添加随机生成的燥点

            Color ChaosColor = Color.LightGray;   //燥点的颜色(默认灰色)

            Pen pen = new Pen(ChaosColor, 0);

            int Length = code.Length;

            int c = Length * 30;

            for (int i = 0; i < c; i++)

            {

                int x = rnd.Next(image.Width);

                int y = rnd.Next(image.Height);

                g.DrawRectangle(pen, x, y, 1, 1);

            }

            #endregion



            int left = 0, top = 0, top1 = 1, top2 = 1;

            int n1 = (imageHeight - fSize - Padding * 2);

            int n2 = n1 / 4;

            top1 = n2;

            top2 = n2 * 3;

            Font f;

            Brush b;



            int cindex, findex;

            string[] Fonts ={ "Arial", "Georgia" };

            Color[] Colors ={ Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };



            for (int i = 0; i < Length; i++)

            {

                cindex = rnd.Next(Colors.Length - 1);

                findex = rnd.Next(Fonts.Length - 1);

                f = new Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);

                b = new System.Drawing.SolidBrush(Colors[cindex]);

                if (i % 2 == 1)

                {

                    top = top2;

                }

                else

                {

                    top = top1;

                }

                left = i * fWidth;

                g.DrawString(code.Substring(i, 1), f, b, left, top);

            }

            //画一个边框 边框颜色为Color.Gainsboro

            g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);

            g.Dispose();

            image = TwistImage(image, true, 4, 2);

            return image;

        }



        #region 产生波形滤镜效果

        private const double PI = 3.1415926535897932384626433832795;

        private const double PI2 = 6.283185307179586476925286766559;

        /// <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>

        private 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.FillRectangle(new SolidBrush(System.Drawing.Color.AliceBlue), 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;

        }

        #endregion



        #endregion



        #region 生成校验码图片方法三

        private Bitmap CreateImageCode_3(string code)

        {

            int iwidth = (int)(code.Length * 15);

            Bitmap image = new Bitmap(iwidth, 20);

            Graphics g = Graphics.FromImage(image);

            g.Clear(Color.White);

            Random random = new Random();

            //画图片的背景噪音线

            for (int i = 0; i < 100; 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.LightGray), x1, y1, x2, y2);

            }

            Font font = new Font("Arial", 15, FontStyle.Bold | FontStyle.Italic);

            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(

                new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.Gray, 1.2f, true);

            g.DrawString(code, font, brush, 0, 0);

            //画图片的前景噪音点

            for (int i = 0; i < 10; i++)

            {

                int x = random.Next(image.Width);

                int y = random.Next(image.Height);

                image.SetPixel(x, y, Color.LightYellow);

            }

            //画图片的边框线

            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

            g.DrawLine(new Pen(GetRandomColor()), 0, 0, iwidth, 20);

            g.DrawLine(new Pen(GetRandomColor()), 0, 20, iwidth, 0);



            g.DrawLine(new Pen(GetRandomColor()), iwidth / 2, 0, iwidth / 2, 20);



            g.DrawLine(new Pen(GetRandomColor()), 0, 10, iwidth, 10);



            return image;

        }

        #endregion



        #region 生成校验码图片方法二

        private Bitmap CreateImageCode_2(string checkCode)

        {

            int iwidth = (int)(checkCode.Length * 14);

            System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 25);

            Graphics g = Graphics.FromImage(image);

            g.Clear(Color.AliceBlue);

            #region 定义颜色

            Color[] c = {

                Color.Black,

                Color.Red,

                Color.DarkBlue,

                Color.Green,

                Color.Orange,

                Color.Brown,

                Color.DarkCyan,

                Color.Purple,

            };

            #endregion



            #region 定义字体

            string[] font = { 

                "Verdana",

                "Microsoft Sans Serif",

                "Comic Sans MS",

                "Arial",

                "宋体" 

            };

            #endregion



            Random rand = new Random();



            #region 随机输出噪点

            for (int i = 0; i < 10; i++)

            {

                int x = rand.Next(image.Width);

                int y = rand.Next(image.Height);

                g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);

            }

            #endregion



            #region 输出不同字体和颜色的验证码字符

            for (int i = 0; i < checkCode.Length; i++)

            {

                int cindex = rand.Next(7);

                int findex = rand.Next(5);

                Font f = new Font(font[findex], 13, System.Drawing.FontStyle.Italic);

                Brush b = new System.Drawing.SolidBrush(GetRandomColor());

                int ii = 2;

                if ((i + 1) % 2 == 0)

                {

                    ii = 4;

                }

                g.DrawString(checkCode.Substring(i, 1), f, b, 3 + (i * 12), ii);

            }

            #endregion



            image = TwistImage(image, true, -4, -1);

            g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1);

            return image;

        }

        #endregion



        #region 生成校验码图片方法一

        private Bitmap CreateImageCode_1(string code)

        {

            //定义图片弯曲的角度

            int srseedangle = 45;

            //定义字体颜色

            // Color[] srColors ={ Color.Black, Color.Red, Color.DarkBlue, Color.Blue, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };

            Color[] srColors ={ Color.Black, Color.Black, Color.Black, Color.Black, Color.Black, Color.Black, Color.Black, Color.Black };

            //定义字体

            string[] srFonts ={ "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };

            Bitmap image = null;

            Graphics g = null;

            Pen srPen = null;

            Font srFont = null;

            Brush srBrush = null;

            try

            {

                //定义图象 

                image = new Bitmap((code.Length * 20 + 12), 30);

                //画图

                g = Graphics.FromImage(image);

                //清空图象

                g.Clear(Color.AliceBlue);

                //给图象画边框

                g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1);

                //定义随即数

                Random rand = new Random();

                //定义画笔

                srPen = new Pen(Color.LightGray, 0);

                ////画噪点

                //for (int i = 0; i < 100; i++)

                //{

                //    g.DrawRectangle(srPen, rand.Next(1, image.Width - 2), rand.Next(1, image.Height - 2), 1, 1);

                //}

                //将字符串转化为字符数组 

                char[] srchars = code.ToCharArray();

                //封状文本

                StringFormat srFormat = new StringFormat(StringFormatFlags.NoClip);

                //设置文本垂直居中

                srFormat.Alignment = StringAlignment.Center;

                //设置文本水平居中

                srFormat.LineAlignment = StringAlignment.Center;



                //循环画出每个字符              

                int pading = 0; // 间隔



//                bool isJoin = false; //是否重叠

                int lastSize = 15;

                int sz = 15;

                Color lastColor = Color.Blue;

                Color c = Color.Blue;

                for (int i = 0, j = srchars.Length; i < j; i++)

                {

                    //pading = rand.Next(-6, 6);

                    pading = 2;

                    sz = 18;

                    ////定义字体 参数分别为字体样式 字体大小 字体字形

                    //if (i == j - 2 && !isJoin) //倒数第二个没有重叠的话,则设置为大字体,保证重叠

                    //{                       

                    //    sz = 20;

                    //}

                    //else

                    //{

                    //    sz = rand.Next(15, 20); 

                    //}

                    c = srColors[rand.Next(7)];

                    //定义字体 参数分别为字体样式 字体大小 字体字形

                    srFont = new Font(srFonts[rand.Next(5)], sz, FontStyle.Regular);



                    /////如果上一个字是14号,那么下一字向左入侵保证重叠

                    ////对大字号重叠的可视性要比小字号强.

                    ////重叠时最好将当前字符的颜色设为上一字符颜色

                    //if (lastSize == 20)

                    //{

                    //    c = lastColor;

                    //    isJoin = true;

                    //    pading = -5;

                    //}



                    //填充图形

                    srBrush = new SolidBrush(c);



                    lastColor = c;

                    lastSize = sz;

                    //定义坐标

                    Point srPoint = new Point(16 + pading, 16);

                    //定义倾斜角度

                    float srangle = rand.Next(-srseedangle, srseedangle);

                    //倾斜

                    g.TranslateTransform(srPoint.X, srPoint.Y);

                    g.RotateTransform(srangle);

                    //填充字符

                    g.DrawString(srchars[i].ToString(), srFont, srBrush, 1, 1, srFormat);

                    //回归正常

                    g.RotateTransform(-srangle);

                    g.TranslateTransform(2, -srPoint.Y);

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

            finally

            {



                if (g != null)

                {

                    g.Dispose();

                    g = null;

                }

                if (srPen != null)

                {

                    srPen.Dispose();

                    srPen = null;

                }

                if (srFont != null)

                {

                    srFont.Dispose();

                    srFont = null;

                }

                if (srBrush != null)

                {

                    srBrush.Dispose();

                    srBrush = null;

                }

            }



            return image;

        }

        #endregion



        #region 获取当前方法序号

        /// <summary>

        /// 获取当前方法序号

        /// </summary>

        /// <returns></returns>

        private int GetCurrentMethodIndex()

        {

            if (iSeed == 999999)

            {

                iSeed = 0;

            }

            else

            {

                iSeed = iSeed + 1;

            }



            int randValue = -1;

            int curSeed = unchecked((int)DateTime.Now.Ticks + iSeed);

            //System.Web.HttpContext.Current.Response.Write(iSeed.ToString() + "&nbsp;&nbsp;" + "种子:" + curSeed.ToString() + "<br>");

            Random rand = new Random(curSeed);

            randValue = rand.Next(1, MethodCount + 1);

            return randValue;

        }

        #endregion



        #region 生成随机颜色

        /// <summary>

        /// 生成随机颜色

        /// </summary>

        /// <returns></returns>

        private Color GetRandomColor()

        {

            Random RandomNum_First = new Random((int)DateTime.Now.Ticks);

            System.Threading.Thread.Sleep(RandomNum_First.Next(50));

            Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);

            //  为了在白色背景上显示,尽量生成深色

            int int_Red = RandomNum_First.Next(256);

            int int_Green = RandomNum_Sencond.Next(256);

            int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;

            int_Blue = (int_Blue > 255) ? 255 : int_Blue;

            return Color.FromArgb(int_Red, int_Green, int_Blue);

        }

        #endregion

    }



    ///// <summary>

    ///// 获得XML文件并缓存XML文件

    ///// </summary>

    //public class CachedXmlData

    //{

    //    /// <summary>

    //    /// 用于 文件路径 和缓存Key

    //    /// </summary>

    //    private string ConfigFilePath = "";



    //    public CachedXmlData(string FilePath)

    //    {

    //        this.ConfigFilePath = FilePath;

    //    }



    //    #region  获得XmlDocument 缓存以依赖FilePath

    //    /// <summary>

    //    /// 获得XmlDocument 缓存以依赖FilePath中的文件 

    //    /// </summary>

    //    /// <param name="FilePath">如果为null 用 /SystemConfig/SmsSendLimit.xml</param>

    //    /// <returns></returns>

    //    private XmlDocument GetXmlDoc()

    //    {

    //        XmlDocument XmlDoc = HttpRuntime.Cache[this.ConfigFilePath] as XmlDocument;

    //        if (XmlDoc != null)

    //        {

    //            return XmlDoc;

    //        }

    //        else

    //        {

    //            XmlDoc = new XmlDocument();

    //            try

    //            {

    //                if (File.Exists(ConfigFilePath))

    //                {

    //                    XmlDoc.Load(ConfigFilePath);

    //                    HttpRuntime.Cache.Insert(this.ConfigFilePath, XmlDoc, new CacheDependency(ConfigFilePath));

    //                }

    //            }

    //            catch

    //            {

    //                if (XmlDoc != null)

    //                {

    //                    XmlDoc = null;

    //                }

    //            }



    //            return XmlDoc;

    //        }



    //    }

    //    #endregion



    //    #region 获得Xml指定的路径的值

    //    /// <summary>

    //    /// 获得Xml指定的路径的值

    //    /// </summary>

    //    /// <param name="XPath">Xml Path</param>

    //    /// <returns>string 或 null</returns>

    //    public string GetXmlNodeValue(string XPath)

    //    {

    //        string ReturnValue = null;

    //        XmlDocument XmlDoc = GetXmlDoc();

    //        if (XmlDoc != null)

    //        {

    //            try

    //            {

    //                XmlNode Node = XmlDoc.SelectSingleNode(XPath);

    //                if (Node != null)

    //                {

    //                    ReturnValue = Node.InnerText;

    //                }

    //            }

    //            catch (Exception)

    //            {

    //                ReturnValue = null;

    //            }



    //        }

    //        return ReturnValue;

    //    }

    //    #endregion



    //    #region 获得Xml指定的路径的XmlNodeXmlNodeList

    //    /// <summary>

    //    /// 获得Xml指定的路径的XmlNode

    //    /// </summary>

    //    /// <param name="XPath">Xml Path</param>

    //    /// <returns>XmlNode 或 null</returns>

    //    public XmlNodeList GetXmlNode(string XPath)

    //    {

    //        XmlNodeList ReturnValue = null;

    //        XmlDocument XmlDoc = GetXmlDoc();

    //        if (XmlDoc != null)

    //        {

    //            try

    //            {

    //                ReturnValue = XmlDoc.SelectNodes(XPath);

    //            }

    //            catch

    //            {

    //                ReturnValue = null;

    //            }

    //        }

    //        return ReturnValue;

    //    }

    //    #endregion

    //}



}

 

 

你可能感兴趣的:(验证码)