static void Test() { Bitmap bmp = new Bitmap(200,200); using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(Color.Yellow); g.FillRectangle(Brushes.Blue, new Rectangle(10, 10, 30, 50)); } bmp.MakeTransparent(Color.Blue); Rectangle rect = GetTransparentRect(bmp); // rect = {10,10,30,50) }static Rectangle GetTransparentRect(Bitmap bmp) { Rectangle rect = new Rectangle(0, 0, 0, 0); for (int y = 0; y < bmp.Height; y++) { for (int x = 0; x < bmp.Width; x++) { Color c = bmp.GetPixel(x, y); if (bmp.GetPixel(x, y).A == 0) // find the topLeft pixle whose Alpha == 0 { rect.Location = new Point(x, y); for (int w = x + 1; w < bmp.Width && bmp.GetPixel(w, y).A == 0; w++) { rect.Width = w - x + 1; } for (int w = y + 1; w < bmp.Height && bmp.GetPixel(x, w).A == 0; w++) { rect.Height = w - y + 1; } return rect; } } } return rect; }
{
Bitmap bmp = new Bitmap(200,200);
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.Yellow);
g.FillRectangle(Brushes.Blue, new Rectangle(10, 10, 30, 50));
}
bmp.MakeTransparent(Color.Blue); Rectangle rect = GetTransparentRect(bmp); // rect = {10,10,30,50)
}static Rectangle GetTransparentRect(Bitmap bmp)
{
Rectangle rect = new Rectangle(0, 0, 0, 0); for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{ Color c = bmp.GetPixel(x, y);
if (bmp.GetPixel(x, y).A == 0) // find the topLeft pixle whose Alpha == 0
{
rect.Location = new Point(x, y);
for (int w = x + 1; w < bmp.Width && bmp.GetPixel(w, y).A == 0; w++)
{
rect.Width = w - x + 1;
}
for (int w = y + 1; w < bmp.Height && bmp.GetPixel(x, w).A == 0; w++)
{
rect.Height = w - y + 1;
}
return rect;
}
}
}
return rect;
}