// // Copyright (c) James Jackson-South and contributors. // Licensed under the Apache License, Version 2.0. // namespace ImageSharp.Processing.Processors { using System; using System.Threading.Tasks; /// /// Provides methods to allow the cropping of an image. /// /// The pixel format. public class CropProcessor : ImageProcessor where TColor : struct, IPackedPixel, IEquatable { /// /// Initializes a new instance of the class. /// /// The target cropped rectangle. public CropProcessor(Rectangle cropRectangle) { this.CropRectangle = cropRectangle; } /// /// Gets the width. /// public Rectangle CropRectangle { get; } /// protected override void OnApply(ImageBase source, Rectangle sourceRectangle) { if (this.CropRectangle == sourceRectangle) { return; } int minY = Math.Max(this.CropRectangle.Y, sourceRectangle.Y); int maxY = Math.Min(this.CropRectangle.Bottom, sourceRectangle.Bottom); int minX = Math.Max(this.CropRectangle.X, sourceRectangle.X); int maxX = Math.Min(this.CropRectangle.Right, sourceRectangle.Right); TColor[] target = PixelPool.RentPixels(this.CropRectangle.Width * this.CropRectangle.Height); using (PixelAccessor sourcePixels = source.Lock()) using (PixelAccessor targetPixels = target.Lock(this.CropRectangle.Width, this.CropRectangle.Height)) { Parallel.For( minY, maxY, this.ParallelOptions, y => { for (int x = minX; x < maxX; x++) { targetPixels[x - minX, y - minY] = sourcePixels[x, y]; } }); } source.SetPixels(this.CropRectangle.Width, this.CropRectangle.Height, target); } } }