How To Crop Image In ASP.NET Core

Introduction

This article demonstrates using image cropper in an ASP.NET Core project. In this article, I will be using ImageSharp.Web component by Six Labors. This article covers package installation, middleware setup, and different features of the components with examples. I found this component very handy for resizing images dynamically in our applications. Users might upload huge images, still, we have to keep our application performance up to the mark. Solving this problem ImageSharp.Web is very useful.

Pre-requisites

All the demonstration and code example used in this article is based on Visual Studio 2022 and .NET 7.0. So, I assume you are familiar with using Microsoft Visual Studio along with C#.

What is ImageSharp.Web?

ImageSharp.Web is a middleware that allows the processing and caching of image requests. This high-performance component is built on top of ImageSharp. ImageSharp.Web is licensed under the terms of Apache License, Version 2.0, and if you are using this component in software that has more than 1M USD annual gross revenue, Six Labors recommend purchasing a commercial license.

Package Installation

You can install ImageSharp.Web via NuGet. To install the package, follow the steps below

  1. Right click on your project
  2. Select Manage NuGet Packages…
  3. In NuGet Package Manager window, select Browse
  4. Search for ImageSharp.Web from searchbox
  5. Select SixLabors.ImageSharp.Web from the package list
  6. Select the version from the dropdown (Latest stable recommended) and select Install.
    Crop Image In ASP.NET Core
  7. Select I Accept to confirm you agree to the license terms

You can install the package from NuGet Package Manager Console also. For that you go to Tools menu > NuGet Package Manager > Package Manager Console

In the Package Manager Console window use below command to install package. In the command you have to replace VERSION_NUMBER by the version number you want to install.

PM > Install-Package SixLabors.ImageSharp.Web -Version VERSION_NUMBER

Adding ImageSharp.Web Middleware

Once you have installed the package, now you have to configure middleware. Open Program.cs in your project.

This code adds default services and options.

builder.Services.AddImageSharp();

And this is the code that adds image processing middleware

app.UseImageSharp();

The below code shows how the basic setup should be.

using SixLabors.ImageSharp.Web.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddImageSharp();
var app = builder.Build();
app.UseImageSharp();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment()) {
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

Now, let's see the result of the above basic middleware setup. This screenshot shows that image1.jpg is 2.3MB in size and took 33ms to load.

Crop Image In ASP.NET Core

And this is the screenshot with the image height cropped to 400px using ImageSharp.Web. In this screenshot, the image size is reduced to 34kB and took 2ms to load. For the first time, you might face a more loading time because of some time-consuming processing to a new size and saving it to the cache folder. The cache folder is created in wwwroot folder. By default, all the cropped images are saved into a cache folder auto-created by the component. The cache folder can also be changed to another folder, which we will look into custom options.

Now, let's look at more custom options. In this code, you can see that more options are added to customize. BrowserMaxAge, and CacheMaxAge has been changed to lower values. You can also see the cache folder changed into imagecache folder.

builder.Services.AddImageSharp(options => {
    options.Configuration = Configuration.Default;
    options.BrowserMaxAge = TimeSpan.FromHours(12);
    options.CacheMaxAge = TimeSpan.FromDays(30);
    options.CacheHashLength = 8;
}).Configure < PhysicalFileSystemCacheOptions > (options => {
    options.CacheFolder = "imagecache";
});

You can read more about custom options here.

Processing Commands

You can use processing commands to process the images into a different sizes and format. The processing commands are extracted from the query string from the web browser. There is a standard list of commands that you have to provide to process the images. To change the image's width, you have to use the command <your-url>/<image-path>?width=400.

Resize

Resize commands are responsible for maintaining the output image's new width, height, and aspect ratio. Some commands that are widely used are listed below

width

The width of the output image in px. <URL>/<image-path>?width=70

height

The width of the output image in px. <URL>/<image-path>?height=70 or <URL>/<image-path>?height=70&width=70. Ordering of the commands can be anywhere. Middleware will handle it automatically.

rmode

This option defines how the image should be resized. The below table shows all the available rmode options.

ranchor

This option defines the anchor position of the resized images to apply. The below table shows all the available ranchor options.

This example shows image width and height are changed to 400px, and ranchor is bottom. So, the output image will be cropped into 400x400px from the bottom.

Crop Image In ASP.NET Core

Format

Format command is used to encode the output image into a new format. If you have a jpg or png image and you want to convert it into webp, then you can do like below,

<URL>/<image-path>?format=webp

Crop Image In ASP.NET Core

You can use BMP, gif, jpg, png, tga, tiff, and webp as the default format. The available format depends on your configuration in middleware.

Quality

The quality of the output image will encode into the given quality. Its range is from 1 to 100.

<URL>/<image-path>?quality=70

Background Color

bgcolor is the command to change the background color of any transparent images.

<URL>/<image-path>?bgcolor=green

More information about ImageSharp.Web can be found here.

Summary

In this article, I discussed how to use ImageSharp.Web in ASP.NET Core project. I demonstrated the package installation and middleware configuration. After that, I explained the processing commands that are available in ImageSharp.Web.

I hope you will find this article helpful. Please feel free to ask in the comment section if you have any suggestions.

Thank you for reading the article.