ImageBorderRemover.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. using Masuit.Tools.Systems;
  2. using SixLabors.ImageSharp;
  3. using SixLabors.ImageSharp.PixelFormats;
  4. using SixLabors.ImageSharp.Processing;
  5. namespace Masuit.Tools.Media;
  6. /// <summary>
  7. /// 图像边框移除器
  8. /// </summary>
  9. public class ImageBorderRemover
  10. {
  11. /// <summary>
  12. /// 检测图片边框信息(支持多色边框)
  13. /// </summary>
  14. /// <param name="imagePath">图片路径</param>
  15. /// <param name="tolerance">颜色容差(0-100),默认10</param>
  16. /// <param name="maxLayers">最大检测边框层数,默认3</param>
  17. /// <param name="useDownscaling">是否使用缩小采样优化性能,默认true</param>
  18. /// <param name="downscaleFactor">缩小采样比例(1-10),默认4</param>
  19. /// <returns>边框检测结果</returns>
  20. public static BorderDetectionResult DetectBorders(string imagePath, int tolerance = 10, int maxLayers = 3, bool useDownscaling = true, int downscaleFactor = 4)
  21. {
  22. using (Image<Rgba32> image = Image.Load<Rgba32>(imagePath))
  23. {
  24. return DetectBorders(image, tolerance, maxLayers, useDownscaling, downscaleFactor);
  25. }
  26. }
  27. /// <summary>
  28. /// 检测图片边框信息(从已加载的图像)
  29. /// </summary>
  30. /// <param name="image">已加载的图像</param>
  31. /// <param name="tolerance">颜色容差(0-100),默认10</param>
  32. /// <param name="maxLayers">最大检测边框层数,默认3</param>
  33. /// <param name="useDownscaling">是否使用缩小采样优化性能,默认true</param>
  34. /// <param name="downscaleFactor">缩小采样比例(1-10),默认4</param>
  35. /// <returns>边框检测结果</returns>
  36. public static BorderDetectionResult DetectBorders(Image<Rgba32> image, int tolerance = 10, int maxLayers = 3, bool useDownscaling = true, int downscaleFactor = 4)
  37. {
  38. var result = new BorderDetectionResult
  39. {
  40. ImageWidth = image.Width,
  41. ImageHeight = image.Height,
  42. BorderColors = new List<Rgba32>(),
  43. BorderLayers = 0
  44. };
  45. byte toleranceValue = (byte)(tolerance * 2.55);
  46. // 使用多层边框检测算法
  47. var (top, bottom, left, right, layers, colors) = FindContentBordersWithLayers(image, toleranceValue, maxLayers, useDownscaling, downscaleFactor);
  48. // 设置内容边界
  49. result.ContentTop = top;
  50. result.ContentBottom = bottom;
  51. result.ContentLeft = left;
  52. result.ContentRight = right;
  53. result.BorderLayers = layers;
  54. result.BorderColors = colors;
  55. return result;
  56. }
  57. /// <summary>
  58. /// 自动移除图片的多层边框(仅当至少有两边存在边框时才裁剪)
  59. /// </summary>
  60. /// <param name="inputPath">输入图片路径</param>
  61. /// <param name="tolerance">颜色容差(0-100),默认10</param>
  62. /// <param name="maxLayers">最大检测边框层数,默认3</param>
  63. /// <returns>是否执行了裁剪操作</returns>
  64. public static void RemoveBorders(string inputPath, int tolerance = 10, int maxLayers = 3)
  65. {
  66. RemoveBorders(inputPath, inputPath, tolerance, maxLayers);
  67. }
  68. /// <summary>
  69. /// 自动移除图片的多层边框(仅当至少有两边存在边框时才裁剪)
  70. /// </summary>
  71. /// <param name="inputPath">输入图片路径</param>
  72. /// <param name="outputPath">输出图片路径</param>
  73. /// <param name="tolerance">颜色容差(0-100),默认10</param>
  74. /// <param name="maxLayers">最大检测边框层数,默认3</param>
  75. /// <param name="useDownscaling">是否使用缩小采样优化性能,默认true</param>
  76. /// <param name="downscaleFactor">缩小采样比例(1-10),默认4</param>
  77. /// <returns>是否执行了裁剪操作</returns>
  78. public static void RemoveBorders(string inputPath, string outputPath, int tolerance = 10, int maxLayers = 3, bool useDownscaling = true, int downscaleFactor = 4)
  79. {
  80. using Image<Rgba32> image = Image.Load<Rgba32>(inputPath);
  81. var hasCropped = RemoveBorders(image, tolerance, maxLayers, useDownscaling, downscaleFactor);
  82. // 决定是否保存
  83. if (hasCropped)
  84. {
  85. image.Save(outputPath);
  86. }
  87. }
  88. /// <summary>
  89. /// 自动移除图片的多层边框(仅当至少有两边存在边框时才裁剪)
  90. /// </summary>
  91. /// <param name="input">输入图片路径</param>
  92. /// <param name="tolerance">颜色容差(0-100),默认10</param>
  93. /// <param name="maxLayers">最大检测边框层数,默认3</param>
  94. /// <param name="useDownscaling">是否使用缩小采样优化性能,默认true</param>
  95. /// <param name="downscaleFactor">缩小采样比例(1-10),默认4</param>
  96. /// <returns>是否执行了裁剪操作</returns>
  97. public static PooledMemoryStream RemoveBorders(Stream input, int tolerance = 10, int maxLayers = 3, bool useDownscaling = true, int downscaleFactor = 4)
  98. {
  99. var format = Image.DetectFormat(input);
  100. input.Seek(0, SeekOrigin.Begin);
  101. Image<Rgba32> image = Image.Load<Rgba32>(input);
  102. RemoveBorders(image, tolerance, maxLayers, useDownscaling, downscaleFactor);
  103. var stream = new PooledMemoryStream();
  104. image.Save(stream, format);
  105. return stream;
  106. }
  107. private static bool RemoveBorders(Image<Rgba32> image, int tolerance, int maxLayers, bool useDownscaling, int downscaleFactor)
  108. {
  109. // 保存原始尺寸用于比较
  110. int originalWidth = image.Width;
  111. int originalHeight = image.Height;
  112. // 使用多层检测方法获取边框信息
  113. var borderInfo = DetectBorders(image, tolerance, maxLayers, useDownscaling, downscaleFactor);
  114. bool hasCropped = false;
  115. if (borderInfo.CanBeCropped)
  116. {
  117. int newWidth = borderInfo.ContentRight - borderInfo.ContentLeft + 1;
  118. int newHeight = borderInfo.ContentBottom - borderInfo.ContentTop + 1;
  119. if (newWidth > 0 && newHeight > 0 && (newWidth != originalWidth || newHeight != originalHeight))
  120. {
  121. image.Mutate(x => x.Crop(new Rectangle(borderInfo.ContentLeft, borderInfo.ContentTop, newWidth, newHeight)));
  122. hasCropped = true;
  123. }
  124. }
  125. return hasCropped;
  126. }
  127. /// <summary>
  128. /// 查找内容边界(支持多层边框检测)
  129. /// </summary>
  130. private static (int top, int bottom, int left, int right, int layers, List<Rgba32> colors) FindContentBordersWithLayers(Image<Rgba32> image, byte tolerance, int maxLayers, bool useDownscaling, int downscaleFactor)
  131. {
  132. // 如果启用缩小采样且图像足够大
  133. Image<Rgba32> workingImage;
  134. float scale = 1f;
  135. bool isDownscaled = false;
  136. if (useDownscaling && image.Width > 500 && image.Height > 500)
  137. {
  138. // 计算缩小尺寸
  139. int newWidth = image.Width / downscaleFactor;
  140. int newHeight = image.Height / downscaleFactor;
  141. scale = (float)image.Width / newWidth;
  142. // 创建缩小版本用于检测
  143. workingImage = image.Clone(ctx => ctx.Resize(newWidth, newHeight));
  144. isDownscaled = true;
  145. }
  146. else
  147. {
  148. workingImage = image;
  149. }
  150. int width = workingImage.Width;
  151. int height = workingImage.Height;
  152. int top = 0;
  153. int bottom = height - 1;
  154. int left = 0;
  155. int right = width - 1;
  156. int layers = 0;
  157. var borderColors = new List<Rgba32>();
  158. // 检测多层边框
  159. for (int layer = 0; layer < maxLayers; layer++)
  160. {
  161. bool borderFound = false;
  162. // 并行检测四个方向的边框层
  163. var results = new (int borderSize, Rgba32? color)[4];
  164. Parallel.Invoke(() =>
  165. {
  166. if (top < height / 2)
  167. {
  168. Rgba32? layerColor = null;
  169. int newTop = DetectLayerBorderTop(workingImage, top, bottom, left, right, tolerance, ref layerColor);
  170. results[0] = (newTop - top, layerColor);
  171. if (newTop > top) borderFound = true;
  172. top = newTop;
  173. }
  174. }, () =>
  175. {
  176. if (bottom > height / 2)
  177. {
  178. Rgba32? layerColor = null;
  179. int newBottom = DetectLayerBorderBottom(workingImage, top, bottom, left, right, tolerance, ref layerColor);
  180. results[1] = (newBottom - bottom, layerColor);
  181. if (newBottom < bottom) borderFound = true;
  182. bottom = newBottom;
  183. }
  184. }, () =>
  185. {
  186. if (left < width / 2)
  187. {
  188. Rgba32? layerColor = null;
  189. int newLeft = DetectLayerBorderLeft(workingImage, top, bottom, left, right, tolerance, ref layerColor);
  190. results[2] = (newLeft - left, layerColor);
  191. if (newLeft > left) borderFound = true;
  192. left = newLeft;
  193. }
  194. }, () =>
  195. {
  196. if (right > width / 2)
  197. {
  198. Rgba32? layerColor = null;
  199. int newRight = DetectLayerBorderRight(workingImage, top, bottom, left, right, tolerance, ref layerColor);
  200. results[3] = (newRight - right, layerColor);
  201. if (newRight < right) borderFound = true;
  202. right = newRight;
  203. }
  204. });
  205. // 收集检测到的边框颜色
  206. foreach (var (borderSize, color) in results)
  207. {
  208. if (color.HasValue && borderSize > 0)
  209. {
  210. borderColors.Add(color.Value);
  211. }
  212. }
  213. if (borderFound)
  214. {
  215. layers++;
  216. }
  217. else
  218. {
  219. break; // 没有检测到更多边框层
  220. }
  221. }
  222. // 如果是缩小采样版本,映射回原图坐标
  223. if (isDownscaled)
  224. {
  225. top = (int)(top * scale);
  226. bottom = (int)(bottom * scale);
  227. left = (int)(left * scale);
  228. right = (int)(right * scale);
  229. // 确保边界在图像范围内
  230. top = Clamp(top, 0, image.Height - 1);
  231. bottom = Clamp(bottom, top, image.Height - 1);
  232. left = Clamp(left, 0, image.Width - 1);
  233. right = Clamp(right, left, image.Width - 1);
  234. // 释放缩小图像
  235. workingImage.Dispose();
  236. }
  237. return (top, bottom, left, right, layers, borderColors);
  238. }
  239. private static int Clamp(int value, int min, int max)
  240. {
  241. return value < min ? min : value > max ? max : value;
  242. }
  243. /// <summary>
  244. /// 检测顶部边框层(优化版)
  245. /// </summary>
  246. private static int DetectLayerBorderTop(Image<Rgba32> image, int currentTop, int currentBottom, int currentLeft, int currentRight, byte tolerance, ref Rgba32? borderColor)
  247. {
  248. int newTop = currentTop;
  249. Rgba32? detectedColor = null;
  250. // 使用采样检测代替全行扫描
  251. int sampleCount = Math.Min(50, currentRight - currentLeft + 1);
  252. int stepX = Math.Max(1, (currentRight - currentLeft) / sampleCount);
  253. // 从当前顶部开始向下扫描
  254. for (int y = currentTop; y <= currentBottom; y++)
  255. {
  256. Rgba32? rowColor = null;
  257. bool isUniform = true;
  258. // 采样检查行是否统一颜色
  259. for (int x = currentLeft; x <= currentRight; x += stepX)
  260. {
  261. if (!rowColor.HasValue)
  262. {
  263. rowColor = image[x, y];
  264. continue;
  265. }
  266. if (!IsSimilarColor(image[x, y], rowColor.Value, tolerance))
  267. {
  268. isUniform = false;
  269. break;
  270. }
  271. }
  272. // 如果是统一颜色行
  273. if (isUniform && rowColor.HasValue)
  274. {
  275. // 第一行总是被认为是边框
  276. if (y == currentTop)
  277. {
  278. detectedColor = rowColor;
  279. newTop = y + 1;
  280. continue;
  281. }
  282. // 后续行必须与第一行颜色相似
  283. if (detectedColor.HasValue && IsSimilarColor(rowColor.Value, detectedColor.Value, tolerance))
  284. {
  285. newTop = y + 1;
  286. }
  287. else
  288. {
  289. break;
  290. }
  291. }
  292. else
  293. {
  294. break;
  295. }
  296. }
  297. if (newTop > currentTop)
  298. {
  299. borderColor = detectedColor;
  300. return newTop;
  301. }
  302. return currentTop;
  303. }
  304. /// <summary>
  305. /// 检测底部边框层(优化版)
  306. /// </summary>
  307. private static int DetectLayerBorderBottom(Image<Rgba32> image, int currentTop, int currentBottom, int currentLeft, int currentRight, byte tolerance, ref Rgba32? borderColor)
  308. {
  309. int newBottom = currentBottom;
  310. Rgba32? detectedColor = null;
  311. // 使用采样检测代替全行扫描
  312. int sampleCount = Math.Min(50, currentRight - currentLeft + 1);
  313. int stepX = Math.Max(1, (currentRight - currentLeft) / sampleCount);
  314. // 从当前底部开始向上扫描
  315. for (int y = currentBottom; y >= currentTop; y--)
  316. {
  317. Rgba32? rowColor = null;
  318. bool isUniform = true;
  319. // 采样检查行是否统一颜色
  320. for (int x = currentLeft; x <= currentRight; x += stepX)
  321. {
  322. if (!rowColor.HasValue)
  323. {
  324. rowColor = image[x, y];
  325. continue;
  326. }
  327. if (!IsSimilarColor(image[x, y], rowColor.Value, tolerance))
  328. {
  329. isUniform = false;
  330. break;
  331. }
  332. }
  333. if (isUniform && rowColor.HasValue)
  334. {
  335. if (y == currentBottom)
  336. {
  337. detectedColor = rowColor;
  338. newBottom = y - 1;
  339. continue;
  340. }
  341. if (detectedColor.HasValue && IsSimilarColor(rowColor.Value, detectedColor.Value, tolerance))
  342. {
  343. newBottom = y - 1;
  344. }
  345. else
  346. {
  347. break;
  348. }
  349. }
  350. else
  351. {
  352. break;
  353. }
  354. }
  355. if (newBottom < currentBottom)
  356. {
  357. borderColor = detectedColor;
  358. return newBottom;
  359. }
  360. return currentBottom;
  361. }
  362. /// <summary>
  363. /// 检测左侧边框层(优化版)
  364. /// </summary>
  365. private static int DetectLayerBorderLeft(Image<Rgba32> image, int currentTop, int currentBottom, int currentLeft, int currentRight, byte tolerance, ref Rgba32? borderColor)
  366. {
  367. int newLeft = currentLeft;
  368. Rgba32? detectedColor = null;
  369. // 使用采样检测代替全列扫描
  370. int sampleCount = Math.Min(50, currentBottom - currentTop + 1);
  371. int stepY = Math.Max(1, (currentBottom - currentTop) / sampleCount);
  372. // 从当前左侧开始向右扫描
  373. for (int x = currentLeft; x <= currentRight; x++)
  374. {
  375. Rgba32? colColor = null;
  376. bool isUniform = true;
  377. // 采样检查列是否统一颜色
  378. for (int y = currentTop; y <= currentBottom; y += stepY)
  379. {
  380. if (!colColor.HasValue)
  381. {
  382. colColor = image[x, y];
  383. continue;
  384. }
  385. if (!IsSimilarColor(image[x, y], colColor.Value, tolerance))
  386. {
  387. isUniform = false;
  388. break;
  389. }
  390. }
  391. if (isUniform && colColor.HasValue)
  392. {
  393. if (x == currentLeft)
  394. {
  395. detectedColor = colColor;
  396. newLeft = x + 1;
  397. continue;
  398. }
  399. if (detectedColor.HasValue && IsSimilarColor(colColor.Value, detectedColor.Value, tolerance))
  400. {
  401. newLeft = x + 1;
  402. }
  403. else
  404. {
  405. break;
  406. }
  407. }
  408. else
  409. {
  410. break;
  411. }
  412. }
  413. if (newLeft > currentLeft)
  414. {
  415. borderColor = detectedColor;
  416. return newLeft;
  417. }
  418. return currentLeft;
  419. }
  420. /// <summary>
  421. /// 检测右侧边框层(优化版)
  422. /// </summary>
  423. private static int DetectLayerBorderRight(Image<Rgba32> image, int currentTop, int currentBottom, int currentLeft, int currentRight, byte tolerance, ref Rgba32? borderColor)
  424. {
  425. int newRight = currentRight;
  426. Rgba32? detectedColor = null;
  427. // 使用采样检测代替全列扫描
  428. int sampleCount = Math.Min(50, currentBottom - currentTop + 1);
  429. int stepY = Math.Max(1, (currentBottom - currentTop) / sampleCount);
  430. // 从当前右侧开始向左扫描
  431. for (int x = currentRight; x >= currentLeft; x--)
  432. {
  433. Rgba32? colColor = null;
  434. bool isUniform = true;
  435. // 采样检查列是否统一颜色
  436. for (int y = currentTop; y <= currentBottom; y += stepY)
  437. {
  438. if (!colColor.HasValue)
  439. {
  440. colColor = image[x, y];
  441. continue;
  442. }
  443. if (!IsSimilarColor(image[x, y], colColor.Value, tolerance))
  444. {
  445. isUniform = false;
  446. break;
  447. }
  448. }
  449. if (isUniform && colColor.HasValue)
  450. {
  451. if (x == currentRight)
  452. {
  453. detectedColor = colColor;
  454. newRight = x - 1;
  455. continue;
  456. }
  457. if (detectedColor.HasValue && IsSimilarColor(colColor.Value, detectedColor.Value, tolerance))
  458. {
  459. newRight = x - 1;
  460. }
  461. else
  462. {
  463. break;
  464. }
  465. }
  466. else
  467. {
  468. break;
  469. }
  470. }
  471. if (newRight < currentRight)
  472. {
  473. borderColor = detectedColor;
  474. return newRight;
  475. }
  476. return currentRight;
  477. }
  478. /// <summary>
  479. /// 颜色相似度比较(SIMD优化)
  480. /// </summary>
  481. private static bool IsSimilarColor(Rgba32 color1, Rgba32 color2, byte tolerance)
  482. {
  483. // 使用快速比较算法
  484. int diffR = Math.Abs(color1.R - color2.R);
  485. int diffG = Math.Abs(color1.G - color2.G);
  486. int diffB = Math.Abs(color1.B - color2.B);
  487. // 快速路径:如果任一通道差异超过容差
  488. if (diffR > tolerance || diffG > tolerance || diffB > tolerance)
  489. return false;
  490. // 精确比较
  491. return diffR <= tolerance && diffG <= tolerance && diffB <= tolerance;
  492. }
  493. }
  494. /// <summary>
  495. /// 边框检测结果(包含多层边框信息)
  496. /// </summary>
  497. public struct BorderDetectionResult
  498. {
  499. /// <summary>原始图片宽度</summary>
  500. public int ImageWidth { get; set; }
  501. /// <summary>原始图片高度</summary>
  502. public int ImageHeight { get; set; }
  503. /// <summary>内容上边界位置</summary>
  504. public int ContentTop { get; set; }
  505. /// <summary>内容下边界位置</summary>
  506. public int ContentBottom { get; set; }
  507. /// <summary>内容左边界位置</summary>
  508. public int ContentLeft { get; set; }
  509. /// <summary>内容右边界位置</summary>
  510. public int ContentRight { get; set; }
  511. /// <summary>检测到的边框层数</summary>
  512. public int BorderLayers { get; set; }
  513. /// <summary>边框颜色层次(从外到内)</summary>
  514. public List<Rgba32> BorderColors { get; set; }
  515. /// <summary>顶部边框总宽度(像素)</summary>
  516. public int TopBorderWidth => ContentTop;
  517. /// <summary>底部边框总宽度(像素)</summary>
  518. public int BottomBorderWidth => ImageHeight - 1 - ContentBottom;
  519. /// <summary>左侧边框总宽度(像素)</summary>
  520. public int LeftBorderWidth => ContentLeft;
  521. /// <summary>右侧边框总宽度(像素)</summary>
  522. public int RightBorderWidth => ImageWidth - 1 - ContentRight;
  523. /// <summary>是否有顶部边框</summary>
  524. public bool HasTopBorder => TopBorderWidth > 0;
  525. /// <summary>是否有底部边框</summary>
  526. public bool HasBottomBorder => BottomBorderWidth > 0;
  527. /// <summary>是否有左侧边框</summary>
  528. public bool HasLeftBorder => LeftBorderWidth > 0;
  529. /// <summary>是否有右侧边框</summary>
  530. public bool HasRightBorder => RightBorderWidth > 0;
  531. /// <summary>是否有任意边框</summary>
  532. public bool HasAnyBorder => BorderCount > 0;
  533. /// <summary>是否满足裁剪条件(至少两个边)</summary>
  534. public bool CanBeCropped => BorderCount >= 2;
  535. public int BorderCount => (HasTopBorder ? 1 : 0) + (HasBottomBorder ? 1 : 0) + (HasLeftBorder ? 1 : 0) + (HasRightBorder ? 1 : 0);
  536. /// <summary>内容区域宽度</summary>
  537. public int ContentWidth => ContentRight - ContentLeft + 1;
  538. /// <summary>内容区域高度</summary>
  539. public int ContentHeight => ContentBottom - ContentTop + 1;
  540. }