我正在尝试使用Blazor输入文件和Imagesharp库将IBrowserFile转换为图像。
我的方法是这样的
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;
}
但我得到了以下错误:
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打开的流。
发布于 2021-09-04 17:07:28
背景:
Stream
对象(如HttpRequest.Body
和IBrowserFile.OpenReadStream()
)每当调用非异步Stream.Read
和Stream.Write
方法时抛出异常,从而阻止开发人员使用非异步IO。- 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
来代替:
因此,将代码更改为:
// 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的禁止:
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;
});
}
发布于 2021-09-04 17:03:56
Image.Load
是一个同步操作。相反,尝试使用异步版本:
using var image = await Image.LoadAsync(file.OpenReadStream());
发布于 2021-09-04 16:35:36
您必须调用异步方法,如LoadAsync
、DisposeAsync()
,而不是同步Dispose()
。使用await using xxx
等待对DisposeAsync()
的调用。
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;
}
https://stackoverflow.com/questions/69056652
复制相似问题