For an application we are building, we had to image processing features to an existing API. Our first idea was to build our own solution but then we discovered ImageSharp.Web. ImageSharp.Web builts on top of the great ImageSharp library and adds middleware to manipulate images. Exactly what we needed!
The documentation is quite limited so let me help you out and walk you through the steps(and share a few gotcha’s along the way) to get it up and running in your ASP.NET Core application.
Installation
First you need to install the library through NuGet:
dotnet add package SixLabors.ImageSharp.Web
Now you need to register the middleware:
And add it to the ASP.NET Core pipeline:
Invoke the middleware
To invoke the middleware, you should browse to the application and add the commands you want to execute. For example, to resize an image, you should call:
http://localhost/imageprocessingexample/exampleimage.png?width=400
Sounds easy? Unfortunately there are a few gotcha’s I encountered.
Static Files middleware
The code I’ve shared so far can also be found in the ImageSharp.Web documentation. But when you try to run the application and call the configured middleware it will fail. This is because some extra work needs to be done depending on the source of your images. Therefore the ImageSharp.Web library uses the concept of ‘Image providers’. An image provider is a specific source where the middleware will try to load the image from. The default middleware will look for the image as static content in the ‘wwwroot’ folder of your ASP.NET core application.
To make this image provider work it is necessary to have the static file middleware added to your request pipeline and of course a ‘wwwroot’ folder with the image you want to manipulate.
So we have to update our code example above to the following:
It is important to notice here that we should add the StaticFiles middleware AFTER the ImageSharp middleware.
ImageSharp 1 vs ImageSharp 2
When I now tried to run the application again, I encountered a second issue. The ImageSharp middleware was invoked correctly but throwed the following exception:
An unhandled exception occurred while processing the request.
MissingMethodException: Method not found: 'System.Threading.Tasks.Task`1<SixLabors.ImageSharp.Formats.IImageFormat> SixLabors.ImageSharp.Image.DetectFormatAsync(SixLabors.ImageSharp.Configuration, System.IO.Stream)'
The root cause of this issue became obvious when I took a look at my dependencies:
I’m using a 1.x version of ImageSharp.Web and a 2.x version of ImageSharp. ImageSharp.Web is only compatible with the 1.x version of ImageSharp. I fixed it by explicitly specifying the correct version in my project: