SlideJigsawCaptcha.cs 13 KB

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