Search code examples
c#.net-4.8imagesharp

Copying an Image to the new instance in SixLabors.ImageSharp


The task is simple, however I can't figure it out. I have following function:

/// <summary>
/// Highlights areas on the image
/// </summary>
/// <param name="initialImage">Initial image to highlight on</param>
/// <param name="rectanglesToHighlight">Areas to highlight</param>
/// <returns></returns>
public static Image Highlight(Image initialImage, params RectangleF[] rectanglesToHighlight)
{
      // Initial image
      Image result = initialImage.Clone(x => x.Opacity(1f));
      // Color of the mask
      Color maskColor = Color.Red;
      // Mask for each rectangle to highlight
      Image mask = new Image<Rgba32>(initialImage.Width, initialImage.Height, maskColor);
      // Recolor brush to draw transparent rectangles
      RecolorBrush brush = new RecolorBrush(maskColor, Color.Transparent, 1f);

      // Draw each rectangle on mask
      foreach(RectangleF rect in rectanglesToHighlight)
            // Draw current rectangle on mask with transparent color
            mask.Mutate(x => x.Clear(brush, rect));

      // Apply mask to the initial image
      result.Mutate(x => x.DrawImage(mask, PixelColorBlendingMode.Normal, 0.5f));

      // Return result image
      return result;
}

If I'm creating new variable like this:

Image result = initialImage;

Applying mask to result changes both initialImage and result.

I need to have variable with initial image in it, so the best way I found was to clone it with unnecessary function (in first line of code in the function).

My question is: How can I copy initial image into new instance without running unnecessary function? And I also wonder why initialImage changes at all.


Solution

  • Image.ColoneAs<TPixel>

    Documentation