VerifyCodeHelper.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.DrawingCore;
  5. using System.DrawingCore.Drawing2D;
  6. using System.DrawingCore.Imaging;
  7. using System.IO;
  8. using Bowin.Common.Utility;
  9. namespace Bowin.Common
  10. {
  11. public class VerifyCodeHelper
  12. {
  13. public static string CreateRandomNum(int length = 5)
  14. {
  15. string numberString = "";
  16. //生成起始序列值
  17. int seed = unchecked((int)DateTime.Now.Ticks);
  18. Random rand = new Random();
  19. //生成随机数字
  20. for (int i = 0; i < length; i++)
  21. {
  22. numberString += rand.Next(0, 10);
  23. }
  24. return numberString;
  25. }
  26. public static byte[] CreateValidateGraphic(string vcode)
  27. {
  28. Bitmap image = new Bitmap((int)Math.Ceiling(vcode.Length * 12.0), 25);
  29. Graphics g = Graphics.FromImage(image);
  30. try
  31. {
  32. //生成随机生成器
  33. Random random = new Random();
  34. //清空图片背景色
  35. g.Clear(Color.White);
  36. //画图片的干扰线
  37. for (int i = 0; i < 25; i++)
  38. {
  39. int x1 = random.Next(image.Width);
  40. int x2 = random.Next(image.Width);
  41. int y1 = random.Next(image.Height);
  42. int y2 = random.Next(image.Height);
  43. g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
  44. }
  45. Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
  46. LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
  47. Color.Blue, Color.DarkRed, 1.2f, true);
  48. g.DrawString(vcode, font, brush, 3, 2);
  49. //画图片的前景干扰点
  50. for (int i = 0; i < 100; i++)
  51. {
  52. int x = random.Next(image.Width);
  53. int y = random.Next(image.Height);
  54. image.SetPixel(x, y, Color.FromArgb(random.Next()));
  55. }
  56. //画图片的边框线
  57. g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
  58. //保存图片数据
  59. MemoryStream stream = new MemoryStream();
  60. image.Save(stream, ImageFormat.Jpeg);
  61. //输出图片流
  62. return stream.ToArray();
  63. }
  64. finally
  65. {
  66. g.Dispose();
  67. image.Dispose();
  68. }
  69. }
  70. public static VerifyCode GetCode(int length = 5)
  71. {
  72. string code = "";
  73. string codeBase64 = "";
  74. code = CreateRandomNum(length);
  75. var bytes = CreateValidateGraphic(code);
  76. codeBase64 = Convert.ToBase64String(bytes);
  77. return new VerifyCode { Code = code.MD5(), CodeBase64 = codeBase64 };
  78. }
  79. }
  80. public class VerifyCode
  81. {
  82. public string Code { get; set; }
  83. public string CodeBase64 { get; set; }
  84. }
  85. }