VerifyCodeUtil.cs 2.8 KB

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