我在我的 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 根据查询字符串参数调整图像大小?