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.