VerifyCode.cs 3.0 KB

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