Nav apraksta

VerifyCode.cs 2.8KB

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