Theme:

Image Processing Alternatives In Umbraco

Tagged with:
Media
ImageSharp is how Umbraco resizes images, but it doesn’t have to be. Umbraco’s media URLs are just a contract: a path and some query params. Honor it, and any image library can sit behind it, even in a separate deployment. That leaves you free to pick the right tool, whether for scaling, features or a license that fits your project better.

Prelude

The rest of this post references a sample project I built while exploring this topic. If you want to follow along in the code, you can find it in the sample project.

Under the hood, ImageSharp does three things for Umbraco:

  1. Decode a source image
  2. Apply a command (resize, crop, re-encode)
  3. Write the result

Pretty much every image library can do that. ImageSharp just happens to be the one Umbraco ships with. So let’s say you’ve got a good reason to swap it out. What would that take?

The goal is a true drop-in replacement: no view changes, and the same query-string contract Umbraco already exposes, including its custom crop command.

The contenders

The repository supports two libraries, and the test project can switch between the two using environment variables.

At the time of writing, SkiaSharp ships under the MIT license, which makes it a great place to start.

ImageFlow is another popular option, and it performs well, but its license is more restrictive. Depending on your situation, you may need to pay for it. More on that later.

Or plug in any other library by implementing IImageProcessor.

Interestingly and maybe surprisingly, we also unlock the option to host the image processing service separately. The next sections will touch on the general in-process setup, a standalone image processing service and reflect on whether any of this is even a better solution.

Intercepting media requests

Umbraco already has a pipeline for generating media URLs, and we don't need to replace any of it as long as we honor the existing contracts.

Let's write middleware that catches incoming media requests and uses a strategy pattern to apply transforms from whichever image-processing provider is registered:


public async Task InvokeAsync(HttpContext context)
{
    ImageSourceMatchResult result = _sourceMatcher.Match(context.Request.Path);
    if (result.Outcome == ImageSourceMatchOutcome.NoMatch)
    {
        await _next(context);
        return;
    }

    if (result.Outcome == ImageSourceMatchOutcome.Rejected)
    {
        Refuse(context, result);
        return;
    }

    ImageSourceMatch match = result.Match!;
    ParsedImageCommand parsed = ImageCommandParser.Parse(context.Request.Query, _options);

    // A plain request with no commands has nothing to tamper with, so it skips signing.
    if (parsed.HasProcessingCommands &&
        !_hmacSigner.Validate(context.Request.Path, context.Request.Query, context.Request.Query[ImageProcessingCommandNames.HmacToken]))
    {
        context.Response.StatusCode = StatusCodes.Status400BadRequest;
        return;
    }

    Stream? source = await _originalImageSources[match.RoutePrefix].OpenReadAsync(match.RelativePath, context.RequestAborted);
    if (source is null)
    {
        await _next(context);
        return;
    }

    await using (source)
    {
        if (!parsed.HasProcessingCommands)
        {
            await WriteResponseAsync(context, source, ContentTypeFor(Path.GetExtension(match.RelativePath).TrimStart('.')));
            return;
        }

        if (!ImageHeaderReader.TryRead(source, out ImageHeaderInfo header))
        {
            context.Response.StatusCode = StatusCodes.Status422UnprocessableEntity;
            return;
        }

        source.Position = 0;
        ResolvedImageCommand resolved = ImageCommandResolver.Resolve(parsed, _options, header);

        string cacheKey = $"{match.RoutePrefix}{match.RelativePath}?{context.Request.QueryString}";
        Stream? cached = await _derivativeImageCache.TryOpenReadAsync(cacheKey, context.RequestAborted);
        if (cached is not null)
        {
            await using (cached)
            {
                await WriteResponseAsync(context, cached, ContentTypeFor(resolved.Format));
            }

            return;
        }

        using var destination = new MemoryStream();
        await _processor.ProcessAsync(source, destination, resolved, context.RequestAborted);

        destination.Position = 0;
        await _derivativeImageCache.WriteAsync(cacheKey, destination, context.RequestAborted);

        destination.Position = 0;
        await WriteResponseAsync(context, destination, ContentTypeFor(resolved.Format));
    }
}

Note

IsImageRequest and WriteResponseAsync are small helpers, omitted here for length.

 

There are a few gaps in that snippet worth filling in. Let's start at the top and work through it.

Image command parser and resolver

The parser's job is to turn the query string into a standardized model, defaults and fallbacks included.

The resolver takes that model and computes everything downstream code needs, like the crop rectangle derived from the coordinates in the query string. That keeps the processors themselves slim and consistent, and gives us one place to put command-specific logic as it grows.

HMAC signer

Modern Umbraco can sign image URLs. That helps block malicious resize requests, which can otherwise be expensive to process, so it's worth supporting.

Since Umbraco renders the URLs and our pipeline serves them, both sides share a secret: we sign when generating the URL and validate when the request comes in. The catch: Umbraco's own HMAC implementation lives inside SixLabors.ImageSharp.Web, not something we can reference without pulling ImageSharp back in. So we need our own HmacSigner:


public sealed class HmacSigner(IOptions<ImageProcessingOptions> options) : IHmacSigner
{
    private readonly ImageProcessingOptions _options = options.Value;

    public bool IsEnabled => _options.HmacSecretKey is { Length: > 0 };

    public string? ComputeToken(PathString path, IQueryCollection query)
    {
        if (!IsEnabled)
        {
            return null;
        }

        string canonical = BuildCanonicalString(path, query);
        byte[] hash = HMACSHA256.HashData(_options.HmacSecretKey!, Encoding.UTF8.GetBytes(canonical));
        return Convert.ToHexStringLower(hash);
    }

    public bool Validate(PathString path, IQueryCollection query, string? token)
    {
        if (!IsEnabled)
        {
            return true;
        }

        if (string.IsNullOrEmpty(token))
        {
            return false;
        }

        string? expected = ComputeToken(path, query);
        if (expected is null)
        {
            return false;
        }

        return CryptographicOperations.FixedTimeEquals(
            Encoding.ASCII.GetBytes(expected),
            Encoding.ASCII.GetBytes(token.ToLowerInvariant()));
    }

    private static string BuildCanonicalString(PathString path, IQueryCollection query)
    {
        IEnumerable<string> pairs = query
            .Where(kvp => !string.Equals(kvp.Key, ImageProcessingCommandNames.HmacToken, StringComparison.OrdinalIgnoreCase))
            .OrderBy(kvp => kvp.Key, StringComparer.Ordinal)
            .Select(kvp => $"{kvp.Key}={kvp.Value}");

        return $"{path}?{string.Join('&', pairs)}";
    }
}

We also need to override Umbraco's IImageUrlGenerator so it signs URLs with this instead of ImageSharp's version:


public string? GetImageUrl(ImageUrlGenerationOptions? options)
{
    if (options?.ImageUrl is null)
    {
        return null;
    }

    var query = new SortedDictionary<string, string?>(StringComparer.Ordinal);

    if (options.Crop is { } crop)
    {
        query[ImageProcessingCommandNames.Crop] = FormattableString.Invariant($"{crop.Left},{crop.Top},{crop.Right},{crop.Bottom}");
    }

    if (options.Width is { } width)
    {
        query[ImageProcessingCommandNames.Width] = width.ToString(CultureInfo.InvariantCulture);
    }

    // ...height, format, quality, further options and cache buster, same pattern

    string url = QueryHelpers.AddQueryString(options.ImageUrl, query);

    if (_hmacSigner.IsEnabled)
    {
        var path = new PathString(GetPathOnly(options.ImageUrl));
        var queryCollection = new QueryCollection(query.ToDictionary(kvp => kvp.Key, kvp => new StringValues(kvp.Value!)));

        string? token = _hmacSigner.ComputeToken(path, queryCollection);
        if (!string.IsNullOrEmpty(token))
        {
            url = QueryHelpers.AddQueryString(url, ImageProcessingCommandNames.HmacToken, token);
        }
    }

    // Standalone mode: point the URL straight at the image service.
    if (!string.IsNullOrEmpty(_options.ExternalBaseUrl) && IsServedBySource(options.ImageUrl))
    {
        url = _options.ExternalBaseUrl.TrimEnd('/') + url;
    }

    return url;
}

Image source and cache

After validating the HMAC, the middleware fetches the image through IOriginalImageSource. I won't go into depth here, but this interface handles reading the original image file from wherever it lives. The repository has examples for both the local file system and Azure Blob Storage. The derivative cache follows the same pattern.

Processors

Now for the main course: IImageProcessor.ProcessAsync handles the library-specific work.

Here's the SkiaSharp implementation:


public Task ProcessAsync(Stream source, Stream destination, ResolvedImageCommand command, CancellationToken cancellationToken = default)
{
    using SKBitmap decoded = SKBitmap.Decode(source) ??
        throw new InvalidOperationException("SkiaSharp could not decode the original image.");

    SKBitmap current = decoded;
    var owned = new List<SKBitmap>();
    try
    {
        if (command.Crop is { } crop)
        {
            current = Crop(current, crop);
            owned.Add(current);
        }

        if (command.ExifOrientation is not (ExifOrientation.TopLeft or ExifOrientation.Unknown))
        {
            current = ApplyOrientation(current, command.ExifOrientation);
            owned.Add(current);
        }

        int resizeWidth = command.Placement?.Width ?? command.Width;
        int resizeHeight = command.Placement?.Height ?? command.Height;
        if (resizeWidth != current.Width || resizeHeight != current.Height)
        {
            current = Resize(current, resizeWidth, resizeHeight);
            owned.Add(current);
        }

        // ...padding and background colour, same pattern

        Encode(current, command.Format, command.Quality, destination);
    }
    finally
    {
        foreach (SKBitmap bitmap in owned)
        {
            bitmap.Dispose();
        }
    }

    return Task.CompletedTask;
}

Note

Crop, ApplyOrientation, Resize and Encode are thin wrappers around SkiaSharp calls. The full version is in the repo.

Wiring it up

With the pieces in place, we register them in Program.cs. AddImageProcessing() registers everything that works the same whichever library you use: options, the HMAC signer, image source and cache. The processor is a single call chained after it. AddUmbracoImageProcessing() then swaps in our URL generator, so Umbraco renders signed URLs that our middleware accepts.


builder.CreateUmbracoBuilder()
    .AddBackOffice()
    .AddWebsite()
    .AddComposers()
    .Build();

builder.Services
    .AddImageProcessing(options => builder.Configuration.GetSection("ImageProcessing").Bind(options))
    .UseSkiaSharp() // or .UseImageFlow()
    .AddUmbracoImageProcessing();

WebApplication app = builder.Build();

// Before Umbraco's pipeline, so media requests never reach its static file handling.
app.UseImageProcessing();

await app.BootUmbracoAsync();
// ...the usual app.UseUmbraco() setup

Switching libraries means changing that one .UseSkiaSharp() line and the package reference. Nothing else changes.

Note

Umbraco’s own imaging package registers its IImageUrlGenerator with a plain Add, and .NET’s dependency injection uses whichever registration comes last. So AddUmbracoImageProcessing() uses Services.Replace(...) rather than TryAdd. That way our generator wins whether it’s registered before or after Umbraco’s.

And that's it. Your images are now scaled through SkiaSharp instead of ImageSharp.

But we can go further.

Standalone service

This same seam makes it straightforward to host image processing as its own service, separate from Umbraco. That's useful when you want to scale image operations independently of the CMS. Resizing is CPU-bound, and a burst of image requests competes for the same threads as your page rendering if they're both in one process. Separate the two and you can scale the image service on its own, without touching the CMS. It's also useful for licensing. Some libraries require a paid license unless your own application adopts a matching license, and AGPL is the classic copyleft example.

The middleware itself doesn’t change between the two modes. Both read the same list of image sources: a route prefix like /media, plus where the original files live. That way the service answers exactly the paths Umbraco would have.

The standalone service is a plain ASP.NET Core app with no Umbraco reference at all. It’s little more than a Program.cs, an appsettings.json and a couple of package references:


WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddImageProcessing(options => builder.Configuration.GetSection("ImageProcessing").Bind(options))
    .UseSkiaSharp()
    .UseAzureBlobOriginalImageSource("/media", options =>
        builder.Configuration.GetSection("ImageProcessing:Sources:0:Storage:AzureBlob").Bind(options));

WebApplication app = builder.Build();

app.UseImageProcessing();

await app.RunAsync();

The service needs a way to reach the original images. That’s easiest if Umbraco already stores its media in Blob Storage: point both at the same container and you’re done. The repo also covers a shared disk, and an HTTP mode where the service fetches originals from Umbraco itself.

On the Umbraco side, drop the processor and the middleware, and tell the URL generator where the service lives:


{
  "ImageProcessing": {
    "ExternalBaseUrl": "https://images.example.com"
  }
}

Now IImageUrlGenerator renders absolute URLs that point straight at the service, so freshly rendered pages never touch the CMS for images. The HMAC signature covers the path, not the host, so signed URLs still validate on the other side.

But some URLs still won’t go through the generator, like images embedded in rich text or a hard-coded /media/... link. For those, a tiny middleware in Umbraco redirects anything under a configured source to the service:


app.Use(async (context, next) =>
{
    if (sourceMatcher.Match(context.Request.Path).Outcome == ImageSourceMatchOutcome.NoMatch)
    {
        await next();
        return;
    }

    context.Response.Redirect($"{serviceBaseUrl}{context.Request.Path}{context.Request.QueryString}");
});

Tip

Set the HMAC key in both Umbraco and the standalone image service. Umbraco signs the URLs and the service checks the signature, so if the two disagree on the key, you get a wall of 400s and a lot of silent staring at your screen. Don’t ask me how I know.

Tradeoffs

None of this is free, figuratively anyway. Six Labors has spent years tuning ImageSharp's web middleware and the underlying methods. Reimplementing that in SkiaSharpImageProcessor, and again in a separate ImageFlow processor, means rediscovering issues Six Labors already found and fixed years ago.
The crop math, the orientation matrix, the aspect-ratio fallback when only width or only height is set. All of that has to mature over time, while ImageSharp has a long history with Umbraco and is well tested over many years.

You might find that ImageSharp's tried and tested solution is a better fit for you. After all, they are veterans of image processing.

However, separating our deployments and repositories also makes it easy to open-source just a small part of our application. The image service, for example, could be fully open source. That makes copyleft-licensed libraries like ImageFlow (AGPL at the time of writing) a viable option, and the community gets a reference implementation as a bonus. Just remember to give back if you end up loving a specific library.

Bonus: Hey, I already have an ImageSharp license!

If you already hold a Six Labors commercial license, or you qualify for the Apache 2.0 terms of the Six Labors Split License, you don't need any of the pipeline above to get this same standalone deployment shape. SixLabors.ImageSharp.Web ships its own ASP.NET Core middleware: AddImageSharp() in Program.cs, UseImageSharp() in the pipeline, and you get decode, resize, crop, encode, caching, and HMAC signing out of the box. Add SixLabors.ImageSharp.Web.Providers.Azure and Blob Storage support for both source images and the derivative cache is a package reference and a config block away. No IOriginalImageSource, no IDerivativeImageCache, no custom HmacSigner, none of it. Simple.

But really this is a great option if you like ImageSharp. Just remember to re-implement Umbraco's custom crop command in the standalone app too!

If this has piqued your interest, both the in-process and standalone setups are ready for you to try out with just a few package references. Check out the setup guides in the repository.


Skrift Gold: Confidence With Umbraco Media

Check it out here