Make a Region from non-transparent pixels in C#


[region]

The example Make shaped PictureBoxes in C# sets the Region property of two PictureBox controls to circular regions. That works well in that example where the images are round volleyballs with transparent backgrounds, but it would be hard to manually create regions representing more irregular areas such as the ones used by this example.

This example uses the following method to automatically create a Region representing the non-transparent pixels in a bitmap.

// Make a region representing the
// image's non-transparent pixels.
public static Region MakeNonTransparentRegion(Bitmap bm)
{
    if (bm == null) return null;

    // Make the result region.
    Region result = new Region();
    result.MakeEmpty();

    Rectangle rect = new Rectangle(0, 0, 1, 1);
    bool in_image = false;
    for (int y = 0; y < bm.Height; y++)
    {
        for (int x = 0; x < bm.Width; x++)
        {
            if (!in_image)
            {
                // We're not now in the non-transparent pixels.
                if (bm.GetPixel(x, y).A != 0)
                {
                    // We just started into non-transparent pixels.
                    // Start a Rectangle to represent them.
                    in_image = true;
                    rect.X = x;
                    rect.Y = y;
                    rect.Height = 1;
                }
            }
            else if (bm.GetPixel(x, y).A == 0)
            {
                // We are in the non-transparent pixels and
                // have found a transparent one.
                // Add the rectangle so far to the region.
                in_image = false;
                rect.Width = (x - rect.X);
                result.Union(rect);
            }
        }

        // Add the final piece of the rectangle if necessary.
        if (in_image)
        {
            in_image = false;
            rect.Width = (bm.Width - rect.X);
            result.Union(rect);
        }
    }

    return result;
}

This method first makes an empty Region. It then loops through each row in the bitmap. It scans each row building horizontal strips of non-transparent pixels and adds a rectangle to the region representing each strip.

This method is relatively simple and handles odd cases such as images that include multiple disconnected non-transparent areas or areas with transparent holes.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in algorithms, geometry, graphics, image processing and tagged , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *