Question

I have a set of images of various objects of different shapes and sizes. They have transparent backgrounds set on them but the full dimension of the image is a square. I want to calculate a box of coordinates (upper left x/y, lower right x/y) that encompasses the object in the image while ignoring as much of the transparent background as possible. And I need to do this on the fly in code.

Is there an example, or a library, available for C# that would allow me to do this? I am using these in a website where several objects are dynamically overlaid into a single image and I want to calculate an image map with coordinates for each object in the merged image. Using the full size of the square image creates huge overlaps in the coordinate sets and often the last in coordinates hide the lower object from being clickable.

Was it helpful?

Solution

Well, using System.Drawing.Bitmap this is not too hard (the following certainly is not the most performant way):

// we will store actual bounds in here
int left, right, top, bottom;

using (Bitmap b = ...) // open image here
{
    var pixelsX = Enumerable.Range(0, b.Width);
    var pixelsY = Enumerable.Range(0, b.Height);

    left   = pixelsX.FirstOrDefault(
                x => pixelsY.Any(y => b.GetPixel(x, y).A != 0));
    right  = pixelsX.Reverse().FirstOrDefault(
                x => pixelsY.Any(y => b.GetPixel(x, y).A != 0));

    top    = pixelsY.FirstOrDefault(
                y => pixelsX.Any(x => b.GetPixel(x, y).A != 0));
    bottom = pixelsY.Reverse().FirstOrDefault(
                y => pixelsX.Any(x => b.GetPixel(x, y).A != 0));
}

Notice that all these 4 coordinates are "inclusive" bounds (meaning: the row/column of pixels they represent does contain at least one non-transparent pixel), so if you should calculate width and height of your new bounds do it like this:

int width = right - left + 1;
int height = bottom - top + 1;

By the way, for an entirely transparent image, all 4 coordinates should be 0, as a result width and height will both be 1 - I guess this is not a problem for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top