Example #1
0
        private static Bitmap QuickTrimTransparent(Bitmap bitmap)
        {
            Rectangle source = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            Rectangle rect   = source;

            using (UnsafeBitmap unsafeBitmap = new UnsafeBitmap(bitmap, true, ImageLockMode.ReadOnly))
            {
                int middleX = rect.Width / 2;
                int middleY = rect.Height / 2;

                // Find X
                for (int x = rect.X; x < rect.Width; x++)
                {
                    if (unsafeBitmap.GetPixel(x, middleY).Alpha > 0)
                    {
                        rect.X = x;
                        break;
                    }
                }

                // Find Y
                for (int y = rect.Y; y < rect.Height; y++)
                {
                    if (unsafeBitmap.GetPixel(middleX, y).Alpha > 0)
                    {
                        rect.Y = y;
                        break;
                    }
                }

                // Find Width
                for (int x = rect.Width - 1; x >= rect.X; x--)
                {
                    if (unsafeBitmap.GetPixel(x, middleY).Alpha > 0)
                    {
                        rect.Width = x - rect.X + 1;
                        break;
                    }
                }

                // Find Height
                for (int y = rect.Height - 1; y >= rect.Y; y--)
                {
                    if (unsafeBitmap.GetPixel(middleX, y).Alpha > 0)
                    {
                        rect.Height = y - rect.Y + 1;
                        break;
                    }
                }
            }

            if (source != rect)
            {
                return(CaptureHelpers.CropBitmap(bitmap, rect));
            }

            return(bitmap);
        }
Example #2
0
        private static Bitmap TrimTransparent(Bitmap bitmap)
        {
            Rectangle source = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            Rectangle rect   = source;

            using (UnsafeBitmap unsafeBitmap = new UnsafeBitmap(bitmap, true, ImageLockMode.ReadOnly))
            {
                rect = TrimTransparentFindX(unsafeBitmap, rect);
                rect = TrimTransparentFindY(unsafeBitmap, rect);
                rect = TrimTransparentFindWidth(unsafeBitmap, rect);
                rect = TrimTransparentFindHeight(unsafeBitmap, rect);
            }

            if (source != rect)
            {
                return(CaptureHelpers.CropBitmap(bitmap, rect));
            }

            return(bitmap);
        }