标签:
using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; namespace ConsoleApplication1 { class ImageUtil { public static void ClearBlank(string sourceFileName, string targetFileName) { var srcBmp = new Bitmap(sourceFileName); var rect = new Rectangle(0, 0, srcBmp.Width, srcBmp.Height); var srcBmpData = srcBmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); var srcPtr = srcBmpData.Scan0; var scanWidth = srcBmpData.Width * 3; var srcBytes = scanWidth * srcBmp.Height; var srcRgbValues = new byte[srcBytes]; Marshal.Copy(srcPtr, srcRgbValues, 0, srcBytes); /*************************************************************************************/ //从下向上 int k = 0; int lastRow = 0; var found = false; for (var i = srcBmp.Height - 1; i >= 0; i--) { for (var j = 0; j < srcBmp.Width; j++) { k = 3 * j; var r = srcRgbValues[i * scanWidth + k + 0]; var g = srcRgbValues[i * scanWidth + k + 1]; var b = srcRgbValues[i * scanWidth + k + 2]; if (r + g + b < 255 * 3) { lastRow = i; found = true; break; } } if (found) { break; } } //从上向下 k = 0; found = false; var firstRow = 0; for (var i = 0; i < srcBmp.Height; i++) { for (var j = 0; j < srcBmp.Width; j++) { k = 3 * j; var r = srcRgbValues[i * scanWidth + k + 0]; var g = srcRgbValues[i * scanWidth + k + 1]; var b = srcRgbValues[i * scanWidth + k + 2]; if (r + g + b < 255 * 3) { firstRow = i; found = true; break; } } if (found) { break; } } //从左向右 k = 0; found = false; var firstCol = 0; for (var i = 0; i < srcBmp.Width; i++) { for (var j = 0; j < srcBmp.Height; j++) { k = 3 * i; var r = srcRgbValues[j * scanWidth + k + 0]; var g = srcRgbValues[j * scanWidth + k + 1]; var b = srcRgbValues[j * scanWidth + k + 2]; if (r + g + b < 255 * 3) { firstCol = i; found = true; break; } } if (found) { break; } } //从右向左 k = 0; found = false; var lastCol = 0; for (var i = srcBmp.Width - 1; i >= 0; i--) { for (var j = srcBmp.Height - 1; j >= 0; j--) { k = 3 * i; var r = srcRgbValues[j * scanWidth + k + 0]; var g = srcRgbValues[j * scanWidth + k + 1]; var b = srcRgbValues[j * scanWidth + k + 2]; if (r + g + b < 255 * 3) { lastCol = i; found = true; break; } } if (found) { break; } } //解锁位图 srcBmp.UnlockBits(srcBmpData); const int yuLiang = 3; var t = CutImage(srcBmp, new Rectangle(firstCol - yuLiang, firstRow -yuLiang, lastCol - firstCol + 2* yuLiang, Math.Abs(lastRow - firstRow) + 2* yuLiang)); t.Save(targetFileName, ImageFormat.Png); t.Dispose(); } private static Bitmap CutImage(Image img, Rectangle rect) { var b = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb); var g = Graphics.FromImage(b); g.DrawImage(img, 0, 0, rect, GraphicsUnit.Pixel); g.Dispose(); return b; } } }
标签:
原文地址:http://www.cnblogs.com/littlehb/p/5119123.html