What's wrong with InputFile in Blazor?
(Edit: "what's wrong with my implementation of InputFile, as someone pointed out in the comment")
this was the actual image I'm trying to upload,
and this is the resulting display, after uploading; the image is cropped. On top of that, the application also stops working all of a sudden.
and here's the piece of code what is called on the OnChange
event of the InputFile
async Task OnFileChange(InputFileChangeEventArgs e) {
const string format = "image/png";
var resizedImage = await e.File.RequestImageFileAsync(format, 512, 512);
var buffer = new byte[resizedImage.Size];
await resizedImage.OpenReadStream().ReadAsync(buffer);
imageBase64 = $"data:{format};base64,{Convert.ToBase64String(buffer)}";
}
the usual tutorials use 200 or 256 as image size, though all I did was just double the value, which is still below the threshold of the
RequestImageFileAsync
method which is 512000
Edit 1: this is the snippet of the button that triggers the InputFile
<MudFab HtmlTag="label" Size="Size.Small" Color="Color.Primary" StartIcon="@Icons.Filled.CloudUpload" for="fileInput" />
here's the snippet of the InputFile on the razor page.
<InputFile id="fileInput" OnChange="OnFileChange" hidden multiple accept=".jpg, .jpeg, .png" />
here's the image component displaying the image
<MudImage ObjectFit="ObjectFit.ScaleDown" Src="@imageBase64" Elevation="25" Class="rounded my-2"></MudImage>
note that I'm indeed using Mudblazor, but I don't think that is of any significance. I tried it on vanilla HTML but still the same issue.
I have slimmed the code so if you put it together, the razor page should look like this:
@page "/tryImage"
<PageTitle>Try Image</PageTitle>
<InputFile id="fileInput" OnChange="OnFileChange" hidden multiple accept=".jpg, .jpeg, .png" />
<MudImage ObjectFit="ObjectFit.ScaleDown" Src="@imageBase64" Elevation="25" Class="rounded my-2"></MudImage>
<MudFab HtmlTag="label" Size="Size.Small" Color="Color.Primary" StartIcon="@Icons.Filled.CloudUpload" for="fileInput" />
@code {
private string? imageBase64;
async Task OnFileChange(InputFileChangeEventArgs e) {
const string format = "image/png";
var resizedImage = await e.File.RequestImageFileAsync(format, 512, 512);
var buffer = new byte[resizedImage.Size];
await resizedImage.OpenReadStream().ReadAsync(buffer);
imageBase64 = $"data:{format};base64,{Convert.ToBase64String(buffer)}";
}
}
Edit 2:
Or is it possible that the error has something to do with large images in conflict with RequestImageFileAsync
since the sample image I showed above is about 1.2 MB and has dimensions of 4929x3286?