// // Copyright (c) James Jackson-South and contributors. // Licensed under the Apache License, Version 2.0. // namespace ImageSharp.Processing.Processors { using System; using System.Numerics; using System.Threading.Tasks; /// /// An to change the alpha component of an . /// /// The pixel format. public class AlphaProcessor : ImageProcessor where TColor : struct, IPackedPixel, IEquatable { /// /// Initializes a new instance of the class. /// /// The percentage to adjust the opacity of the image. Must be between 0 and 100. /// /// is less than 0 or is greater than 100. /// public AlphaProcessor(int percent) { Guard.MustBeBetweenOrEqualTo(percent, 0, 100, nameof(percent)); this.Value = percent; } /// /// Gets the alpha value. /// public int Value { get; } /// protected override void OnApply(ImageBase source, Rectangle sourceRectangle) { float alpha = this.Value / 100F; int startY = sourceRectangle.Y; int endY = sourceRectangle.Bottom; int startX = sourceRectangle.X; int endX = sourceRectangle.Right; // Align start/end positions. int minX = Math.Max(0, startX); int maxX = Math.Min(source.Width, endX); int minY = Math.Max(0, startY); int maxY = Math.Min(source.Height, endY); // Reset offset if necessary. if (minX > 0) { startX = 0; } if (minY > 0) { startY = 0; } Vector4 alphaVector = new Vector4(1, 1, 1, alpha); using (PixelAccessor sourcePixels = source.Lock()) { Parallel.For( minY, maxY, this.ParallelOptions, y => { int offsetY = y - startY; for (int x = minX; x < maxX; x++) { int offsetX = x - startX; TColor packed = default(TColor); packed.PackFromVector4(sourcePixels[offsetX, offsetY].ToVector4() * alphaVector); sourcePixels[offsetX, offsetY] = packed; } }); } } } }