1

我在我的 Asp.net Core 项目中使用 SixLabors 的 ImageSharp 和 ImageSharp.Web。图像大小调整适用于存储在磁盘上的图像的查询字符串。例子:

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

但是,如果图像是从流中提供的,ImageSharp 似乎不会调整图像大小。这是一个示例中间件,如果它符合某些条件,我将使用它从安全文件夹中传递图像:

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);
    }
}

我在 Startup.cs 中的中间件之前注册了 ImageSharp,以便它有机会拦截响应:

启动.cs

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

当路径不在磁盘上时,如何让 ImageSharp 根据查询字符串参数调整图像大小?

4

1 回答 1

2

ImageSharp 中间件仅拦截具有识别命令的图像请求。

由于您在启动中的 ImageSharp 中间件之后注册了您的中间件,因此 ImageSharp 中间件在您拦截请求之前已经处理了请求。

有两种方法可以满足您的要求:

  1. 首先注册您的中间件,使其在 ImageSharp 中间件之前运行并拒绝无效查询。
  2. 创建您自己的自定义IImageProvider来处理图像的分辨率以限制您的标准。
于 2019-07-18T00:43:43.680 回答