Image Mutation Pipeline - Reshaping and Overlay Images
In this post, we’ll go over image manipulation via creating a pipeline, the goal of this post will be to create avatar, consisting of a user/character, then surrounding this picture with a frame as an overlay.
Rather than using
System.Drawing we’ll instead using ImageSharp which is the most popular image processing library written using .NET Core, it’s very fast and highly optimized, despite being in beta I have used in production for a year without problems.
Using this library, we’ll create our own pipeline of image operations to perform using
IImageProcessingContext, and take advantage of some of heavy lifting ImageSharp provides.
For assets, we’ll be using two images, a base picture and an overlay to surround:
Base picture (me.png)
- Create a .NET Core Console App
- Add the following Package Reference to your .csproj file
<PackageReference Include="SixLabors.ImageSharp.Drawing" Version="1.0.0-beta0007" />If you install through nuget, ensure that
.Drawingis included, else you won’t be able to access the
- Add the assets to your project, make sure you select
Copy if newerin the Properties panel > Copy to Output Directory
The first part of this process is to alter the shape of our user image to something the resembles a diamond.
Below is the code for this, with heavy use of comments elaborating on the process since this is much easier than blog annotations:
The above code results in the following image:
We can achieve our approximate diamond shape via increasing the
cornerRadius float value, however this will result in less of the canvas showing, below is 200:
Side note, if you wanted a circle, all that would be required is to set the
cornerRadius to 50% of the image size.
Currently we’re filling in the areas we’ve clipped with a solid green. Great for testing, but not for our desired result. You will want to comment out the following line which will automatically remove our colour fill.
AlphaCompositionMode = PixelAlphaCompositionMode.DestOut
Next, we’ll add our overlay, this is simpler than the previous code. We’ll embed another
using statement since we still want the original outputs, this makes viewing each stage of the process and making changes much easier whilst we build the pipeline.
Add the following within the
destRound using, after
using (var overlay = Image.Load("frame.png"))
GenerateOverlay is part our pipeline for this project, add the following:
private static IImageProcessingContext GenerateOverlay(this IImageProcessingContext processingContext, Image me)
The above method will draw the image together with the previous image, once that has completed this will be saved to the disk.
The Final Result
It should be noted that the code above is simply a proof in concept, for instance the
Clone methods add overhead and shouldn’t appear in production code.