/// <summary>
/// 剪切白边(上下左右)
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
public static Bitmap Crop(Bitmap b)
{
int x, y;//for use of X,Y Coordinates of pixels
Color c = new Color(); //pixel color for use of identifying if background
int intLeft = 0;//furthest left X coordinate
int intRight = 0;//furthest right X coordinate
int intBottom = 0;//furthest to the bottom Y coordinate
int intTop = 0;
y = 0;
while (y < b.Height)
{
x = 0;
while (x < b.Width) //loop through pixels on X axis until end of image width
{
c = b.GetPixel(x, y); //Get the color of the pixel
if (c.R != 255 && c.R != 0 && c.G != 255 && c.G != 0 && c.B != 255 && c.B != 0)
{
if (c.R < 240 || c.G < 240 || c.B < 240)
{
//Determine if pixel is further left than the value we already have
if (intLeft == 0 || intLeft > x)
{
intLeft = x;
}
//Determine if pixel is further to the top than the value we already have
if (intTop == 0 || intTop > y)
{
intTop = y;
}
//Determine if pixel is further right than the value we already have
if (intRight <= b.Width && intRight < x)
{
intRight = x;
}
//Determine if pixel is further to the bottom than the value we already have
if (intBottom <= b.Height && intBottom < y)
{
intBottom = y;
}
}
}
x += 1;
}
y += 1;
}
Bitmap imgCropped = new Bitmap(b.Width - 2 * intLeft, b.Height - 2 * intTop);
Graphics objGraphics = Graphics.FromImage(imgCropped);
objGraphics.Clear(System.Drawing.Color.Transparent);
RectangleF imagerec = new RectangleF(intLeft, intTop, b.Width - 2 * intLeft, b.Height- 2 * intTop);
objGraphics.DrawImage(b, new Rectangle(0, 0, b.Width - 2 * intLeft, b.Height- 2 * intTop), imagerec, GraphicsUnit.Pixel);
b.Dispose();
objGraphics.Dispose();
return imgCropped;
}
转载于:https://www.cnblogs.com/FightingJia/p/5703973.html