VerifyCode.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using LeaRun.Util;
  2. using System;
  3. using System.Drawing;
  4. using System.Drawing.Imaging;
  5. using System.IO;
  6. namespace LeaRun.Application.Code
  7. {
  8. /// <summary>
  9. /// 版 本 6.1
  10. /// Copyright (c) 2013-2016 上海力软信息技术有限公司
  11. /// 创建人:佘赐雄
  12. /// 日 期:2015.11.9 10:45
  13. /// 描 述:生成验证码
  14. /// </summary>
  15. public class VerifyCode
  16. {
  17. /// <summary>
  18. /// 生成验证码
  19. /// </summary>
  20. /// <returns></returns>
  21. public byte[] GetVerifyCode()
  22. {
  23. int codeW = 80;
  24. int codeH = 30;
  25. int fontSize = 16;
  26. string chkCode = string.Empty;
  27. //颜色列表,用于验证码、噪线、噪点
  28. Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
  29. //字体列表,用于验证码
  30. string[] font = { "Times New Roman" };
  31. //验证码的字符集,去掉了一些容易混淆的字符
  32. char[] character = { '2', '3', '4', '5', '6', '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' };
  33. Random rnd = new Random();
  34. //生成验证码字符串
  35. for (int i = 0; i < 4; i++)
  36. {
  37. chkCode += character[rnd.Next(character.Length)];
  38. }
  39. //写入Session、验证码加密
  40. WebHelper.WriteSession("session_verifycode", Md5Helper.MD5(chkCode.ToLower(), 16));
  41. //创建画布
  42. Bitmap bmp = new Bitmap(codeW, codeH);
  43. Graphics g = Graphics.FromImage(bmp);
  44. g.Clear(Color.White);
  45. //画噪线
  46. for (int i = 0; i < 1; i++)
  47. {
  48. int x1 = rnd.Next(codeW);
  49. int y1 = rnd.Next(codeH);
  50. int x2 = rnd.Next(codeW);
  51. int y2 = rnd.Next(codeH);
  52. Color clr = color[rnd.Next(color.Length)];
  53. g.DrawLine(new Pen(clr), x1, y1, x2, y2);
  54. }
  55. //画验证码字符串
  56. for (int i = 0; i < chkCode.Length; i++)
  57. {
  58. string fnt = font[rnd.Next(font.Length)];
  59. Font ft = new Font(fnt, fontSize);
  60. Color clr = color[rnd.Next(color.Length)];
  61. g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0);
  62. }
  63. //将验证码图片写入内存流,并将其以 "image/Png" 格式输出
  64. MemoryStream ms = new MemoryStream();
  65. try
  66. {
  67. bmp.Save(ms, ImageFormat.Png);
  68. return ms.ToArray();
  69. }
  70. catch (Exception)
  71. {
  72. return null;
  73. }
  74. finally
  75. {
  76. g.Dispose();
  77. bmp.Dispose();
  78. }
  79. }
  80. }
  81. }