private static Bitmap CropBitmapAndUnlok(FastBitmap bmp, Color backgroundColor) { int y = 0; int x; Color c = backgroundColor; int backgroundArgb = backgroundColor.ToArgb(); // Crop top while (y < bmp.Height && IsBackgroundColor(c, backgroundArgb)) { c = bmp.GetPixel(0, y); if (IsBackgroundColor(c, backgroundArgb)) { for (x = 1; x < bmp.Width; x++) { c = bmp.GetPixelNext(); if (c.A != 0 && c.ToArgb() != backgroundArgb) break; } } if (IsBackgroundColor(c, backgroundArgb)) y++; } int minY = y; if (minY > 3) minY -= 3; else minY = 0; // Crop left x = 0; c = backgroundColor; while (x < bmp.Width && IsBackgroundColor(c, backgroundArgb)) { for (y = minY; y < bmp.Height; y++) { c = bmp.GetPixel(x, y); if (!IsBackgroundColor(c, backgroundArgb)) break; } if (IsBackgroundColor(c, backgroundArgb)) x++; } int minX = x; if (minX > 3) minX -= 3; else minX -= 0; // Crop bottom y = bmp.Height - 1; c = backgroundColor; while (y > minY && IsBackgroundColor(c, backgroundArgb)) { c = bmp.GetPixel(0, y); if (IsBackgroundColor(c, backgroundArgb)) { for (x = 1; x < bmp.Width; x++) { c = bmp.GetPixelNext(); if (!IsBackgroundColor(c, backgroundArgb)) break; } } if (IsBackgroundColor(c, backgroundArgb)) y--; } int maxY = y + 7; if (maxY >= bmp.Height) maxY = bmp.Height - 1; // Crop right x = bmp.Width - 1; c = backgroundColor; while (x > minX && IsBackgroundColor(c, backgroundArgb)) { for (y = minY; y < bmp.Height; y++) { c = bmp.GetPixel(x, y); if (!IsBackgroundColor(c, backgroundArgb)) break; } if (IsBackgroundColor(c, backgroundArgb)) x--; } int maxX = x + 7; if (maxX >= bmp.Width) maxX = bmp.Width - 1; bmp.UnlockImage(); Bitmap bmpImage = bmp.GetBitmap(); if (bmpImage.Width > 1 && bmpImage.Height > 1 && maxX - minX > 0 && maxY - minY > 0) { Bitmap bmpCrop = bmpImage.Clone(new Rectangle(minX, minY, maxX - minX, maxY - minY), bmpImage.PixelFormat); return bmpCrop; } return (Bitmap)bmpImage.Clone(); }