Dynamically Resize and Reformat Images in ASP.NET Core with ImageSharp.Web using URL Parameters

Web applications often need to deliver images optimized for device resolution, bandwidth, and format. Instead of manually preprocessing and storing multiple versions of each image, you can use ImageSharp.Web (middleware from SixLabors) to dynamically resize, crop, and convert image formats on the fly by appending query parameters to the image URL. For example:

http://images/photo.jpg?width=300&height=200&format=webp

This approach gives flexibility, avoids storing redundant image files, and lets you tailor output per request. In this article, you’ll learn how to use ImageSharp.Web in ASP.NET Core, how to control its behavior, and how to cache results efficiently.

What Is ImageSharp.Web?

ImageSharp.Web is an ASP.NET Core middleware (and processing pipeline) provided by SixLabors for handling web image requests. It hooks into HTTP request processing such that when a client requests an image URL with processing commands (via query string), the middleware intercepts, processes the image (resize, format conversion, cropping, etc.), caches the result, and returns the optimized image.

Out of the box, it supports several built-in processors (resize, format, etc.), and it is configurable for cache behavior, supported providers, request parsing, and more.

Getting Started: Installation & Basic Setup

Install the NuGet package

Add the package to your project:

dotnet add package SixLabors.ImageSharp.Web

Configure services and middleware

In your Program.cs or Startup.cs, register ImageSharp and add it to the pipeline. For example, in .NET 6+ minimal hosting:

using SixLabors.ImageSharp.Web.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();
builder.Services.AddImageSharp();  // register default ImageSharp.Web services

var app = builder.Build();

app.UseImageSharp();  
app.UseStaticFiles();
app.UseRouting();
app.MapDefaultControllerRoute();

app.Run();

Important: The app.UseImageSharp() call should occur before or in the correct order relative to UseStaticFiles. If static files middleware handles the request before ImageSharp, your query-string-based processing may never be reached.

Configure options (optional but recommended)

You can customize behavior via AddImageSharp(options => { … }). Some common options:

  • BrowserMaxAge – how long browsers should cache images.
  • CacheMaxAge – how long processed images stay in server-side cache.
  • CacheHashLength – length of the hash used for caching processed filenames.
  • OnPrepareResponse / OnPrepareResponseAsync – to adjust response headers (e.g. cache-control).
  • Configure cache provider (e.g. physical file system, Azure blob, etc.)
  • Add or remove specific processors (resize, format, etc.)

Query-String Parameters: Commands You Can Use

ImageSharp.Web supports a set of commands via query string. Some of the commonly used ones:

  • width — set desired output width in pixels

  • height — set desired output height

  • format — target image format (e.g. jpg, png, webp, gif, etc.)

  • quality — compression quality (1 to 100)

  • rmode — resize mode (e.g. max, stretch, crop, pad)

  • ranchor — anchor position when cropping or padding

  • bgcolor — background color for transparent image fill

  • Other commands depending on your configured processors

For example:

http://images/banner.jpg?width=600&format=webp&quality=80

The image will be resized so its width is 600px (height scaled accordingly), then converted to WebP format with quality 80.

You can also combine width + height, and specify cropping or padding behavior via rmode. For instance:

http://images/avatar.png?width=200&height=200&rmode=crop&ranchor=center

That would crop the image to a 200×200 square centered around the image’s center.

How It Works Internally & Caching Strategy

When an image request arrives, ImageSharp.Web’s pipeline:

  1. Parses the query string to extract processing commands.

  2. Locates the source image via registered providers (e.g., physical file provider).

  3. Applies one or more processors (resize, format conversion, crop, etc.).

  4. Saves the processed image into a server-side cache (based on a hashing scheme tied to the commands).

  5. Serves the resulting image with appropriate HTTP headers (e.g., caching, content-type).

Because of the processing cost, caching is vital. Some best practices:

  • Use a persistent cache (file system, blob storage, etc.) so that each unique combination is processed only once.

  • Limit the number of allowed sizes or formats to prevent abuse (e.g. DoS by asking for many slight variants).

  • Control cache durations via CacheMaxAge and browser caching via BrowserMaxAge or OnPrepareResponse.

  • Use consistent hashing for commands so that the same combination yields the same cache key.

Example: Enable Format Conversion and Resizing

Here’s an example of how you might add only the resize and format processors (assuming default behavior includes these):

builder.Services.AddImageSharp(options =>
{
    options.BrowserMaxAge = TimeSpan.FromHours(1);
    options.CacheMaxAge = TimeSpan.FromDays(30);
    options.CacheHashLength = 8;
})
.Configure<PhysicalFileSystemCacheOptions>(options =>
{
    options.CacheFolder = "img-cache";
})
.ClearProviders()
.AddProvider<PhysicalFileSystemProvider>()
.SetCache<PhysicalFileSystemCache>()
.AddProcessor<ResizeWebProcessor>()
.AddProcessor<FormatWebProcessor>();

Potential Pitfalls and Best Practices

  • Middleware ordering matters — placing UseImageSharp after UseStaticFiles may prevent the middleware from intercepting image requests.

  • Unbounded resizing is dangerous — allowing arbitrary widths/heights may let clients trigger expensive processing tasks. Mitigate by restricting allowed sizes or falling back to nearest acceptable size.

  • Cache invalidation — if source images change, ensure that caches are invalidated or use caching strategies that respect file timestamps.

  • Browser caching & headers — carefully manage Cache-Control, ETag, and Last-Modified so browsers efficiently reuse images.

  • Supported formats & encoders — ensure your configuration supports the formats you intend to output (e.g. WebP support).

  • Memory / resource usage — on high-load servers, image manipulation may be CPU- and memory-intensive. Monitor performance and consider throttling or queuing.

Use Cases & Benefits

  • Serve appropriately sized images for responsive layouts (mobile, tablet, desktop) without manual preprocessing.

  • Convert all client requests to modern formats (e.g. WebP) when supported.

  • Reduce bandwidth by sending optimized images per request.

  • Simplify content workflows (you only store a master/original image and generate variants on demand).

Conclusion

Using ImageSharp.Web in ASP.NET Core, adding query parameters like ?width=200&format=png lets you dynamically resize and reformat images in a flexible, maintainable way. The key is combining correct middleware setup, processor configuration, caching, and safe bounds on what is allowed. With the right setup, you can deliver image assets optimized per request with minimal overhead.

Comments Add
No comments yet.