.net图片自动裁剪白边函数案例

时间:2023-03-09 01:37:15
.net图片自动裁剪白边函数案例

1.项目要求上传白底的图片要进行裁剪白边,于是同事谢了个函数感觉很好用。

2.

  #region 剪切白边
/// <summary>
/// 剪切白边
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
public static Image Crop(Image p)
{
int x, y ;//for use of X,Y Coordinates of pixels
Bitmap b = new Bitmap(p); //image needed to crop
Color c = new Color(); //pixel color for use of identifying if background
int intLeft=;//furthest left X coordinate
int intRight=;//furthest right X coordinate
int intBottom =;//furthest to the bottom Y coordinate
int intTop =;
y = ;
while(y < b.Height)
{
x = ;
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 != &&c.R!= && c.G != &&c.G!= && c.B != &&c.B!=)
{
if (c.R < || c.G < || c.B < )
{
//Determine if pixel is further left than the value we already have
if (intLeft == || intLeft > x )
{
intLeft = x;
}
//Determine if pixel is further to the top than the value we already have
if (intTop == || 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 += ;
}
y += ;
}
int intNewWidth = intRight; //Establish width of new cropped image
int intNewHeight = intBottom; //Establish height of new cropped image
Bitmap imgCropped =new Bitmap(intNewWidth - intLeft + , intNewHeight - intTop + );
Graphics objGraphics = Graphics.FromImage(imgCropped);
//set the background color to white (you can choose what you like
objGraphics.Clear(System.Drawing.Color.Transparent);
int intStartTop = - intTop; /// 40 + 5
int intStartLeft = - intLeft; /// 40 + 5
//Draw the original image to your new cropped sized image
objGraphics.DrawImage(b, intStartLeft, intStartTop);
b.Dispose();
objGraphics.Dispose();
//return the Cropped image to the caller
return imgCropped;
}