1

ImageSharp 如何处理从数据库加载的动态图像?这是我的控制器获取图像文件:

public async Task<FileResult> GetPhoto([FromQuery] GetFileAttachementInputAsync input)
    {
        var file = await filesAttachementAppService
            .GetFileAsync(new GetFileAttachementInputAsync() { FileId = input.FileId })
            .ConfigureAwait(false);
        return file != null 
            ? File(new MemoryStream(file.FileDto.FileContent), file.FileDto.ContentType, file.FileDto.FileName) 
            : null;
    }

这是我的 Html 调用:

<img src="/PropertyAdministration/GetPhoto?FileId=@item.MainPhotoId&width=554&height=360" alt="" />

我正在使用 ImageSharp 如下:

 public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddImageSharp();
    }
public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
    {            
        app.UseImageSharp();
    }

我在这里缺少什么来使它起作用?

4

1 回答 1

1

您没有使用中间件,也没有使用为中间件提供图像的服务。

为了使中间件工作,它需要能够捕获图像请求。在默认安装中,这是通过将请求与 wwwroot 中物理文件系统中的图像源进行匹配来完成的。

在您的代码中,尽管您创建了一个隔离的操作结果,但它返回了一个包含中间件不知道的图像的流。

免责声明,以下内容基于最新的开发人员版本1.0.0-dev000131,虽然不太可能发生变化,但在最终发布之前可能会发生变化。

https://www.myget.org/feed/sixlabors/package/nuget/SixLabors.ImageSharp.Web/1.0.0-dev000131

为了提供来自自定义源的图像,您需要创建自己的实现,IImageProvider并且IImageResolver您可以使用源中的示例作为实现的基础。

一旦实现,您将需要通过依赖注入注册实现。这需要使用更细粒度的注册,因为您不再使用默认值。

// Fine-grain control adding the default options and configure all other services. Setting all services is required.
services.AddImageSharpCore()
        .SetRequestParser<QueryCollectionRequestParser>()
        .SetBufferManager<PooledBufferManager>()
        .SetMemoryAllocatorFromMiddlewareOptions()
        .SetCacheHash<CacheHash>()
        .AddProvider<PhysicalFileSystemProvider>()
        /// Add your provider here via AddProvider<T>().
        .AddProvider<PhysicalFileSystemProvider>()
        .AddProcessor<ResizeWebProcessor>()
        .AddProcessor<FormatWebProcessor>()
        .AddProcessor<BackgroundColorWebProcessor>();

然后,您应该能够完全删除您的操作结果并使用IImageProviderandIImageResolver组合来识别请求并返回图像。

于 2018-10-08T14:23:12.467 回答