예제 #1
0
        /// <summary>
        /// Detects the widest and tallest pixels to determine the image padding based on the optional background color.
        /// </summary>
        /// <param name="image">The original image</param>
        /// <param name="backgroundColor">Specifies a background color for this image or transparent by default.</param>
        /// <returns>A rectangle containing the borders of this image's content.</returns>
        public static Rectangle DetectPadding(this Image image, Color backgroundColor = default(Color))
        {
            if (backgroundColor.IsEmpty)
            {
                backgroundColor = Color.Transparent;
            }

            var top    = image.Height;
            var bottom = 0;
            var left   = image.Width;
            var right  = 0;
            var width  = image.Width - 1;
            var height = image.Height - 1;

            using (var context = new UnsafeBitmapContext(image))
            {
                for (int y = 0; y < context.Height; y++)
                {
                    for (int x = 0; x < context.Width; x++)
                    {
                        if (width - right <= x && left <= x && height - bottom <= y)
                        {
                            break;
                        }
                        if (x < left && !context.GetRawPixel(x, y).EqualsColor(backgroundColor))
                        {
                            if (y < top)
                            {
                                top = y;
                            }
                            left = x;
                        }
                        if (x < width - right && !context.GetRawPixel(width - x, y).EqualsColor(backgroundColor))
                        {
                            if (y < top)
                            {
                                top = y;
                            }
                            right = width - x;
                        }
                        if (y < height - bottom && !context.GetRawPixel(x, height - y).EqualsColor(backgroundColor))
                        {
                            bottom = height - y;
                        }
                    }
                }
            }
            width  = Math.Max(0, right - left);
            height = Math.Max(0, bottom - top);
            return(new Rectangle(left, top, width, height));
        }
예제 #2
0
 /// <summary>
 /// Compares a pixel and color and determines equality.
 /// </summary>
 public static bool EqualsPixel(this Color color, UnsafeBitmapContext.Pixel pixel)
 {
     return pixel.EqualsColor(color);
 }