using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Tango.RemoteDesktop.Clipping { public class BitmapCliper { public static ClipResult ClipBitmap(Bitmap img) { //get image data BitmapData bd = img.LockBits(new Rectangle(Point.Empty, img.Size), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); int[] rgbValues = new int[img.Height * img.Width]; Marshal.Copy(bd.Scan0, rgbValues, 0, rgbValues.Length); img.UnlockBits(bd); #region determine bounds int left = bd.Width; int top = bd.Height; int right = 0; int bottom = 0; //determine top for (int i = 0; i < rgbValues.Length; i++) { if (rgbValues[i] != 16777215) { int r = i / bd.Width; int c = i % bd.Width; if (left > c) { left = c; } if (right < c) { right = c; } bottom = r; top = r; break; } } //determine bottom for (int i = rgbValues.Length - 1; i >= 0; i--) { if (rgbValues[i] != 16777215) { int r = i / bd.Width; int c = i % bd.Width; if (left > c) { left = c; } if (right < c) { right = c; } bottom = r; break; } } if (bottom > top) { for (int r = top + 1; r < bottom; r++) { //determine left for (int c = 0; c < left; c++) { if (rgbValues[r * bd.Width + c] != 16777215) { if (left > c) { left = c; break; } } } //determine right for (int c = bd.Width - 1; c > right; c--) { if (rgbValues[r * bd.Width + c] != 16777215) { if (right < c) { right = c; break; } } } } } int width = right - left + 1; int height = bottom - top + 1; #endregion if (width < 0 || height < 0) { return new ClipResult() { Bitmap = new Bitmap(1, 1), Bounds = new Rectangle(0, 0, 1, 1) }; } //copy image data int[] imgData = new int[width * height]; for (int r = top; r <= bottom; r++) { Array.Copy(rgbValues, r * bd.Width + left, imgData, (r - top) * width, width); } //create new image Bitmap newImage = new Bitmap(width, height, PixelFormat.Format32bppArgb); BitmapData nbd = newImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); Marshal.Copy(imgData, 0, nbd.Scan0, imgData.Length); newImage.UnlockBits(nbd); return new ClipResult() { Bitmap = newImage, Bounds = new Rectangle(left, top, width, height) }; } } }