开发者

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 w开发者_高级运维idth is will require. If there any way to auto-crop it to size?


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;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜