Justin808
Justin808

Reputation: 21522

c# auto-crop an image

I have a black and white System.Drawing.Bitmap I need to auto-crop it so that it is only as big as needed to fit the image. This image always starts at the top left (0,0) position but I'm not sure how much height and width is will require. If there any way to auto-crop it to size?

Upvotes: 1

Views: 3748

Answers (2)

test
test

Reputation: 2639

If your image does not start at 0,0 like mine, here is a variant that gets you the auto-crop bounds:

public static Rectangle GetAutoCropBounds(Bitmap bitmap)
{
    int maxX = 0;
    int maxY = 0;

    int minX = bitmap.Width;
    int minY = bitmap.Height;

    for (int x = 0; x < bitmap.Width; x++)
    {
        for (int y = 0; y < bitmap.Height; y++)
        {
            var c = bitmap.GetPixel(x, y);
            var w = Color.White;
            if (c.R != w.R || c.G != w.G || c.B != w.B)
            {
                if (x > maxX)
                    maxX = x;
                if (x < minX)
                    minX = x;
                if (y > maxY)
                    maxY = y;
                if (y < minY)
                    minY = y;
            }
        }
    }

    maxX += 2;

    return new Rectangle(minX, minY, maxX - minX, maxY - minY);
}

Note: if you are processing any amount of images in quantity or high-resolution then you'll want to look into faster alternatives than the GetPixel method.

Upvotes: 0

Justin808
Justin808

Reputation: 21522

The following is the code I used:

    // Figure out the final size
    int maxX = 0;
    int maxY = 0;
    for (int x = 0; x < bitmap.Width; x++)
    {
        for (int y = 0; y < bitmap.Height; y++)
        {
            System.Drawing.Color c = bitmap.GetPixel(x, y);
            System.Drawing.Color w = System.Drawing.Color.White;
            if (c.R != w.R || c.G != w.G || c.B != w.B)
            {
                if (x > maxX)
                    maxX = x;
                if (y > maxY)
                    maxY = y;
            }
        }
    }
    maxX += 2;

Upvotes: 1

Related Questions