1. using System;
  2. using System.Web;
  3. using System.Drawing;
  4. using System.Security.Cryptography;
  5.  
  6. namespace MyProject.Common
  7. {
  8. /// <summary>
  9. /// 验证码类
  10. /// </summary>
  11. public class Rand
  12. {
  13. #region 生成随机数字
  14. /// <summary>
  15. /// 生成随机数字
  16. /// </summary>
  17. /// <param name="length">生成长度</param>
  18. public static string Number(int Length)
  19. {
  20. return Number(Length, false);
  21. }
  22.  
  23. /// <summary>
  24. /// 生成随机数字
  25. /// </summary>
  26. /// <param name="Length">生成长度</param>
  27. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  28. public static string Number(int Length, bool Sleep)
  29. {
  30. if (Sleep) System.Threading.Thread.Sleep();
  31. string result = "";
  32. System.Random random = new Random();
  33. for (int i = ; i < Length; i++)
  34. {
  35. result += random.Next().ToString();
  36. }
  37. return result;
  38. }
  39. #endregion
  40.  
  41. #region 生成随机字母与数字
  42. /// <summary>
  43. /// 生成随机字母与数字
  44. /// </summary>
  45. /// <param name="IntStr">生成长度</param>
  46. public static string Str(int Length)
  47. {
  48. return Str(Length, false);
  49. }
  50.  
  51. /// <summary>
  52. /// 生成随机字母与数字
  53. /// </summary>
  54. /// <param name="Length">生成长度</param>
  55. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  56. public static string Str(int Length, bool Sleep)
  57. {
  58. if (Sleep) System.Threading.Thread.Sleep();
  59. char[] Pattern = new char[] { '', '', '', '', '', '', '', '', '', '', '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' };
  60. string result = "";
  61. int n = Pattern.Length;
  62. System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
  63. for (int i = ; i < Length; i++)
  64. {
  65. int rnd = random.Next(, n);
  66. result += Pattern[rnd];
  67. }
  68. return result;
  69. }
  70. #endregion
  71.  
  72. #region 生成随机纯字母随机数
  73. /// <summary>
  74. /// 生成随机纯字母随机数
  75. /// </summary>
  76. /// <param name="IntStr">生成长度</param>
  77. public static string Str_char(int Length)
  78. {
  79. return Str_char(Length, false);
  80. }
  81.  
  82. /// <summary>
  83. /// 生成随机纯字母随机数
  84. /// </summary>
  85. /// <param name="Length">生成长度</param>
  86. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  87. public static string Str_char(int Length, bool Sleep)
  88. {
  89. if (Sleep) System.Threading.Thread.Sleep();
  90. char[] Pattern = new char[] { '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' };
  91. string result = "";
  92. int n = Pattern.Length;
  93. System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
  94. for (int i = ; i < Length; i++)
  95. {
  96. int rnd = random.Next(, n);
  97. result += Pattern[rnd];
  98. }
  99. return result;
  100. }
  101. #endregion
  102. }
  103.  
  104. /// <summary>
  105. /// 验证图片类
  106. /// </summary>
  107. public class YZMHelper
  108. {
  109. #region 私有字段
  110. private string text;
  111. private Bitmap image;
  112. private int letterCount = ; //验证码位数
  113. private int letterWidth = ; //单个字体的宽度范围
  114. private int letterHeight = ; //单个字体的高度范围
  115. private static byte[] randb = new byte[];
  116. private static RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();
  117. private Font[] fonts =
  118. {
  119. new Font(new FontFamily("Times New Roman"), +Next(),System.Drawing.FontStyle.Regular),
  120. new Font(new FontFamily("Georgia"), + Next(),System.Drawing.FontStyle.Regular),
  121. new Font(new FontFamily("Arial"), + Next(),System.Drawing.FontStyle.Regular),
  122. new Font(new FontFamily("Comic Sans MS"), + Next(),System.Drawing.FontStyle.Regular)
  123. };
  124. #endregion
  125.  
  126. #region 公有属性
  127. /// <summary>
  128. /// 验证码
  129. /// </summary>
  130. public string Text
  131. {
  132. get { return this.text; }
  133. }
  134.  
  135. /// <summary>
  136. /// 验证码图片
  137. /// </summary>
  138. public Bitmap Image
  139. {
  140. get { return this.image; }
  141. }
  142. #endregion
  143.  
  144. #region 构造函数
  145. public YZMHelper()
  146. {
  147. HttpContext.Current.Response.Expires = ;
  148. HttpContext.Current.Response.Buffer = true;
  149. HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-);
  150. HttpContext.Current.Response.AddHeader("pragma", "no-cache");
  151. HttpContext.Current.Response.CacheControl = "no-cache";
  152. this.text = Rand.Number();
  153. CreateImage();
  154. }
  155. #endregion
  156.  
  157. #region 私有方法
  158. /// <summary>
  159. /// 获得下一个随机数
  160. /// </summary>
  161. /// <param name="max">最大值</param>
  162. private static int Next(int max)
  163. {
  164. rand.GetBytes(randb);
  165. int value = BitConverter.ToInt32(randb, );
  166. value = value % (max + );
  167. if (value < ) value = -value;
  168. return value;
  169. }
  170.  
  171. /// <summary>
  172. /// 获得下一个随机数
  173. /// </summary>
  174. /// <param name="min">最小值</param>
  175. /// <param name="max">最大值</param>
  176. private static int Next(int min, int max)
  177. {
  178. int value = Next(max - min) + min;
  179. return value;
  180. }
  181. #endregion
  182.  
  183. #region 公共方法
  184. /// <summary>
  185. /// 绘制验证码
  186. /// </summary>
  187. public void CreateImage()
  188. {
  189. int int_ImageWidth = this.text.Length * letterWidth;
  190. Bitmap image = new Bitmap(int_ImageWidth, letterHeight);
  191. Graphics g = Graphics.FromImage(image);
  192. g.Clear(Color.White);
  193. for (int i = ; i < ; i++)
  194. {
  195. int x1 = Next(image.Width - );
  196. int x2 = Next(image.Width - );
  197. int y1 = Next(image.Height - );
  198. int y2 = Next(image.Height - );
  199. g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
  200. }
  201. int _x = -, _y = ;
  202. for (int int_index = ; int_index < this.text.Length; int_index++)
  203. {
  204. _x += Next(, );
  205. _y = Next(-, );
  206. string str_char = this.text.Substring(int_index, );
  207. str_char = Next() == ? str_char.ToLower() : str_char.ToUpper();
  208. Brush newBrush = new SolidBrush(GetRandomColor());
  209. Point thePos = new Point(_x, _y);
  210. g.DrawString(str_char, fonts[Next(fonts.Length - )], newBrush, thePos);
  211. }
  212. for (int i = ; i < ; i++)
  213. {
  214. int x = Next(image.Width - );
  215. int y = Next(image.Height - );
  216. image.SetPixel(x, y, Color.FromArgb(Next(, ), Next(, ), Next(, )));
  217. }
  218. image = TwistImage(image, true, Next(, ), Next(, ));
  219. g.DrawRectangle(new Pen(Color.LightGray, ), , , int_ImageWidth - , (letterHeight - ));
  220. this.image = image;
  221. }
  222.  
  223. /// <summary>
  224. /// 字体随机颜色
  225. /// </summary>
  226. public Color GetRandomColor()
  227. {
  228. Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
  229. System.Threading.Thread.Sleep(RandomNum_First.Next());
  230. Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);
  231. int int_Red = RandomNum_First.Next();
  232. int int_Green = RandomNum_Sencond.Next();
  233. int int_Blue = (int_Red + int_Green > ) ? : - int_Red - int_Green;
  234. int_Blue = (int_Blue > ) ? : int_Blue;
  235. return Color.FromArgb(int_Red, int_Green, int_Blue);
  236. }
  237.  
  238. /// <summary>
  239. /// 正弦曲线Wave扭曲图片
  240. /// </summary>
  241. /// <param name="srcBmp">图片路径</param>
  242. /// <param name="bXDir">如果扭曲则选择为True</param>
  243. /// <param name="nMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param>
  244. /// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param>
  245. public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
  246. {
  247. double PI = 6.283185307179586476925286766559;
  248. Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);
  249. Graphics graph = Graphics.FromImage(destBmp);
  250. graph.FillRectangle(new SolidBrush(Color.White), , , destBmp.Width, destBmp.Height);
  251. graph.Dispose();
  252. double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;
  253. for (int i = ; i < destBmp.Width; i++)
  254. {
  255. for (int j = ; j < destBmp.Height; j++)
  256. {
  257. double dx = ;
  258. dx = bXDir ? (PI * (double)j) / dBaseAxisLen : (PI * (double)i) / dBaseAxisLen;
  259. dx += dPhase;
  260. double dy = Math.Sin(dx);
  261. int nOldX = , nOldY = ;
  262. nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
  263. nOldY = bXDir ? j : j + (int)(dy * dMultValue);
  264.  
  265. Color color = srcBmp.GetPixel(i, j);
  266. if (nOldX >= && nOldX < destBmp.Width
  267. && nOldY >= && nOldY < destBmp.Height)
  268. {
  269. destBmp.SetPixel(nOldX, nOldY, color);
  270. }
  271. }
  272. }
  273. srcBmp.Dispose();
  274. return destBmp;
  275. }
  276. #endregion
  277. }
  278. }

需要添加以下引用

使用

添加引用后

  1. public ActionResult CreateCode() {
  2. YZMHelper yzm = new YZMHelper();
  3. Session["vCode"] = yzm.Text;
  4. MemoryStream ms = new MemoryStream();
  5. yzm.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
  6. byte[] bytes = ms.ToArray();
  7. ms.Close();
  8. return File(bytes, "Image/JPEG"); //需要将Bitmap类型转成byte[]类型
  9. }

前端

  1. <div class="form-group">
  2. <label for="UserPwd">验证码</label>
  3. <img src="/Login/CreateCode" alt="Alternate Text" onclick="this.src='/Login/CreateCode/'+Math.ceil(Math.random()*100)"/>
  4. <input type="text" class="form-control" name="vCode" placeholder="验证码输入">
  5. </div>

完整验证码类(validityHelper)(代码+使用)的更多相关文章

  1. PHP-解析验证码类--学习笔记

    1.开始 在 网上看到使用PHP写的ValidateCode生成验证码码类,感觉不错,特拿来分析学习一下. 2.类图 3.验证码类部分代码 3.1  定义变量 //随机因子 private $char ...

  2. 验证码类validateCode

    PHP验证码类,代码如下: <?php //验证码类 class ValidateCode { private $charset = 'abcdefghkmnprstuvwxyzABCDEFGH ...

  3. CI框架中,扩展验证码类。

    使用CI框架的朋友,应该都知道CI框架的的验证码辅助函数,不太好用.它需要写入到数据库中,然后再进行比对. 大家在实际项目中,好像不会这样去使用,因为会对数据库造成一定的压力. 所以,我们还是利用se ...

  4. 一个漂亮的php验证码类(分享)

    直接上代码: 复制代码 代码如下: //验证码类class ValidateCode { private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRS ...

  5. php面向对象(OOP)---- 验证码类

    PHP常用自封装类--验证码类 验证码是众多网站登陆.注册等相关功能不可以或缺的功能,实现展示验证码的方式有很多,这篇文章作者以工作中比较常用的方法进行了封装. 逻辑准备 要实现一个完整的验证码,需要 ...

  6. 建立一个漂亮的PHP验证码类文件及调用方式

    //验证码类class ValidateCode { private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';/ ...

  7. 一个漂亮的php验证码类

    一个漂亮的php验证码类(分享)   作者: 字体:[增加 减小] 类型:转载 下面小编就为大家分享一个漂亮的php验证码类.需要的朋友可以过来参考下   直接上代码: 复制代码 代码如下: //验证 ...

  8. Gif图片验证码类

    新开发的安全验证码类,支持生成Gif图片验证码(带噪点,干扰线,网格,随机色背景,随机自定义字体,倾斜,Gif动画). 上图: 字体及字体文件的路径需要在类中$FontFilePath及$FontFi ...

  9. THINKPHP源码学习--------验证码类

    TP3.2验证码类的理解 今天在学习中用到了THINKPHP验证码,为了了解究竟,就开始阅读TP验证码的源码. 源码位置:./ThinkPHP/Library/Think/Verify.class.p ...

随机推荐

  1. Unity3d- 资源

    Data与Resources文件夹一般只读文件放到Resources目录Data用于新建的文件或者要修改的文件============================================= ...

  2. Null hypothesis TypeⅠerror Type Ⅱ error

    Null hypothesis usually express the phenomenon of no effect or no difference. TypeⅠerror is the inco ...

  3. PAT 乙级 1010 一元多项式求导 (25) C++版

    1010. 一元多项式求导 (25) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 设计函数求一元多项式的导数.(注:xn(n为整数)的一 ...

  4. [VS2013]常见异常修正

    未能加载文件或程序集“Microsoft.SqlServer.Management.Sdk.Sfc, Version=11.0.0.0, Culture=neutral, PublicKeyToken ...

  5. 方法 - 调试Dll方法

    1.exe加载dll 2.Dll属性设置2.1运行exe生成Debug/...exe2.2属性->调试->命令-> 改成 ./Debug/调试Dll.exe ../Debug/调试D ...

  6. dell 7447加装SSD

    老本加新件:) dell 7447第一款游匣? 14年冬入手,陪伴在下已有4年 一.需要拆机看接口(不知道的话),拆机无流程,网上一大把,此处不再赘述. 二.硬盘接口知识扩展: SATA3 m2接口有 ...

  7. [UE4]Canvas Panel应用小技巧

    当设置为满屏拉伸的时候,只要把“偏移左侧”和“偏移底部”都设置为0,就会自动拉伸为整屏了.再也不需要手动担心拉不满屏了.

  8. JVM内存调优

    JVM性能调优有很多设置,这个参考JVM参数即可. 主要调优的目的: 控制GC的行为.GC是一个后台处理,但是它也是会消耗系统性能的,因此经常会根据系统运行的程序的特性来更改GC行为 控制JVM堆栈大 ...

  9. 使用命名管道的OVERLAPPED方式实现非阻塞模式编程 .

    命令管道是进程间通讯的一种常用方式,对于命令管道的介绍可以参考别的资料和书籍,这里推荐一个<VC++下命名管道编程的原理及实现>这篇博文,写得比较清楚.但是都是介绍了阻塞模式的编程,我这里 ...

  10. C#语言正则用法

    string phone =""; string pattern @"|\d{10}"; bool rusurt = false; Console.WriteL ...