代碼根據別人的進行改寫,效果更好
直接拷貝使用
名稱空間:
using System.Drawing;
代碼:
/// <summary> /// 裁剪圖片(去掉百邊) /// </summary> /// <param name="FilePath"></param> public static Bitmap CutImageWhitePart(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); bmp.Dispose(); //cloneBitmap.Save(@"d:\123.png", ImageFormat.Png); return cloneBitmap; } /// <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; }
調用:
Bitmap bitmap = CutImageWhitePart(@"C:\Users\Ping\Desktop\2.png"); bitmap.Save(@"d:\123.png", ImageFormat.Png);