Title image of Properly size images in Asp.Net with middleware

Properly size images in Asp.Net with middleware

8 July 2023

·
C#
AspNet

A common improvement that PageSpeed Insights suggests is to “properly size images”. This gets raised when the test detects the browser rendering images smaller than the original image downloaded from your server. Forcing users to download images that are larger than they need to be wastes their time and bandwidth. Making the images smaller in the first place means less data to download and faster websites.

So does this mean a server needs to keep multiple versions of every image on the website? thankfully no. There’s some fancy Asp.Net core middleware to make it a lot easier than that.

ImageSharp middleware

ImageSharp is a library I’ve blogged about before when Converting images to webp. It can do many image processing tasks in C#. A hidden gem of the library is the middleware package, ImageSharp.Web. This is what we’re going to use to resize our images on the fly.

Width and height need to be included whenever an image is requested so it can be resized. The best way to do this is to include them as URL parameters like this:

https://localhost:44384/images/cheese.jpg?width=300&height=200

Now images in the app can be the appropriate size for the location and the user doesn’t download any unnecessary data.

Setting up the middleware

Add the Nuget package:

Install-Package SixLabors.ImageSharp.Web

Setup the dependency injection by adding AddImageSharp and UseImageSharp:

using SixLabors.ImageSharp.Web.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

builder.Services.AddImageSharp(options =>
{
    options.CacheMaxAge = TimeSpan.FromDays(365);
    options.CacheHashLength = 12;
});

var app = builder.Build();

app.UseHttpsRedirection();

// Must be before UseStaticFiles()
app.UseImageSharp();

app.UseStaticFiles();

The middleware automatically resizes images that are requested with width and height URL parameters. So that’s all the configuration we need to do.

Resizing images

Width and height of an image need to be included in the URL to resize it. Imagesharp has a tag helper to do this and keep our code tidy and maintainable.

Include the tag helper import in the _viewImports.cshtml:

@addTagHelper *, SixLabors.ImageSharp.Web

And add imagesharp-width and imagesharp-height attributes to any img element:

<div>
    <h1>Original cheese</h1>    
    <img src="/images/cheese.jpg"/>

    <h1>Resized cheese</h1>
    <img src="/images/cheese.jpg" imagesharp-width="300" imagesharp-height="200" />
</div>

Resized cheese

Resized image after being processed by the asp-net core middleware

The cheese image in the asp.net core app has been automatically resized by the middleware. And because the asp net has built-in caching it’s also super fast. That’s another Page Insights suggestion done. 🙂