一个MVC4 下的验证码用法

先看一个核心验证码类(不用在意实现过程,直接copy就行),下面包含了两种验证码图片(原理一样),代码如下:

[csharp] view plain copy
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Drawing;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.IO;  
  8. using System.Drawing.Imaging;  
  9. namespace TyMall.Util  
  10. {  
  11.     public class Yzm : System.Web.UI.Page  
  12.     {  
  13.         #region 生成4个随机数  
  14.         public string RandCode()  
  15.         {  
  16.             int CodeCount = 4;//生成4个随机数  
  17.             string randomChar = "2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z";  
  18.             randomChar = randomChar.Replace(",", "");  
  19.             string RandomCode = "";  
  20.             System.Threading.Thread.Sleep(3);  
  21.             char[] allCharArray = randomChar.ToCharArray();  
  22.             int n = allCharArray.Length;  
  23.             System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));  
  24.             for (int i = 0; i < CodeCount; i++)  
  25.             {  
  26.                 int rnd = random.Next(0, n);  
  27.                 RandomCode += allCharArray[rnd];  
  28.             }  
  29.             return RandomCode;  
  30.         }  
  31.         #endregion  
  32.  
  33.         #region 验证码--方式1  
  34.         ///  <summary>  
  35.         ///  验证码--方式1 创建验证码图片  
  36.         ///  </summary>  
  37.         ///  <param  name="randomcode">验证码</param>  
  38.         public byte[] CreateImage(string randomcode)  
  39.         {  
  40.             int randAngle = 40; //随机转动角度  
  41.             int mapwidth = (int)(randomcode.Length * 18);  
  42.             Bitmap map = new Bitmap(mapwidth, 24);//创建图片背景  
  43.             Graphics graph = Graphics.FromImage(map);  
  44.             graph.Clear(Color.White);//清除画面,填充背景  
  45.             //graph.DrawRectangle(new Pen(Color.Silver, 0), 0, 0, map.Width - 1, map.Height - 1);//画一个边框  
  46.   
  47.             Random rand = new Random();  
  48.   
  49.             //验证码旋转,防止机器识别  
  50.             char[] chars = randomcode.ToCharArray();//拆散字符串成单字符数组  
  51.             //文字距中  
  52.             StringFormat format = new StringFormat(StringFormatFlags.NoClip);  
  53.             format.Alignment = StringAlignment.Center;  
  54.             format.LineAlignment = StringAlignment.Center;  
  55.             //定义颜色  
  56.             Color[] c = { Color.Black, Color.Red, Color.Blue, Color.Green,   
  57.                             Color.Orange, Color.Brown, Color.DarkBlue };  
  58.   
  59.             //画图片的背景噪音线  
  60.             for (int i = 0; i < 2; i++)  
  61.             {  
  62.                 int x1 = rand.Next(10);  
  63.                 int x2 = rand.Next(map.Width - 10, map.Width);  
  64.                 int y1 = rand.Next(map.Height);  
  65.                 int y2 = rand.Next(map.Height);  
  66.   
  67.                 graph.DrawLine(new Pen(c[rand.Next(7)]), x1, y1, x2, y2);  
  68.             }  
  69.   
  70.             for (int i = 0; i < chars.Length; i++)  
  71.             {  
  72.                 int cindex = rand.Next(7);  
  73.                 int findex = rand.Next(5);  
  74.                 Font f = new System.Drawing.Font("Arial", 18, System.Drawing.FontStyle.Regular);//字体样式(参数2为字体大小)  
  75.                 Brush b = new System.Drawing.SolidBrush(c[cindex]);  
  76.                 Point dot = new Point(12, 16);  
  77.                 float angle = rand.Next(-randAngle, randAngle);//转动的度数  
  78.                 graph.TranslateTransform(dot.X, dot.Y);//移动光标到指定位置  
  79.                 graph.RotateTransform(angle);  
  80.                 graph.DrawString(chars[i].ToString(), f, b, 1, 1, format);  
  81.                 graph.RotateTransform(-angle);//转回去  
  82.                 graph.TranslateTransform(2, -dot.Y);//移动光标到指定位置  
  83.             }  
  84.             //生成图片  
  85.             System.IO.MemoryStream ms = new System.IO.MemoryStream();  
  86.             MemoryStream stream = new MemoryStream();  
  87.             map.Save(stream, ImageFormat.Jpeg);  
  88.             graph.Dispose();  
  89.             map.Dispose();  
  90.             return stream.ToArray();  
  91.   
  92.   
  93.         }  
  94.         #endregion  
  95.  
  96.         #region 验证码--方式2  
  97.         /// <summary>  
  98.         /// 验证码--方式2  
  99.         /// </summary>  
  100.         /// <param name="chkCode">验证码</param>  
  101.         /// <returns></returns>  
  102.         public Byte[] CreateImage2(string chkCode)  
  103.         {  
  104.             //颜色列表,用于验证码、噪线、噪点    
  105.             Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };  
  106.             //字体列表,用于验证码    
  107.             string[] font = { "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh", "PMingLiU", "Impact" };   
  108.             Random rnd = new Random();  
  109.             Bitmap bmp = new Bitmap(100, 40);  
  110.             Graphics g = Graphics.FromImage(bmp);  
  111.             g.Clear(Color.White);  
  112.             //画噪线    
  113.             for (int i = 0; i < 3; i++)  
  114.             {  
  115.                 int x1 = rnd.Next(100);  
  116.                 int y1 = rnd.Next(40);  
  117.                 int x2 = rnd.Next(100);  
  118.                 int y2 = rnd.Next(40);  
  119.                 Color clr = color[rnd.Next(color.Length)];  
  120.                 g.DrawLine(new Pen(clr), x1, y1, x2, y2);  
  121.             }  
  122.             //画验证码字符串    
  123.             for (int i = 0; i < chkCode.Length; i++)  
  124.             {  
  125.                 string fnt = font[rnd.Next(font.Length)];  
  126.                 Font ft = new Font(fnt, 18);  
  127.                 Color clr = color[rnd.Next(color.Length)];  
  128.                 g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 20 + 8, (float)8);  
  129.             }  
  130.             //画噪点    
  131.             for (int i = 0; i < 20; i++)  
  132.             {  
  133.                 int x = rnd.Next(bmp.Width);  
  134.                 int y = rnd.Next(bmp.Height);  
  135.                 Color clr = color[rnd.Next(color.Length)];  
  136.                 bmp.SetPixel(x, y, clr);  
  137.             }  
  138.              
  139.             MemoryStream ms = new MemoryStream();  
  140.             try  
  141.             {  
  142.                 bmp.Save(ms, ImageFormat.Png);  
  143.                 return ms.ToArray();  
  144.             }  
  145.             finally  
  146.             {  
  147.                 //显式释放资源    
  148.                 bmp.Dispose();  
  149.                 g.Dispose();  
  150.             }  
  151.         }  
  152.         #endregion  
  153.     }  
  154. }  



然后需要在控制器中实现访问的方式(其实就是写一个action,把生成的image文件返回给view)

[csharp] view plain copy
 
  1. /// <summary>  
  2. /// 验证码,形状一  
  3. /// </summary>  
  4. /// <returns></returns>  
  5. public ActionResult Yzm()  
  6. {  
  7.     TyMall.Util.Yzm sc = new TyMall.Util.Yzm();  
  8.     string vVerificationCode = sc.RandCode();  
  9.     Session["vcode"] = null;  
  10.     Session("vcode", vVerificationCode.ToLower());   //Session中保存验证码    
  11.     sc.CreateImage(vVerificationCode);  
  12.     return File(sc.CreateImage(vVerificationCode), @"image/jpeg");  
  13. }  
  14. /// <summary>  
  15. ///验证码,形状二  
  16. /// </summary>  
  17. /// <returns></returns>  
  18. public ActionResult Yzm2()  
  19. {  
  20.     TyMall.Util.Yzm sc = new TyMall.Util.Yzm();  
  21.     string vVerificationCode = sc.RandCode();  
  22.     Session["vcode"] = null;  
  23.     Session("vcode", vVerificationCode.ToLower());   //Session中保存验证码    
  24.     sc.CreateImage(vVerificationCode);  
  25.     return File(sc.CreateImage2(vVerificationCode), @"image/jpeg");  
  26. }  



view中访问方式(就是image的最原始展示方式)

[html] view plain copy
 
    1. <img id="yzm" src="/控制器名称/yzm" />  
    2. <img id="yzm" src="/控制器名称/yzm2" />  
原文地址:https://www.cnblogs.com/Alex80/p/7743371.html