1

I'm using SixLabors' ImageSharp with ImageSharp.Web in my Asp.net Core project. Image resizing works well with query strings for images that are stored on disk. Example:

/myimage.jpg?width=10&height=10&rmode=max

However, ImageSharp doesn't seem to resize images if the image is served from stream. Here's an example Middleware that I'm using to deliver an image from a secure folder if it meets certain criteria:

public class ExposeSecureImageMiddleware
{
    public ExposeSecureImageMiddleware(RequestDelegate next, IFolders folders)
    {
        Next = next;
        Folders = folders;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        if (meets_my_criteria)
            await SendFile(httpContext);
        else
            await Next(httpContext);
    }

    async Task SendFile(HttpContext httpContext)
    {
        var fs = File.OpenRead("c:/path/to/secure/file.jpg");

        var bytes = new byte[fs.Length];
        await fs.ReadAsync(bytes, 0, bytes.Length);

        httpContext.Response.Headers.ContentLength = bytes.Length;
        httpContext.Response.ContentType = "image/jpeg";
        await httpContext.Response.Body.WriteAsync(bytes, 0, bytes.Length);
    }
}

I registered ImageSharp before my middleware in Startup.cs so that it has a chance intercept the response:

Startup.cs

    app.UseImageSharp();
    app.UseMiddleware<ExposeSecureImageMiddleware>();

How can I get ImageSharp to resize images based on query string parameters when the path isn't on disk?

Johnny Oshika
  • 54,741
  • 40
  • 181
  • 275

1 Answers1

2

The ImageSharp Middleware only intercepts image requests with recognized commands.

Since you've registered your Middleware after the ImageSharp Middleware in Startup, the ImageSharp Middleware has already processed the request before yours intercepts the request.

There are two ways to do what you require:

  1. Register your Middleware first so that it runs before the ImageSharp Middleware and rejects invalid queries.
  2. Create your own custom IImageProvider that handles the resolution of images to limit to your criteria.
James South
  • 10,147
  • 4
  • 59
  • 115