【问题标题】:ImageSharp - resize image from streamImageSharp - 从流中调整图像大小
【发布时间】:2019-07-16 20:08:09
【问题描述】:

我在我的 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,以便它有机会拦截响应:

Startup.cs

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

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

【问题讨论】:

    标签: .net asp.net-core imagesharp


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      • 2012-02-24
      • 2023-03-28
      • 1970-01-01
      相关资源
      最近更新 更多