【问题标题】:How ImageSharp work with Asp.Net Mvc ControllerImageSharp 如何与 Asp.Net Mvc 控制器配合使用
【发布时间】:2018-10-08 09:58:57
【问题描述】:

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

我在这里缺少什么来使其正常工作?

【问题讨论】:

    标签: .net-core imagesharp


    【解决方案1】:

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

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

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

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

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

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

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

    // 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>();
    

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 2023-04-05
    • 2011-11-14
    • 2023-04-06
    相关资源
    最近更新 更多