1
0

SlideJigsawCaptcha.cs 13 KB

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