验证码

验证码中的其中两种:

前端页面:

1 <li class="yzm">
2                             <input type="text" name="Verify" class="input_text icon_3" placeholder="请输入验证码" />
3                             <span class="yam_pic">
4                                 @*<img src="~/sinoair/img/yzm.png" />*@
5                                 <img style="82px;height:40px;text-align:left;float:left;" src="" id="verify_code_img" onclick="verify()">
6 
7                             </span>
8                         </li>

js:

1 <script type="text/javascript">
2         $(document).ready(function () {
3             $('#verify_code_img').attr('src', '/Login/ShowValidateCode?id=' + Math.random());
4         });
5         function verify() {
6             $('#verify_code_img').attr('src', '/Login/ShowValidateCode?id=' + Math.random());
7         }
8 
9     </script>

控制器:

 1 #region 返回验证码
 2         //返回验证码
 3         [ActionDescription("验证码")]
 4         public ActionResult ShowValidateCode()
 5         {
 6             //string code = new ValidateCode().CreateValidateCode(4);//生成验证码,传几就是几位验证码["verify_code"]
 7             ////Session["verify_code"] = code;   //保存已生成的验证码    
 8             //HttpContext.Session.Set<string>("verify_code", code);
 9             //byte[] buffer = new ValidateCode().CreateValidateGraphic(code);//把验证码画到画布
10 
11             byte[] buffer = GetVerifyCode();
12             return File(buffer, "image/jpeg");//方法二
13             //return File(buffer, "image/jpeg");//方法一
14         }
15 
16         #endregion

验证码方法一:(此方法比较麻烦,样式比较单一,不好看)

  1  #region 创建验证码 方法一
  2 
  3         public class ValidateCode
  4         {
  5             public ValidateCode()
  6             {
  7             }
  8             /// <summary>
  9             /// 验证码的最大长度
 10             /// </summary>
 11             public int MaxLength
 12             {
 13                 get { return 10; }
 14             }
 15             /// <summary>
 16             /// 验证码的最小长度
 17             /// </summary>
 18             public int MinLength
 19             {
 20                 get { return 1; }
 21             }
 22             /// <summary>
 23             /// 生成验证码
 24             /// </summary>
 25             /// <param name="length">指定验证码的长度</param>
 26             /// <returns></returns>
 27             public string CreateValidateCode(int length)
 28             {
 29                 int[] randMembers = new int[length];
 30                 int[] validateNums = new int[length];
 31                 string validateNumberStr = "";
 32                 //生成起始序列值
 33                 int seekSeek = unchecked((int)DateTime.Now.Ticks);
 34                 Random seekRand = new Random(seekSeek);
 35                 int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000);
 36                 int[] seeks = new int[length];
 37                 for (int i = 0; i < length; i++)
 38                 {
 39                     beginSeek += 10000;
 40                     seeks[i] = beginSeek;
 41                 }
 42                 //生成随机数字
 43                 for (int i = 0; i < length; i++)
 44                 {
 45                     Random rand = new Random(seeks[i]);
 46                     int pownum = 1 * (int)Math.Pow(10, length);
 47                     randMembers[i] = rand.Next(pownum, Int32.MaxValue);
 48                 }
 49                 //抽取随机数字
 50                 for (int i = 0; i < length; i++)
 51                 {
 52                     string numStr = randMembers[i].ToString();
 53                     int numLength = numStr.Length;
 54                     Random rand = new Random();
 55                     int numPosition = rand.Next(0, numLength - 1);
 56                     validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1));
 57                 }
 58                 //生成验证码
 59                 for (int i = 0; i < length; i++)
 60                 {
 61                     validateNumberStr += validateNums[i].ToString();
 62                 }
 63                 return validateNumberStr;
 64             }
 65 
 66             /// <summary>
 67             /// 得到验证码图片的长度
 68             /// </summary>
 69             /// <param name="validateNumLength">验证码的长度</param>
 70             /// <returns></returns>
 71             public static int GetImageWidth(int validateNumLength)
 72             {
 73                 return (int)(validateNumLength * 12.0);
 74             }
 75             /// <summary>
 76             /// 得到验证码的高度
 77             /// </summary>
 78             /// <returns></returns>
 79             public static double GetImageHeight()
 80             {
 81                 return 22.5;
 82             }
 83 
 84 
 85 
 86 
 87             //C# MVC 升级版
 88             /// <summary>
 89             /// 创建验证码的图片
 90             /// </summary>
 91             /// <param name="containsPage">要输出到的page对象</param>
 92             /// <param name="validateNum">验证码</param>
 93             public byte[] CreateValidateGraphic(string validateCode)
 94             {
 95                 Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22);
 96                 Graphics g = Graphics.FromImage(image);
 97                 try
 98                 {
 99                     //生成随机生成器
100                     Random random = new Random();
101                     //清空图片背景色
102                     g.Clear(Color.White);
103                     //画图片的干扰线
104                     for (int i = 0; i < 25; i++)
105                     {
106                         int x1 = random.Next(image.Width);
107                         int x2 = random.Next(image.Width);
108                         int y1 = random.Next(image.Height);
109                         int y2 = random.Next(image.Height);
110                         g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
111                     }
112                     Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
113                     LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
114                      Color.YellowGreen, Color.YellowGreen, 1.2f, true);
115                     g.DrawString(validateCode, font, brush, 3, 2);
116                     //画图片的前景干扰点
117                     //for (int i = 0; i < 100; i++)
118                     //{
119                     //    int x = random.Next(image.Width);
120                     //    int y = random.Next(image.Height);
121                     //    image.SetPixel(x, y, Color.FromArgb(random.Next()));
122                     //}
123                     //画图片的边框线
124                     g.DrawRectangle(new Pen(Color.White), 0, 0, image.Width - 1, image.Height - 1);
125                     //保存图片数据
126                     MemoryStream stream = new MemoryStream();
127                     image.Save(stream, ImageFormat.Jpeg);
128                     //输出图片流
129                     return stream.ToArray();
130                 }
131                 finally
132                 {
133                     g.Dispose();
134                     image.Dispose();
135                 }
136             }
137         }
138         #endregion

验证码方法二:(简单好看)

 1  #region 验证码方法二字体彩色
 2         /// <summary>
 3         /// 创建验证码
 4         /// </summary>
 5         /// <returns></returns>
 6         public byte[] GetVerifyCode()
 7         {
 8             int codeW = 80;
 9             int codeH = 30;
10             int fontSize = 16;
11             string chkCode = string.Empty;
12             Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.DarkBlue, Color.PaleGreen };
13             string[] font = { "Times New Roman" };
14             char[] character = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
15             //生成验证码字符串
16             Random rnd = new Random();
17             for (int i = 0; i < 4; i++)
18             {
19                 chkCode += character[rnd.Next(character.Length)];
20             }
21             //写入Session用于验证码校验,可以对校验码进行加密,提高安全性
22             HttpContext.Session.Set<string>("verify_code", chkCode);
23 
24             //创建画布
25             Bitmap bmp = new Bitmap(codeW, codeH);
26             Graphics g = Graphics.FromImage(bmp);
27             g.Clear(Color.Linen);
28 
29             //画噪线
30             for (int i = 0; i < 3; i++)
31             {
32                 int x1 = rnd.Next(codeW);
33                 int y1 = rnd.Next(codeH);
34                 int x2 = rnd.Next(codeW);
35                 int y2 = rnd.Next(codeH);
36 
37                 Color clr = color[rnd.Next(color.Length)];
38                 g.DrawLine(new Pen(clr), x1, y1, x2, y2);
39             }
40             //画验证码
41             for (int i = 0; i < chkCode.Length; i++)
42             {
43                 string fnt = font[rnd.Next(font.Length)];
44                 Font ft = new Font(fnt, fontSize);
45                 Color clr = color[rnd.Next(color.Length)];
46                 g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0);
47             }
48             //将验证码写入图片内存流中,以image/png格式输出
49             MemoryStream ms = new MemoryStream();
50             try
51             {
52                 bmp.Save(ms, ImageFormat.Png);
53                 return ms.ToArray();
54             }
55             catch (Exception ex)
56             {
57                 return null;
58             }
59             finally
60             {
61                 g.Dispose();
62                 bmp.Dispose();
63             }
64         }
65 
66         #endregion 

 

#region创建验证码方法一

 

        publicclassValidateCode

        {

            public ValidateCode()

            {

            }

            ///<summary>

            ///验证码的最大长度

            ///</summary>

            publicint MaxLength

            {

                get { return 10; }

            }

            ///<summary>

            ///验证码的最小长度

            ///</summary>

            publicint MinLength

            {

                get { return 1; }

            }

            ///<summary>

            ///生成验证码

            ///</summary>

            ///<param name="length">指定验证码的长度</param>

            ///<returns></returns>

            publicstring CreateValidateCode(int length)

            {

                int[] randMembers = newint[length];

                int[] validateNums = newint[length];

                string validateNumberStr = "";

                //生成起始序列值

                int seekSeek = unchecked((int)DateTime.Now.Ticks);

                Random seekRand = new Random(seekSeek);

                int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000);

                int[] seeks = newint[length];

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

                {

                    beginSeek += 10000;

                    seeks[i] = beginSeek;

                }

                //生成随机数字

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

                {

                    Random rand = new Random(seeks[i]);

                    int pownum = 1 * (int)Math.Pow(10, length);

                    randMembers[i] = rand.Next(pownum, Int32.MaxValue);

                }

                //抽取随机数字

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

                {

                    string numStr = randMembers[i].ToString();

                    int numLength = numStr.Length;

                    Random rand = new Random();

                    int numPosition = rand.Next(0, numLength - 1);

                    validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1));

                }

                //生成验证码

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

                {

                    validateNumberStr += validateNums[i].ToString();

                }

                return validateNumberStr;

            }

 

            ///<summary>

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

            ///</summary>

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

            ///<returns></returns>

            publicstaticint GetImageWidth(int validateNumLength)

            {

                return (int)(validateNumLength * 12.0);

            }

            ///<summary>

            ///得到验证码的高度

            ///</summary>

            ///<returns></returns>

            publicstaticdouble GetImageHeight()

            {

                return 22.5;

            }

 

 

 

 

            //C# MVC 升级版

            ///<summary>

            ///创建验证码的图片

            ///</summary>

            ///<param name="containsPage">要输出到的page对象</param>

            ///<param name="validateNum">验证码</param>

            publicbyte[] CreateValidateGraphic(string validateCode)

            {

                Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22);

                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 Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));

                    LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),

                     Color.YellowGreen, Color.YellowGreen, 1.2f, true);

                    g.DrawString(validateCode, font, brush, 3, 2);

                    //画图片的前景干扰点

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

                    //保存图片数据

                    MemoryStream stream = new MemoryStream();

                    image.Save(stream, ImageFormat.Jpeg);

                    //输出图片流

                    return stream.ToArray();

                }

                finally

                {

                    g.Dispose();

                    image.Dispose();

                }

            }

        }

        #endregion

原文地址:https://www.cnblogs.com/cfss/p/VerificationCode.html