SlideJigsawCaptcha.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. using Admin.Core;
  2. using Admin.Core.Common.Attributes;
  3. using Admin.Core.Common.Cache;
  4. using Newtonsoft.Json;
  5. using System;
  6. using System.Drawing;
  7. using System.Drawing.Drawing2D;
  8. using System.Drawing.Imaging;
  9. using System.IO;
  10. using System.Threading.Tasks;
  11. /*
  12. Linux下Ubuntu如果报Gdip错误,需要按照以下步骤操作
  13. 1. apt-get install libgdiplus
  14. 2. cd /usr/lib
  15. 3. ln -s libgdiplus.so gdiplus.dll
  16. */
  17. namespace Admin.Tools.Captcha
  18. {
  19. /// <summary>
  20. /// 滑块拼图验证
  21. /// </summary>
  22. [SingleInstance]
  23. public class SlideJigsawCaptcha : ICaptcha
  24. {
  25. private readonly ICache _cache;
  26. public SlideJigsawCaptcha(ICache cache)
  27. {
  28. _cache = cache;
  29. }
  30. /// <summary>
  31. /// Bitmap转为base64编码的文本
  32. /// </summary>
  33. /// <param name="bmp"></param>
  34. /// <returns></returns>
  35. private string ImgToBase64String(Bitmap bmp)
  36. {
  37. try
  38. {
  39. MemoryStream ms = new MemoryStream();
  40. bmp.Save(ms, ImageFormat.Png);
  41. byte[] arr = new byte[ms.Length];
  42. ms.Position = 0;
  43. ms.Read(arr, 0, (int)ms.Length);
  44. ms.Close();
  45. return Convert.ToBase64String(arr);
  46. }
  47. catch
  48. {
  49. return null;
  50. }
  51. }
  52. private void ReadPixel(Bitmap img, int x, int y, int[] pixels)
  53. {
  54. int xStart = x - 1;
  55. int yStart = y - 1;
  56. int current = 0;
  57. for (int i = xStart; i < 3 + xStart; i++)
  58. {
  59. for (int j = yStart; j < 3 + yStart; j++)
  60. {
  61. int tx = i;
  62. if (tx < 0)
  63. {
  64. tx = -tx;
  65. }
  66. else if (tx >= img.Width)
  67. {
  68. tx = x;
  69. }
  70. int ty = j;
  71. if (ty < 0)
  72. {
  73. ty = -ty;
  74. }
  75. else if (ty >= img.Height)
  76. {
  77. ty = y;
  78. }
  79. pixels[current++] = img.GetPixel(tx, ty).ToArgb();
  80. }
  81. }
  82. }
  83. private void FillMatrix(int[][] matrix, int[] values)
  84. {
  85. int filled = 0;
  86. for (int i = 0; i < matrix.Length; i++)
  87. {
  88. int[] x = matrix[i];
  89. for (int j = 0; j < x.Length; j++)
  90. {
  91. x[j] = values[filled++];
  92. }
  93. }
  94. }
  95. private Color AvgMatrix(int[][] matrix)
  96. {
  97. int r = 0;
  98. int g = 0;
  99. int b = 0;
  100. for (int i = 0; i < matrix.Length; i++)
  101. {
  102. int[] x = matrix[i];
  103. for (int j = 0; j < x.Length; j++)
  104. {
  105. if (j == 1)
  106. {
  107. continue;
  108. }
  109. Color c = Color.FromArgb(x[j]);
  110. r += c.R;
  111. g += c.G;
  112. b += c.B;
  113. }
  114. }
  115. return Color.FromArgb(r / 8, g / 8, b / 8);
  116. }
  117. /// <summary>
  118. /// 根据模板生成拼图
  119. /// </summary>
  120. /// <param name="baseImage"></param>
  121. /// <param name="templateImage"></param>
  122. /// <param name="x"></param>
  123. /// <param name="y"></param>
  124. /// <returns></returns>
  125. private Bitmap CutByTemplate(Bitmap baseImage, Bitmap templateImage, int x, int y)
  126. {
  127. //生成透明背景图
  128. Bitmap newImage = new Bitmap(templateImage.Width, baseImage.Height);
  129. for (int i = 0, newImageWidth = templateImage.Width; i < newImageWidth; i++)
  130. {
  131. for (int j = 0, newImageHeight = baseImage.Height; j < newImageHeight; j++)
  132. {
  133. newImage.SetPixel(i, j, Color.FromArgb(0,0,0,0));
  134. }
  135. }
  136. // 临时数组遍历用于高斯模糊存周边像素值
  137. int[][] martrix = { new int[3], new int[3], new int[3] };
  138. int[] values = new int[9];
  139. int xLength = templateImage.Width;
  140. int yLength = templateImage.Height;
  141. // 模板图像宽度
  142. for (int i = 0; i < xLength; i++)
  143. {
  144. // 模板图片高度
  145. for (int j = 0; j < yLength; j++)
  146. {
  147. // 如果模板图像当前像素点不是透明色 copy源文件信息到目标图片中
  148. int rgb = templateImage.GetPixel(i, j).ToArgb();
  149. if (rgb < 0)
  150. {
  151. Color oriImageColor = baseImage.GetPixel(x + i, y + j);
  152. newImage.SetPixel(i, y + j, oriImageColor);
  153. //抠图区域半透明
  154. //baseImage.SetPixel(x + i, y + j, Color.FromArgb(120, oriImageColor.R, oriImageColor.G, oriImageColor.B));
  155. //抠图区域高斯模糊
  156. ReadPixel(baseImage, x + i, y + j, values);
  157. FillMatrix(martrix, values);
  158. baseImage.SetPixel(x + i, y + j, AvgMatrix(martrix));
  159. }
  160. //防止数组越界判断
  161. if (i == (xLength - 1) || j == (yLength - 1))
  162. {
  163. continue;
  164. }
  165. int rightRgb = templateImage.GetPixel(i + 1, j).ToArgb();
  166. int downRgb = templateImage.GetPixel(i, j + 1).ToArgb();
  167. //描边处理,,取带像素和无像素的界点,判断该点是不是临界轮廓点,如果是设置该坐标像素是白色
  168. if ((rgb >= 0 && rightRgb < 0) || (rgb < 0 && rightRgb >= 0) || (rgb >= 0 && downRgb < 0) || (rgb < 0 && downRgb >= 0))
  169. {
  170. newImage.SetPixel(i, y + j, Color.White);
  171. baseImage.SetPixel(x + i, y + j, Color.White);
  172. }
  173. }
  174. }
  175. return newImage;
  176. }
  177. /// <summary>
  178. /// 根据模板生成干扰图
  179. /// </summary>
  180. /// <param name="baseImage"></param>
  181. /// <param name="templateImage"></param>
  182. /// <param name="x"></param>
  183. /// <param name="y"></param>
  184. private void InterferenceByTemplate(Bitmap baseImage, Bitmap templateImage, int x, int y)
  185. {
  186. // 临时数组遍历用于高斯模糊存周边像素值
  187. int[][] martrix = { new int[3], new int[3], new int[3] };
  188. int[] values = new int[9];
  189. int xLength = templateImage.Width;
  190. int yLength = templateImage.Height;
  191. // 模板图像宽度
  192. for (int i = 0; i < xLength; i++)
  193. {
  194. // 模板图片高度
  195. for (int j = 0; j < yLength; j++)
  196. {
  197. // 如果模板图像当前像素点不是透明色 copy源文件信息到目标图片中
  198. int rgb = templateImage.GetPixel(i, j).ToArgb();
  199. if (rgb < 0)
  200. {
  201. Color oriImageColor = baseImage.GetPixel(x + i, y + j);
  202. //抠图区域半透明
  203. //baseImage.SetPixel(x + i, y + j, Color.FromArgb(120, oriImageColor.R, oriImageColor.G, oriImageColor.B));
  204. //抠图区域高斯模糊
  205. ReadPixel(baseImage, x + i, y + j, values);
  206. FillMatrix(martrix, values);
  207. baseImage.SetPixel(x + i, y + j, AvgMatrix(martrix));
  208. }
  209. //防止数组越界判断
  210. if (i == (xLength - 1) || j == (yLength - 1))
  211. {
  212. continue;
  213. }
  214. int rightRgb = templateImage.GetPixel(i + 1, j).ToArgb();
  215. int downRgb = templateImage.GetPixel(i, j + 1).ToArgb();
  216. //描边处理,,取带像素和无像素的界点,判断该点是不是临界轮廓点,如果是设置该坐标像素是白色
  217. if ((rgb >= 0 && rightRgb < 0) || (rgb < 0 && rightRgb >= 0) || (rgb >= 0 && downRgb < 0) || (rgb < 0 && downRgb >= 0))
  218. {
  219. baseImage.SetPixel(x + i, y + j, Color.White);
  220. }
  221. }
  222. }
  223. }
  224. /// <summary>
  225. /// 更改图片尺寸
  226. /// </summary>
  227. /// <param name="bmp"></param>
  228. /// <param name="width"></param>
  229. /// <param name="height"></param>
  230. /// <returns></returns>
  231. private Bitmap ResizeImage(Bitmap bmp, int width, int height)
  232. {
  233. try
  234. {
  235. Bitmap b = new Bitmap(width, height);
  236. Graphics g = Graphics.FromImage(b);
  237. // 图画质量
  238. g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  239. g.DrawImage(bmp, new Rectangle(0, 0, width, height), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
  240. g.Dispose();
  241. return b;
  242. }
  243. catch
  244. {
  245. return null;
  246. }
  247. }
  248. /// <summary>
  249. /// 随机范围内数字
  250. /// </summary>
  251. /// <param name="startNum"></param>
  252. /// <param name="endNum"></param>
  253. /// <returns></returns>
  254. public int GetRandomInt(int startNum, int endNum)
  255. {
  256. return (endNum > startNum ? new Random().Next(endNum - startNum) : 0) + startNum;
  257. }
  258. /// <summary>
  259. /// 随机生成拼图坐标
  260. /// </summary>
  261. /// <param name="originalWidth"></param>
  262. /// <param name="originalHeight"></param>
  263. /// <param name="templateWidth"></param>
  264. /// <param name="templateHeight"></param>
  265. /// <returns></returns>
  266. private PointModel GeneratePoint(int originalWidth, int originalHeight, int templateWidth, int templateHeight)
  267. {
  268. Random random = new Random();
  269. int widthDifference = originalWidth - templateWidth;
  270. int heightDifference = originalHeight - templateHeight;
  271. int x;
  272. if (widthDifference <= 0)
  273. {
  274. x = 5;
  275. }
  276. else
  277. {
  278. x = random.Next(originalWidth - templateWidth - 100) + 100;
  279. }
  280. int y;
  281. if (heightDifference <= 0)
  282. {
  283. y = 5;
  284. }
  285. else
  286. {
  287. y = random.Next(originalHeight - templateHeight - 5) + 5;
  288. }
  289. return new PointModel(x, y);
  290. }
  291. /// <summary>
  292. /// 随机生成干扰图坐标
  293. /// </summary>
  294. /// <param name="originalWidth"></param>
  295. /// <param name="originalHeight"></param>
  296. /// <param name="templateWidth"></param>
  297. /// <param name="templateHeight"></param>
  298. /// <param name="blockX"></param>
  299. /// <param name="blockY"></param>
  300. /// <returns></returns>
  301. private PointModel GenerateInterferencePoint(int originalWidth, int originalHeight, int templateWidth, int templateHeight, int blockX, int blockY)
  302. {
  303. int x;
  304. if (originalWidth - blockX - 5 > templateWidth * 2)
  305. {
  306. //在原扣图右边插入干扰图
  307. x = GetRandomInt(blockX + templateWidth + 5, originalWidth - templateWidth);
  308. }
  309. else
  310. {
  311. //在原扣图左边插入干扰图
  312. x = GetRandomInt(100, blockX - templateWidth - 5);
  313. }
  314. int y;
  315. if (originalHeight - blockY - 5 > templateHeight * 2)
  316. {
  317. //在原扣图下边插入干扰图
  318. y = GetRandomInt(blockY + templateHeight + 5, originalHeight - templateHeight);
  319. }
  320. else
  321. {
  322. //在原扣图上边插入干扰图
  323. y = GetRandomInt(5, blockY - templateHeight - 5);
  324. }
  325. return new PointModel(x, y);
  326. }
  327. /// <summary>
  328. /// 获得验证数据
  329. /// </summary>
  330. /// <returns>JObject</returns>
  331. public async Task<CaptchaOutput> GetAsync()
  332. {
  333. //获取网络图片
  334. //var client = new HttpClient();
  335. //var stream = await client.GetStreamAsync("https://picsum.photos/310/155");
  336. //client.Dispose();
  337. //Bitmap baseImage = new Bitmap(stream);
  338. //stream.Dispose();
  339. var oriImage = Image.FromFile($@"{Directory.GetCurrentDirectory()}\wwwroot\captcha\jigsaw\{new Random().Next(1, 4)}.jpg".ToPath());
  340. //更改图片尺寸
  341. //Bitmap baseImage = ResizeImage(oriImage, 310, 155);
  342. Bitmap baseImage = new Bitmap(oriImage);
  343. oriImage.Dispose();
  344. var oriTemplate = Image.FromFile($@"{Directory.GetCurrentDirectory()}\wwwroot\captcha\jigsaw\templates\{new Random().Next(1, 7)}.png".ToPath());
  345. Bitmap templateImage = new Bitmap(oriTemplate);
  346. oriTemplate.Dispose();
  347. int baseWidth = baseImage.Width;
  348. int baseHeight = baseImage.Height;
  349. int templateWidth = templateImage.Width;
  350. int templateHeight = templateImage.Height;
  351. //随机生成拼图坐标
  352. PointModel point = GeneratePoint(baseWidth, baseHeight, templateWidth, templateHeight);
  353. int x = point.X;
  354. int y = point.Y;
  355. //生成拼图
  356. string blockImageBase64 = "data:image/png;base64," + ImgToBase64String(CutByTemplate(baseImage, templateImage, x, y));
  357. //生成干扰图
  358. PointModel interferencePoint = GenerateInterferencePoint(baseWidth, baseHeight, templateWidth, templateHeight, x, y);
  359. InterferenceByTemplate(baseImage, templateImage, interferencePoint.X, interferencePoint.Y);
  360. string baseImageBase64 = "data:image/png;base64," + ImgToBase64String(baseImage);
  361. templateImage.Dispose();
  362. baseImage.Dispose();
  363. var token = Guid.NewGuid().ToString();
  364. CaptchaOutput captchaData = new CaptchaOutput
  365. {
  366. Token = token,
  367. Data = new SlideJigsawCaptchaModel()
  368. {
  369. BlockImage = blockImageBase64,
  370. BaseImage = baseImageBase64
  371. }
  372. };
  373. var key = string.Format(CacheKey.VerifyCodeKey, token);
  374. await _cache.SetAsync(key, point.X);
  375. return captchaData;
  376. }
  377. /// <summary>
  378. /// 检查验证数据
  379. /// </summary>
  380. /// <param name="input"></param>
  381. /// <returns></returns>
  382. public async Task<bool> CheckAsync(CaptchaInput input)
  383. {
  384. if (input == null || input.Data.IsNull())
  385. {
  386. return false;
  387. }
  388. var key = string.Format(CacheKey.VerifyCodeKey, input.Token);
  389. if (await _cache.ExistsAsync(key))
  390. {
  391. try
  392. {
  393. var point = JsonConvert.DeserializeObject<PointModel>(input.Data);
  394. var x = await _cache.GetAsync<int>(key);
  395. if (Math.Abs(x - point.X) < 5)
  396. {
  397. if (input.DeleteCache)
  398. {
  399. await _cache.DelAsync(key);
  400. }
  401. return true;
  402. }
  403. else
  404. {
  405. await _cache.DelAsync(key);
  406. return false;
  407. }
  408. }
  409. catch
  410. {
  411. await _cache.DelAsync(key);
  412. return false;
  413. }
  414. }
  415. else
  416. {
  417. return false;
  418. }
  419. }
  420. }
  421. }