SlideJigsawCaptcha.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. /// <summary>
  53. /// 根据模板生成拼图
  54. /// </summary>
  55. /// <param name="baseImage"></param>
  56. /// <param name="templateImage"></param>
  57. /// <param name="x"></param>
  58. /// <param name="y"></param>
  59. /// <returns></returns>
  60. private Bitmap CutByTemplate(Bitmap baseImage, Bitmap templateImage, int x, int y)
  61. {
  62. Bitmap newImage = new Bitmap(templateImage.Width, baseImage.Height, PixelFormat.Format32bppRgb);
  63. newImage.MakeTransparent();
  64. int xLength = templateImage.Width;
  65. int yLength = templateImage.Height;
  66. // 模板图像宽度
  67. for (int i = 0; i < xLength; i++)
  68. {
  69. // 模板图片高度
  70. for (int j = 0; j < yLength; j++)
  71. {
  72. // 如果模板图像当前像素点不是透明色 copy源文件信息到目标图片中
  73. int rgb = templateImage.GetPixel(i, j).ToArgb();
  74. if (rgb < 0)
  75. {
  76. Color oriImageColor = baseImage.GetPixel(x + i, y + j);
  77. newImage.SetPixel(i, y + j, oriImageColor);
  78. //抠图区域半透明
  79. baseImage.SetPixel(x + i, y + j, Color.FromArgb(120, oriImageColor.R, oriImageColor.G, oriImageColor.B));
  80. }
  81. //防止数组越界判断
  82. if (i == (xLength - 1) || j == (yLength - 1))
  83. {
  84. continue;
  85. }
  86. int rightRgb = templateImage.GetPixel(i + 1, j).ToArgb();
  87. int downRgb = templateImage.GetPixel(i, j + 1).ToArgb();
  88. //描边处理,,取带像素和无像素的界点,判断该点是不是临界轮廓点,如果是设置该坐标像素是白色
  89. if ((rgb >= 0 && rightRgb < 0) || (rgb < 0 && rightRgb >= 0) || (rgb >= 0 && downRgb < 0) || (rgb < 0 && downRgb >= 0))
  90. {
  91. newImage.SetPixel(i, y + j, Color.White);
  92. baseImage.SetPixel(x + i, y + j, Color.White);
  93. }
  94. }
  95. }
  96. return newImage;
  97. }
  98. /// <summary>
  99. /// 根据模板生成干扰图
  100. /// </summary>
  101. /// <param name="baseImage"></param>
  102. /// <param name="templateImage"></param>
  103. /// <param name="x"></param>
  104. /// <param name="y"></param>
  105. private void InterferenceByTemplate(Bitmap baseImage, Bitmap templateImage, int x, int y)
  106. {
  107. int xLength = templateImage.Width;
  108. int yLength = templateImage.Height;
  109. // 模板图像宽度
  110. for (int i = 0; i < xLength; i++)
  111. {
  112. // 模板图片高度
  113. for (int j = 0; j < yLength; j++)
  114. {
  115. // 如果模板图像当前像素点不是透明色 copy源文件信息到目标图片中
  116. int rgb = templateImage.GetPixel(i, j).ToArgb();
  117. if (rgb < 0)
  118. {
  119. Color oriImageColor = baseImage.GetPixel(x + i, y + j);
  120. //抠图区域半透明
  121. baseImage.SetPixel(x + i, y + j, Color.FromArgb(120, oriImageColor.R, oriImageColor.G, oriImageColor.B));
  122. }
  123. //防止数组越界判断
  124. if (i == (xLength - 1) || j == (yLength - 1))
  125. {
  126. continue;
  127. }
  128. int rightRgb = templateImage.GetPixel(i + 1, j).ToArgb();
  129. int downRgb = templateImage.GetPixel(i, j + 1).ToArgb();
  130. //描边处理,,取带像素和无像素的界点,判断该点是不是临界轮廓点,如果是设置该坐标像素是白色
  131. if ((rgb >= 0 && rightRgb < 0) || (rgb < 0 && rightRgb >= 0) || (rgb >= 0 && downRgb < 0) || (rgb < 0 && downRgb >= 0))
  132. {
  133. baseImage.SetPixel(x + i, y + j, Color.White);
  134. }
  135. }
  136. }
  137. }
  138. /// <summary>
  139. /// 更改图片尺寸
  140. /// </summary>
  141. /// <param name="bmp"></param>
  142. /// <param name="width"></param>
  143. /// <param name="height"></param>
  144. /// <returns></returns>
  145. private Bitmap ResizeImage(Bitmap bmp, int width, int height)
  146. {
  147. try
  148. {
  149. Bitmap b = new Bitmap(width, height);
  150. Graphics g = Graphics.FromImage(b);
  151. // 图画质量
  152. g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  153. g.DrawImage(bmp, new Rectangle(0, 0, width, height), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
  154. g.Dispose();
  155. return b;
  156. }
  157. catch
  158. {
  159. return null;
  160. }
  161. }
  162. /// <summary>
  163. /// 随机范围内数字
  164. /// </summary>
  165. /// <param name="startNum"></param>
  166. /// <param name="endNum"></param>
  167. /// <returns></returns>
  168. public int GetRandomInt(int startNum, int endNum)
  169. {
  170. return (endNum > startNum ? new Random().Next(endNum - startNum) : 0) + startNum;
  171. }
  172. /// <summary>
  173. /// 随机生成拼图坐标
  174. /// </summary>
  175. /// <param name="originalWidth"></param>
  176. /// <param name="originalHeight"></param>
  177. /// <param name="templateWidth"></param>
  178. /// <param name="templateHeight"></param>
  179. /// <returns></returns>
  180. private PointModel GeneratePoint(int originalWidth, int originalHeight, int templateWidth, int templateHeight)
  181. {
  182. Random random = new Random();
  183. int widthDifference = originalWidth - templateWidth;
  184. int heightDifference = originalHeight - templateHeight;
  185. int x;
  186. if (widthDifference <= 0)
  187. {
  188. x = 5;
  189. }
  190. else
  191. {
  192. x = random.Next(originalWidth - templateWidth - 100) + 100;
  193. }
  194. int y;
  195. if (heightDifference <= 0)
  196. {
  197. y = 5;
  198. }
  199. else
  200. {
  201. y = random.Next(originalHeight - templateHeight - 5) + 5;
  202. }
  203. return new PointModel(x, y);
  204. }
  205. /// <summary>
  206. /// 随机生成干扰图坐标
  207. /// </summary>
  208. /// <param name="originalWidth"></param>
  209. /// <param name="originalHeight"></param>
  210. /// <param name="templateWidth"></param>
  211. /// <param name="templateHeight"></param>
  212. /// <param name="blockX"></param>
  213. /// <param name="blockY"></param>
  214. /// <returns></returns>
  215. private PointModel GenerateInterferencePoint(int originalWidth, int originalHeight, int templateWidth, int templateHeight, int blockX, int blockY)
  216. {
  217. int x;
  218. if (originalWidth - blockX - 5 > templateWidth * 2)
  219. {
  220. //在原扣图右边插入干扰图
  221. x = GetRandomInt(blockX + templateWidth + 5, originalWidth - templateWidth);
  222. }
  223. else
  224. {
  225. //在原扣图左边插入干扰图
  226. x = GetRandomInt(100, blockX - templateWidth - 5);
  227. }
  228. int y;
  229. if (originalHeight - blockY - 5 > templateHeight * 2)
  230. {
  231. //在原扣图下边插入干扰图
  232. y = GetRandomInt(blockY + templateHeight + 5, originalHeight - templateHeight);
  233. }
  234. else
  235. {
  236. //在原扣图上边插入干扰图
  237. y = GetRandomInt(5, blockY - templateHeight - 5);
  238. }
  239. return new PointModel(x, y);
  240. }
  241. /// <summary>
  242. /// 获得验证数据
  243. /// </summary>
  244. /// <returns>JObject</returns>
  245. public async Task<CaptchaOutput> GetAsync()
  246. {
  247. //获取网络图片
  248. //var client = new HttpClient();
  249. //var stream = await client.GetStreamAsync("https://picsum.photos/310/155");
  250. //client.Dispose();
  251. //Bitmap baseImage = new Bitmap(stream);
  252. //stream.Dispose();
  253. var oriImage = Image.FromFile($@"{Directory.GetCurrentDirectory()}\wwwroot\captcha\jigsaw\{new Random().Next(1, 4)}.jpg".ToPath());
  254. //更改图片尺寸
  255. //Bitmap baseImage = ResizeImage(oriImage, 310, 155);
  256. Bitmap baseImage = new Bitmap(oriImage);
  257. oriImage.Dispose();
  258. var oriTemplate = Image.FromFile($@"{Directory.GetCurrentDirectory()}\wwwroot\captcha\jigsaw\templates\{new Random().Next(1, 7)}.png".ToPath());
  259. Bitmap templateImage = new Bitmap(oriTemplate);
  260. oriTemplate.Dispose();
  261. int baseWidth = baseImage.Width;
  262. int baseHeight = baseImage.Height;
  263. int templateWidth = templateImage.Width;
  264. int templateHeight = templateImage.Height;
  265. //随机生成拼图坐标
  266. PointModel point = GeneratePoint(baseWidth, baseHeight, templateWidth, templateHeight);
  267. int x = point.X;
  268. int y = point.Y;
  269. //生成拼图
  270. string blockImageBase64 = "data:image/png;base64," + ImgToBase64String(CutByTemplate(baseImage, templateImage, x, y));
  271. //生成干扰图
  272. PointModel interferencePoint = GenerateInterferencePoint(baseWidth, baseHeight, templateWidth, templateHeight, x, y);
  273. InterferenceByTemplate(baseImage, templateImage, interferencePoint.X, interferencePoint.Y);
  274. string baseImageBase64 = "data:image/png;base64," + ImgToBase64String(baseImage);
  275. templateImage.Dispose();
  276. baseImage.Dispose();
  277. var token = Guid.NewGuid().ToString();
  278. CaptchaOutput captchaData = new CaptchaOutput
  279. {
  280. Token = token,
  281. Data = new SlideJigsawCaptchaModel()
  282. {
  283. BlockImage = blockImageBase64,
  284. BaseImage = baseImageBase64
  285. }
  286. };
  287. var key = string.Format(CacheKey.VerifyCodeKey, token);
  288. await _cache.SetAsync(key, point.X);
  289. return captchaData;
  290. }
  291. /// <summary>
  292. /// 检查验证数据
  293. /// </summary>
  294. /// <param name="input"></param>
  295. /// <returns></returns>
  296. public async Task<bool> CheckAsync(CaptchaInput input)
  297. {
  298. if (input == null || input.Data.IsNull())
  299. {
  300. return false;
  301. }
  302. var key = string.Format(CacheKey.VerifyCodeKey, input.Token);
  303. if (await _cache.ExistsAsync(key))
  304. {
  305. try
  306. {
  307. var point = JsonConvert.DeserializeObject<PointModel>(input.Data);
  308. var x = await _cache.GetAsync<int>(key);
  309. if (Math.Abs(x - point.X) < 5)
  310. {
  311. if (input.DeleteCache)
  312. {
  313. await _cache.DelAsync(key);
  314. }
  315. return true;
  316. }
  317. else
  318. {
  319. await _cache.DelAsync(key);
  320. return false;
  321. }
  322. }
  323. catch
  324. {
  325. await _cache.DelAsync(key);
  326. return false;
  327. }
  328. }
  329. else
  330. {
  331. return false;
  332. }
  333. }
  334. }
  335. }