首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么在ImageSharp中不支持同步读取?

为什么在ImageSharp中不支持同步读取?
EN

Stack Overflow用户
提问于 2021-09-04 15:24:38
回答 3查看 1.7K关注 0票数 2

我正在尝试使用Blazor输入文件和Imagesharp库将IBrowserFile转换为图像。

我的方法是这样的

代码语言:javascript
运行
复制
public async Task<byte[]> ConvertFileToByteArrayAsync(IBrowserFile file)
        {

            using var image = Image.Load(file.OpenReadStream());
            image.Mutate(x => x.Resize(new ResizeOptions
            {
                Mode = ResizeMode.Min,
                Size = new Size(128)
            }));

            MemoryStream memoryStream = new MemoryStream();
            if (file.ContentType == "image/png")
            {

                await image.SaveAsPngAsync(memoryStream);
            }
            else
            {
                await image.SaveAsJpegAsync(memoryStream);
            }
            var byteFile = memoryStream.ToArray();
            memoryStream.Close();
            memoryStream.Dispose();


            return byteFile;
            
        } 

但我得到了以下错误:

代码语言:javascript
运行
复制
crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: Synchronous reads are not supported.
System.NotSupportedException: Synchronous reads are not supported.
   at Microsoft.AspNetCore.Components.Forms.BrowserFileStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.Stream.CopyTo(Stream destination, Int32 bufferSize)
   at SixLabors.ImageSharp.Image.WithSeekableStream[ValueTuple`2](Configuration configuration, Stream stream, Func`2 action)
   at SixLabors.ImageSharp.Image.Load(Configuration configuration, Stream stream, IImageFormat& format)
   at SixLabors.ImageSharp.Image.Load(Configuration configuration, Stream stream)
   at SixLabors.ImageSharp.Image.Load(Stream stream)
   at MasterMealWA.Client.Services.FileService.ConvertFileToByteArrayAsync(IBrowserFile file) in F:\CoderFoundry\Code\MasterMealWA\MasterMealWA\Client\Services\FileService.cs:line 37
   at MasterMealWA.Client.Pages.RecipePages.RecipeCreate.CreateRecipeAsync() in F:\CoderFoundry\Code\MasterMealWA\MasterMealWA\Client\Pages\RecipePages\RecipeCreate.razor:line 128
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.Forms.EditForm.HandleSubmitAsync()
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)

为了记录在案,第37行是“使用var映像.”,我不太清楚我在哪里使用多个流,除非它是读取流和内存流。但是,我也不知道如何关闭使用file.OpenReadStream打开的流。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-09-04 17:07:28

背景:

  • ASP.NET Core 3+通过让ASP.NET Core处理的Stream对象(如HttpRequest.BodyIBrowserFile.OpenReadStream())每当调用非异步Stream.ReadStream.Write方法时抛出异常,从而阻止开发人员使用非异步IO。

代码语言:javascript
运行
复制
- See this thread: [https://github.com/dotnet/aspnetcore/issues/7644](https://github.com/dotnet/aspnetcore/issues/7644)
- And this thread: [ASP.NET Core : Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead](https://stackoverflow.com/questions/47735133/asp-net-core-synchronous-operations-are-disallowed-call-writeasync-or-set-all)
- [This behaviour is controlled by `IHttpBodyControlFeature` - so you _can_ re-enable synchronous stream IO if you absolutely have to](https://stackoverflow.com/a/60985016/159145), but you really shouldn't.

  • 也不需要中间MemoryStream:您可以将ImageSharp输出直接写入响应。

适当的解决办法:

您正在调用ImageSharp的Image.Load方法,该方法使用非异步Stream方法。解决方法是简单地使用await Image.LoadAsync来代替:

因此,将代码更改为:

代码语言:javascript
运行
复制
// I assume this is a Controller Action method
// This method does not return an IActionResult because it writes directly to the response in the action method. See examples here: https://stackoverflow.com/questions/42771409/how-to-stream-with-asp-net-core

public async Task ResizeImageAsync( IBrowserFile file )
{
    await using( Stream stream = file.OpenReadStream() )
    using( Image image = await Image.LoadAsync( stream ) )
    {
        ResizeOptions ro = new ResizeOptions
        {
            Mode = ResizeMode.Min,
            Size = new Size(128)
        };

        image.Mutate( img => img.Resize( ro ) );

        if( file.ContentType == "image/png" ) // <-- You should not do this: *never trust* the client to be correct and truthful about uploaded files' types and contents. In this case it's just images so it's not that big a deal, but always verify independently server-side.
        {
            this.Response.ContentType = "image/png";
            await image.SaveAsPngAsync( this.Response.Body );
        }
        else
        {
            this.Response.ContentType = "image/jpeg";
            await image.SaveAsJpegAsync( this.Response.Body );
        }
}

替代(非)解决方案:拖延

只需禁用ASP.NET核心对非异步IO的禁止:

代码语言:javascript
运行
复制
public void ConfigureServices(IServiceCollection services)
{
    // If using Kestrel:
    services.Configure<KestrelServerOptions>(options =>
    {
        options.AllowSynchronousIO = true;
    });

    // If using IIS:
    services.Configure<IISServerOptions>(options =>
    {
        options.AllowSynchronousIO = true;
    });
}
票数 3
EN

Stack Overflow用户

发布于 2021-09-04 17:03:56

Image.Load是一个同步操作。相反,尝试使用异步版本:

代码语言:javascript
运行
复制
using var image = await Image.LoadAsync(file.OpenReadStream());
票数 3
EN

Stack Overflow用户

发布于 2021-09-04 16:35:36

您必须调用异步方法,如LoadAsyncDisposeAsync(),而不是同步Dispose()。使用await using xxx等待对DisposeAsync()的调用。

代码语言:javascript
运行
复制
public async Task<byte[]> ConvertFileToByteArrayAsync(IBrowserFile file)
{
    await using var image = await image.LoadAsync(file.OpenReadStream());
    image.Mutate(x => x.Resize(new ResizeOptions
    {
        Mode = ResizeMode.Min,
        Size = new Size(128)
    }));

    MemoryStream memoryStream = new MemoryStream();
    if (file.ContentType == "image/png")
    {

        await image.SaveAsPngAsync(memoryStream);
    }
    else
    {
        await image.SaveAsJpegAsync(memoryStream);
    }
    var byteFile = memoryStream.ToArray();
    memoryStream.Close();
    await memoryStream.DisposeAsync();

    return byteFile;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69056652

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档