SlideJigsawCaptchaTool.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.IO;
  4. using System.Threading.Tasks;
  5. using System.Collections.Generic;
  6. using SixLabors.ImageSharp;
  7. using SixLabors.ImageSharp.Drawing.Processing;
  8. using SixLabors.ImageSharp.Processing;
  9. using SixLabors.ImageSharp.Formats.Png;
  10. using SixLabors.ImageSharp.Drawing;
  11. using SixLabors.ImageSharp.PixelFormats;
  12. using ZhonTai.Admin.Core.Attributes;
  13. using ZhonTai.Admin.Tools.Cache;
  14. /*
  15. Linux下Ubuntu如果报Gdip错误,需要按照以下步骤操作
  16. 1. apt-get install libgdiplus
  17. 2. cd /usr/lib
  18. 3. ln -s libgdiplus.so gdiplus.dll
  19. */
  20. namespace ZhonTai.Admin.Tools.Captcha
  21. {
  22. /// <summary>
  23. /// 滑块拼图验证
  24. /// </summary>
  25. [SingleInstance]
  26. public class SlideJigsawCaptchaTool : ICaptchaTool
  27. {
  28. private readonly ICacheTool _cache;
  29. public SlideJigsawCaptchaTool(ICacheTool cache)
  30. {
  31. _cache = cache;
  32. }
  33. /// <summary>
  34. /// 随机范围内数字
  35. /// </summary>
  36. /// <param name="startNum"></param>
  37. /// <param name="endNum"></param>
  38. /// <returns></returns>
  39. public int GetRandomInt(int startNum, int endNum)
  40. {
  41. return (endNum > startNum ? new Random().Next(endNum - startNum) : 0) + startNum;
  42. }
  43. /// <summary>
  44. /// 随机生成拼图坐标
  45. /// </summary>
  46. /// <param name="originalWidth"></param>
  47. /// <param name="originalHeight"></param>
  48. /// <param name="templateWidth"></param>
  49. /// <param name="templateHeight"></param>
  50. /// <returns></returns>
  51. private PointModel GeneratePoint(int originalWidth, int originalHeight, int templateWidth, int templateHeight)
  52. {
  53. Random random = new Random();
  54. int widthDifference = originalWidth - templateWidth;
  55. int heightDifference = originalHeight - templateHeight;
  56. int x;
  57. if (widthDifference <= 0)
  58. {
  59. x = 5;
  60. }
  61. else
  62. {
  63. x = random.Next(originalWidth - templateWidth - 100) + 100;
  64. }
  65. int y;
  66. if (heightDifference <= 0)
  67. {
  68. y = 5;
  69. }
  70. else
  71. {
  72. y = random.Next(originalHeight - templateHeight - 5) + 5;
  73. }
  74. return new PointModel(x, y);
  75. }
  76. /// <summary>
  77. /// 随机生成干扰图坐标
  78. /// </summary>
  79. /// <param name="originalWidth"></param>
  80. /// <param name="originalHeight"></param>
  81. /// <param name="templateWidth"></param>
  82. /// <param name="templateHeight"></param>
  83. /// <param name="blockX"></param>
  84. /// <param name="blockY"></param>
  85. /// <returns></returns>
  86. private PointModel GenerateInterferencePoint(int originalWidth, int originalHeight, int templateWidth, int templateHeight, int blockX, int blockY)
  87. {
  88. int x;
  89. if (originalWidth - blockX - 5 > templateWidth * 2)
  90. {
  91. //在原扣图右边插入干扰图
  92. x = GetRandomInt(blockX + templateWidth + 5, originalWidth - templateWidth);
  93. }
  94. else
  95. {
  96. //在原扣图左边插入干扰图
  97. x = GetRandomInt(100, blockX - templateWidth - 5);
  98. }
  99. int y;
  100. if (originalHeight - blockY - 5 > templateHeight * 2)
  101. {
  102. //在原扣图下边插入干扰图
  103. y = GetRandomInt(blockY + templateHeight + 5, originalHeight - templateHeight);
  104. }
  105. else
  106. {
  107. //在原扣图上边插入干扰图
  108. y = GetRandomInt(5, blockY - templateHeight - 5);
  109. }
  110. return new PointModel(x, y);
  111. }
  112. private static ComplexPolygon CalcBlockShape(Image<Rgba32> holeTemplateImage)
  113. {
  114. int temp = 0;
  115. var pathList = new List<IPath>();
  116. holeTemplateImage.ProcessPixelRows(accessor =>
  117. {
  118. for (int y = 0; y < holeTemplateImage.Height; y++)
  119. {
  120. var rowSpan = accessor.GetRowSpan(y);
  121. for (int x = 0; x < rowSpan.Length; x++)
  122. {
  123. ref Rgba32 pixel = ref rowSpan[x];
  124. if (pixel.A != 0)
  125. {
  126. if (temp == 0)
  127. {
  128. temp = x;
  129. }
  130. }
  131. else
  132. {
  133. if (temp != 0)
  134. {
  135. pathList.Add(new RectangularPolygon(temp, y, x - temp, 1));
  136. temp = 0;
  137. }
  138. }
  139. }
  140. }
  141. });
  142. return new ComplexPolygon(new PathCollection(pathList));
  143. }
  144. /// <summary>
  145. /// 获得验证数据
  146. /// </summary>
  147. /// <returns>JObject</returns>
  148. public async Task<CaptchaOutput> GetAsync(string captchaKey)
  149. {
  150. //获取网络图片
  151. //var client = new HttpClient();
  152. //var stream = await client.GetStreamAsync("https://picsum.photos/310/155");
  153. //client.Dispose();
  154. //底图
  155. using var baseImage = await Image.LoadAsync<Rgba32>($@"{Directory.GetCurrentDirectory()}\wwwroot\captcha\jigsaw\{new Random().Next(1, 4)}.jpg".ToPath());
  156. //模板图
  157. using var templateImage = await Image.LoadAsync<Rgba32>($@"{Directory.GetCurrentDirectory()}\wwwroot\captcha\jigsaw\templates\{new Random().Next(1, 7)}.png".ToPath());
  158. int baseWidth = baseImage.Width;
  159. int baseHeight = baseImage.Height;
  160. int templateWidth = templateImage.Width;
  161. int templateHeight = templateImage.Height;
  162. //拼图
  163. using var blockImage = new Image<Rgba32>(templateWidth, templateHeight);
  164. //滑块拼图
  165. using var sliderBlockImage = new Image<Rgba32>(templateWidth, baseHeight);
  166. //随机生成拼图坐标
  167. PointModel blockPoint = GeneratePoint(baseWidth, baseHeight, templateWidth, templateHeight);
  168. //根据模板图计算轮廓
  169. var blockShape = CalcBlockShape(templateImage);
  170. //生成拼图
  171. blockImage.Mutate(x =>
  172. {
  173. x.Clip(blockShape, p => p.DrawImage(baseImage, new Point(-blockPoint.X, -blockPoint.Y), 1));
  174. });
  175. //叠加拼图
  176. //blockImage.Mutate(x => x.DrawImage(templateImage, new Point(0, 0), 1));
  177. //生成滑块拼图
  178. sliderBlockImage.Mutate(x => x.DrawImage(blockImage, new Point(0, blockPoint.Y), 1));
  179. //生成拼图底图
  180. baseImage.Mutate(x => x.DrawImage(templateImage, new Point(blockPoint.X, blockPoint.Y), (float)0.5));
  181. //生成干扰图坐标
  182. PointModel interferencePoint = GenerateInterferencePoint(baseWidth, baseHeight, templateWidth, templateHeight, blockPoint.X, blockPoint.Y);
  183. //生成干扰图底图
  184. baseImage.Mutate(x => x.DrawImage(templateImage, new Point(interferencePoint.X, interferencePoint.Y), (float)0.5));
  185. var token = Guid.NewGuid().ToString();
  186. var captchaData = new CaptchaOutput
  187. {
  188. Token = token,
  189. Data = new SlideJigsawCaptchaDto()
  190. {
  191. BaseImage = baseImage.ToBase64String(PngFormat.Instance),
  192. BlockImage = sliderBlockImage.ToBase64String(PngFormat.Instance)
  193. }
  194. };
  195. var key = string.Format(captchaKey, token);
  196. await _cache.SetAsync(key, blockPoint.X);
  197. return captchaData;
  198. }
  199. /// <summary>
  200. /// 检查验证数据
  201. /// </summary>
  202. /// <param name="input"></param>
  203. /// <returns></returns>
  204. public async Task<bool> CheckAsync(CaptchaInput input)
  205. {
  206. if (input == null || input.Data.IsNull())
  207. {
  208. return false;
  209. }
  210. var key = string.Format(input.CaptchaKey, input.Token);
  211. if (await _cache.ExistsAsync(key))
  212. {
  213. try
  214. {
  215. var point = JsonConvert.DeserializeObject<PointModel>(input.Data);
  216. var x = await _cache.GetAsync<int>(key);
  217. if (Math.Abs(x - point.X) < 5)
  218. {
  219. if (input.DeleteCache)
  220. {
  221. await _cache.DelAsync(key);
  222. }
  223. return true;
  224. }
  225. else
  226. {
  227. await _cache.DelAsync(key);
  228. return false;
  229. }
  230. }
  231. catch
  232. {
  233. await _cache.DelAsync(key);
  234. return false;
  235. }
  236. }
  237. else
  238. {
  239. return false;
  240. }
  241. }
  242. }
  243. }