纽威
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.7 KiB

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