Example #1
0
        /// <summary>
        /// Crops the <see cref="Image"/> using rectangle calculated by <see cref="Image.BlackArea"/> method.
        /// </summary>
        /// <param name="dx">The amount by which to expand or shrink the left and right sides of the image black area.</param>
        /// <param name="dy">The amount by which to expand or shrink the top and bottom sides of the image black area.</param>
        /// <returns>
        /// A new cropped <see cref="Image"/>.
        /// </returns>
        /// <exception cref="NotSupportedException">
        /// <para>
        /// The <see cref="Image{T}.BitsPerPixel"/> is not 1.
        /// </para>
        /// </exception>
        public Image CropBlackArea(int dx, int dy)
        {
            // determine black area of the image
            Rectangle blackArea = this.BlackArea();

            if (dx == 0 && dy == 0)
            {
                // no frame - simply crop the black area
                return(this.Crop(blackArea));
            }

            // expand target area
            Rectangle bounds = Rectangle.Inflate(blackArea, dx, dy);

            Image dst = new Image(bounds.Size, this);

            if (!blackArea.IsEmpty)
            {
                Rectangle srcarea = Rectangle.Intersect(bounds, blackArea);
                Rectangle dstarea = Rectangle.Offset(srcarea, -bounds.X, -bounds.Y);
                Image.CopyArea(dst, dstarea.X, dstarea.Y, srcarea.Width, srcarea.Height, this, srcarea.X, srcarea.Y);

                if (this.BitsPerPixel > 1)
                {
                    // set frame to white
                    dst.SetWhiteBorder(dstarea);
                }
            }
            else
            {
                if (this.BitsPerPixel > 1)
                {
                    // set all image to white
                    Vectors.Set(dst.Bits.Length, ulong.MaxValue, dst.Bits, 0);
                }
            }

            dst.AppendTransform(new MatrixTransform(-bounds.X, -bounds.Y));
            return(dst);
        }