先看一个核心验证码类(不用在意实现过程,直接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. #region 验证码--方式1
  33. ///  <summary>
  34. ///  验证码--方式1 创建验证码图片
  35. ///  </summary>
  36. ///  <param  name="randomcode">验证码</param>
  37. public byte[] CreateImage(string randomcode)
  38. {
  39. int randAngle = 40; //随机转动角度
  40. int mapwidth = (int)(randomcode.Length * 18);
  41. Bitmap map = new Bitmap(mapwidth, 24);//创建图片背景
  42. Graphics graph = Graphics.FromImage(map);
  43. graph.Clear(Color.White);//清除画面,填充背景
  44. //graph.DrawRectangle(new Pen(Color.Silver, 0), 0, 0, map.Width - 1, map.Height - 1);//画一个边框
  45. Random rand = new Random();
  46. //验证码旋转,防止机器识别
  47. char[] chars = randomcode.ToCharArray();//拆散字符串成单字符数组
  48. //文字距中
  49. StringFormat format = new StringFormat(StringFormatFlags.NoClip);
  50. format.Alignment = StringAlignment.Center;
  51. format.LineAlignment = StringAlignment.Center;
  52. //定义颜色
  53. Color[] c = { Color.Black, Color.Red, Color.Blue, Color.Green,
  54. Color.Orange, Color.Brown, Color.DarkBlue };
  55. //画图片的背景噪音线
  56. for (int i = 0; i < 2; i++)
  57. {
  58. int x1 = rand.Next(10);
  59. int x2 = rand.Next(map.Width - 10, map.Width);
  60. int y1 = rand.Next(map.Height);
  61. int y2 = rand.Next(map.Height);
  62. graph.DrawLine(new Pen(c[rand.Next(7)]), x1, y1, x2, y2);
  63. }
  64. for (int i = 0; i < chars.Length; i++)
  65. {
  66. int cindex = rand.Next(7);
  67. int findex = rand.Next(5);
  68. Font f = new System.Drawing.Font("Arial", 18, System.Drawing.FontStyle.Regular);//字体样式(参数2为字体大小)
  69. Brush b = new System.Drawing.SolidBrush(c[cindex]);
  70. Point dot = new Point(12, 16);
  71. float angle = rand.Next(-randAngle, randAngle);//转动的度数
  72. graph.TranslateTransform(dot.X, dot.Y);//移动光标到指定位置
  73. graph.RotateTransform(angle);
  74. graph.DrawString(chars[i].ToString(), f, b, 1, 1, format);
  75. graph.RotateTransform(-angle);//转回去
  76. graph.TranslateTransform(2, -dot.Y);//移动光标到指定位置
  77. }
  78. //生成图片
  79. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  80. MemoryStream stream = new MemoryStream();
  81. map.Save(stream, ImageFormat.Jpeg);
  82. graph.Dispose();
  83. map.Dispose();
  84. return stream.ToArray();
  85. }
  86. #endregion
  87. #region 验证码--方式2
  88. /// <summary>
  89. /// 验证码--方式2
  90. /// </summary>
  91. /// <param name="chkCode">验证码</param>
  92. /// <returns></returns>
  93. public Byte[] CreateImage2(string chkCode)
  94. {
  95. //颜色列表,用于验证码、噪线、噪点
  96. Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
  97. //字体列表,用于验证码
  98. string[] font = { "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh", "PMingLiU", "Impact" };
  99. Random rnd = new Random();
  100. Bitmap bmp = new Bitmap(100, 40);
  101. Graphics g = Graphics.FromImage(bmp);
  102. g.Clear(Color.White);
  103. //画噪线
  104. for (int i = 0; i < 3; i++)
  105. {
  106. int x1 = rnd.Next(100);
  107. int y1 = rnd.Next(40);
  108. int x2 = rnd.Next(100);
  109. int y2 = rnd.Next(40);
  110. Color clr = color[rnd.Next(color.Length)];
  111. g.DrawLine(new Pen(clr), x1, y1, x2, y2);
  112. }
  113. //画验证码字符串
  114. for (int i = 0; i < chkCode.Length; i++)
  115. {
  116. string fnt = font[rnd.Next(font.Length)];
  117. Font ft = new Font(fnt, 18);
  118. Color clr = color[rnd.Next(color.Length)];
  119. g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 20 + 8, (float)8);
  120. }
  121. //画噪点
  122. for (int i = 0; i < 20; i++)
  123. {
  124. int x = rnd.Next(bmp.Width);
  125. int y = rnd.Next(bmp.Height);
  126. Color clr = color[rnd.Next(color.Length)];
  127. bmp.SetPixel(x, y, clr);
  128. }
  129. MemoryStream ms = new MemoryStream();
  130. try
  131. {
  132. bmp.Save(ms, ImageFormat.Png);
  133. return ms.ToArray();
  134. }
  135. finally
  136. {
  137. //显式释放资源
  138. bmp.Dispose();
  139. g.Dispose();
  140. }
  141. }
  142. #endregion
  143. }
  144. }

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

  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的最原始展示方式)

    1. <img id="yzm" src="/控制器名称/yzm" />
    2. <img id="yzm" src="/控制器名称/yzm2" />

最新文章

  1. [译]Spring构建微服务
  2. Android 隐式意图的配置
  3. SSH框架流程详解
  4. spark之数据源之自动分区推断
  5. 非阻塞同步机制与CAS操作
  6. uvalive 6185
  7. Xcode编译项目出现访问private key提示框
  8. C#中方法,属性与索引器
  9. maven第5章坐标和依赖
  10. JDK6和JDK7中的substring()方法
  11. 5.PHP 教程_PHP echo/print
  12. Codeforces Round #235 (Div. 2) D. Roman and Numbers (数位dp、状态压缩)
  13. feign多文件上传
  14. this应用详解-js原生
  15. ActiveSync中的SendMail
  16. ClientDataSet
  17. HTTP协议(TCP/IP)
  18. 6个讨喜的 ES6 小技巧
  19. 如何通过 iframe 共享 jQuery $.data?
  20. springboot学习入门之四---开发Web应用之Thymeleaf篇

热门文章

  1. junit与spring-data-redis 版本对应成功的
  2. [Angular] Use Angular components in AngularJS applications with Angular Elements
  3. JS将&quot;\/Date(1530104033000)\/&quot; 格式化
  4. 解决Android sdk无法下载的问题
  5. Android Jackson 概述
  6. 使用Filter过滤非法内容
  7. IIS 之 IIS 7及以上多域名或端口绑定同一物理目录并设置不同默认文档
  8. Windows操作系统下的MySQL主从复制及读写分离[转]
  9. linux2.6.30.4内核移植(6)&mdash;&mdash;移植应用程序hello world常见的错误:-bin/sh ./hello not found
  10. Linux内核配置:定制配置选项