VerifyCode.cs 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * 命名空间: CZFW.Core.Security
  3. *
  4. * 功 能: 图形验证码
  5. * 类 名: VerifyCode
  6. *
  7. * Ver 变更日期 负责人 变更内容
  8. * ───────────────────────────────────
  9. * V0.01 2016/12/19 21:27:48 曹湘 初稿
  10. *
  11. * Copyright (c) 2016 CHUANGZHIKEJI Corporation. All rights reserved.
  12. *┌──────────────────────────────────┐
  13. *│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │
  14. *│ 版权所有:创执科技(北京)有限公司                │
  15. *└──────────────────────────────────┘
  16. */
  17. using System;
  18. using System.IO;
  19. using System.DrawingCore.Imaging;
  20. using System.DrawingCore;
  21. using CZFW.Framework.Model;
  22. namespace CZFW.Core.Security
  23. {
  24. /// <summary>
  25. /// 图形验证码
  26. /// </summary>
  27. public class VerifyCode
  28. {
  29. public byte[] GetVerifyCode()
  30. {
  31. const int codeW = 80;
  32. const int codeH = 30;
  33. const int fontSize = 16;
  34. string chkCode = string.Empty;
  35. //颜色列表,用于验证码、噪线、噪点
  36. Color[] color = { Color.Black,Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
  37. //字体列表,用于验证码
  38. string[] font = { "Times New Roman" };
  39. //验证码的字符集,去掉了一些容易混淆的字符
  40. char[] character = { '1', '2', '3', '4', '5', '6', '7', '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' };
  41. Random rnd = new Random();
  42. //生成验证码字符串
  43. for (int i = 0; i < 4; i++)
  44. {
  45. chkCode += character[rnd.Next(character.Length)];
  46. }
  47. //写入Session、验证码加密
  48. WebHelper.WriteSession("czfw_session_verifycode", DesEncrypt.Encrypt(chkCode.ToLower(), "MD5"));
  49. //创建画布
  50. Bitmap bmp = new Bitmap(codeW, codeH);
  51. Graphics g = Graphics.FromImage(bmp);
  52. g.Clear(Color.White);
  53. //画噪线
  54. for (int i = 0; i < 3; i++)
  55. {
  56. int x1 = rnd.Next(codeW);
  57. int y1 = rnd.Next(codeH);
  58. int x2 = rnd.Next(codeW);
  59. int y2 = rnd.Next(codeH);
  60. Color clr = color[rnd.Next(color.Length)];
  61. g.DrawLine(new Pen(clr), x1, y1, x2, y2);
  62. }
  63. //画验证码字符串
  64. for (int i = 0; i < chkCode.Length; i++)
  65. {
  66. string fnt = font[rnd.Next(font.Length)];
  67. Font ft = new Font(fnt, fontSize);
  68. Color clr = color[rnd.Next(color.Length)];
  69. g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, 0);
  70. }
  71. //将验证码图片写入内存流,并将其以 "image/Png" 格式输出
  72. MemoryStream ms = new MemoryStream();
  73. try
  74. {
  75. bmp.Save(ms, ImageFormat.Png);
  76. return ms.ToArray();
  77. }
  78. catch (Exception)
  79. {
  80. return null;
  81. }
  82. finally
  83. {
  84. g.Dispose();
  85. bmp.Dispose();
  86. }
  87. }
  88. }
  89. }