using System; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; namespace MaddoShared.ImageSharpTests.Helpers { public static class PixelInspector { public static int CountNonBackgroundPixels(string path, int x, int y, int width, int height, Rgba32 background, int tolerance = 0) { using var img = SixLabors.ImageSharp.Image.Load(path); var bx = Math.Max(0, x); var by = Math.Max(0, y); var bw = Math.Min(width, img.Width - bx); var bh = Math.Min(height, img.Height - by); if (bw <= 0 || bh <= 0) return 0; int count = 0; img.ProcessPixelRows(accessor => { for (int yy = by; yy < by + bh; yy++) { var row = accessor.GetRowSpan(yy); for (int xx = bx; xx < bx + bw; xx++) { var p = row[xx]; if (!IsApproximatelyEqual(p, background, tolerance)) count++; } } }); return count; } private static bool IsApproximatelyEqual(Rgba32 a, Rgba32 b, int tol) { return Math.Abs(a.R - b.R) <= tol && Math.Abs(a.G - b.G) <= tol && Math.Abs(a.B - b.B) <= tol && Math.Abs(a.A - b.A) <= tol; } } }