// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Threading.Tasks;
using SixLabors.ImageSharp.Advanced;
using SixLabors.ImageSharp.Helpers;
using SixLabors.ImageSharp.Memory;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.Primitives;
namespace SixLabors.ImageSharp.Drawing.Processors
{
///
/// Combines two images together by blending the pixels.
///
/// The pixel format.
internal class DrawImageProcessor : ImageProcessor
where TPixel : struct, IPixel
{
///
/// Initializes a new instance of the class.
///
/// The image to blend with the currently processing image.
/// The location to draw the blended image.
/// The opacity of the image to blend. Between 0 and 1.
public DrawImageProcessor(Image image, Point location, GraphicsOptions options)
{
Guard.MustBeBetweenOrEqualTo(options.BlendPercentage, 0, 1, nameof(options.BlendPercentage));
this.Image = image;
this.Opacity = options.BlendPercentage;
this.Blender = PixelOperations.Instance.GetPixelBlender(options.BlenderMode);
this.Location = location;
}
///
/// Gets the image to blend
///
public Image Image { get; }
///
/// Gets the opacity of the image to blend
///
public float Opacity { get; }
///
/// Gets the pixel blender
///
public PixelBlender Blender { get; }
///
/// Gets the location to draw the blended image
///
public Point Location { get; }
///
protected override void OnApply(ImageFrame source, Rectangle sourceRectangle, Configuration configuration)
{
Image targetImage = this.Image;
PixelBlender blender = this.Blender;
int locationY = this.Location.Y;
// Align start/end positions.
Rectangle bounds = targetImage.Bounds();
int minX = Math.Max(this.Location.X, sourceRectangle.X);
int maxX = Math.Min(this.Location.X + bounds.Width, sourceRectangle.Width);
int targetX = minX - this.Location.X;
int minY = Math.Max(this.Location.Y, sourceRectangle.Y);
int maxY = Math.Min(this.Location.Y + bounds.Height, sourceRectangle.Bottom);
int width = maxX - minX;
using (var amount = new Buffer(width))
{
for (int i = 0; i < width; i++)
{
amount[i] = this.Opacity;
}
Parallel.For(
minY,
maxY,
configuration.ParallelOptions,
y =>
{
Span background = source.GetPixelRowSpan(y).Slice(minX, width);
Span foreground = targetImage.GetPixelRowSpan(y - locationY).Slice(targetX, width);
blender.Blend(background, background, foreground, amount);
});
}
}
}
}