1 /// <summary> 2 /// 裁剪图片(去掉白边) 3 /// </summary> 4 /// <param name="bmp">图片</param> 5 public static Bitmap CutImageWhitePart(Bitmap bmp) 6 { 7 //上左右下 8 int top = 0, left = 0, right = bmp.Width, bottom = bmp.Height; 9 10 //寻找最上面的标线,从左(0)到右,从上(0)到下 11 for (int i = 0; i < bmp.Height; i++)//行 12 { 13 bool find = false; 14 for (int j = 0; j < bmp.Width; j++)//列 15 { 16 Color c = bmp.GetPixel(j, i); 17 if (!IsWhite(c)) 18 { 19 top = i; 20 find = true; 21 break; 22 } 23 } 24 if (find) 25 break; 26 } 27 //寻找最左边的标线,从上(top位)到下,从左到右 28 for (int i = 0; i < bmp.Width; i++)//列 29 { 30 bool find = false; 31 for (int j = top; j < bmp.Height; j++)//行 32 { 33 Color c = bmp.GetPixel(i, j); 34 if (!IsWhite(c)) 35 { 36 left = i; 37 find = true; 38 break; 39 } 40 } 41 if (find) 42 break; 43 } 44 //寻找最下边标线,从下到上,从左到右 45 for (int i = bmp.Height - 1; i >= 0; i--)//行 46 { 47 bool find = false; 48 for (int j = left; j < bmp.Width; j++)//列 49 { 50 Color c = bmp.GetPixel(j, i); 51 if (!IsWhite(c)) 52 { 53 bottom = i; 54 find = true; 55 break; 56 } 57 } 58 if (find) 59 break; 60 } 61 //寻找最右边的标线,从上到下,从右往左 62 for (int i = bmp.Width - 1; i >= 0; i--)//列 63 { 64 bool find = false; 65 for (int j = 0; j <= bottom; j++)//行 66 { 67 Color c = bmp.GetPixel(i, j); 68 if (!IsWhite(c)) 69 { 70 right = i; 71 find = true; 72 break; 73 } 74 } 75 if (find) 76 break; 77 } 78 79 //克隆位图对象的一部分。 80 Rectangle cloneRect = new Rectangle(left, top, right - left, bottom - top); 81 Bitmap cloneBitmap = bmp.Clone(cloneRect, bmp.PixelFormat); 82 bmp.Dispose(); 83 //cloneBitmap.Save(@"d:123.png", ImageFormat.Png); 84 return cloneBitmap; 85 } 86 87 /// <summary> 88 /// 判断是否白色和纯透明色(10点的容差) 89 /// </summary> 90 public static bool IsWhite(Color c) 91 { 92 //纯透明也是白色,RGB都为255为纯白 93 if (c.A < 10 || (c.R > 245 && c.G > 245 && c.B > 245)) 94 return true; 95 96 return false; 97 }