Duality.ExtMethodsBitmap.OpaqueBounds C# (CSharp) Method

OpaqueBounds() public static method

Measures the bounding rectangle of the opaque pixels in a Bitmap.
public static OpaqueBounds ( this bm ) : Rectangle
bm this
return System.Drawing.Rectangle
        public static Rectangle OpaqueBounds(this Bitmap bm)
        {
            ColorRgba[] pixels = bm.GetPixelDataRgba();
            Rectangle bounds = new Rectangle(bm.Width, bm.Height, 0, 0);
            for (int i = 0; i < pixels.Length; i++)
            {
                if (pixels[i].A == 0) continue;
                int x = i % bm.Width;
                int y = i / bm.Width;
                bounds.X = Math.Min(bounds.X, x);
                bounds.Y = Math.Min(bounds.Y, y);
                bounds.Width = Math.Max(bounds.Width, x);
                bounds.Height = Math.Max(bounds.Height, y);
            }
            bounds.Width = 1 + Math.Max(0, bounds.Width - bounds.X);
            bounds.Height = 1 + Math.Max(0, bounds.Height - bounds.Y);

            return bounds;
        }