/// <summary>
/// 裁剪图片(去掉白色边沿)
/// </summary>
/// <param name="FilePath">图片路径</param>
public void RemoveWhiteEdge(string FilePath)
{
Bitmap bmp = new Bitmap(FilePath);
//上左右下
int top = 0, left = 0, right = bmp.Width, bottom = bmp.Height;
//寻找最上面的标线,从左(0)到右,从上(0)到下
for (int i = 0; i < bmp.Height; i++)//行
{
bool find = false;
for (int j = 0; j < bmp.Width; j++)//列
{
Color c = bmp.GetPixel(j, i);
if (!IsWhite(c))
{
top = i;
find = true;
break;
}
}
if (find)
break;
}
//寻找最左边的标线,从上(top位)到下,从左到右
for (int i = 0; i < bmp.Width; i++)//列
{
bool find = false;
for (int j = top; j < bmp.Height; j++)//行
{
Color c = bmp.GetPixel(i, j);
if (!IsWhite(c))
{
left = i;
find = true;
break;
}
}
if (find)
break;
}
//寻找最下边标线,从下到上,从左到右
for (int i = bmp.Height - 1; i >= 0; i--)//行
{
bool find = false;
for (int j = left; j < bmp.Width; j++)//列
{
Color c = bmp.GetPixel(j, i);
if (!IsWhite(c))
{
bottom = i;
find = true;
break;
}
}
if (find)
break;
}
//寻找最右边的标线,从上到下,从右往左
for (int i = bmp.Width - 1; i >= 0; i--)//列
{
bool find = false;
for (int j = 0; j <= bottom; j++)//行
{
Color c = bmp.GetPixel(i, j);
if (!IsWhite(c))
{
right = i;
find = true;
break;
}
}
if (find)
break;
}
//克隆位图对象的一部分。
Rectangle cloneRect = new Rectangle(left, top, right - left, bottom - top);
Bitmap cloneBitmap = bmp.Clone(cloneRect, bmp.PixelFormat);
cloneBitmap.Save(@"D:/123.png", ImageFormat.Png);
bmp.Dispose();
}
/// <summary>
/// 判断是否白色和纯透明色(10点的容差)
/// </summary>
public static bool IsWhite(Color c)
{
//纯透明也是白色,RGB都为255为纯白
if (c.A < 10 || (c.R > 245 && c.G > 245 && c.B > 245))
return true;
return false;
}