Viewing an image captured in a Blazor Web Assembly PWA

1.2k Views Asked by At

Following on from the example Access Device Camera with Blazor I would like to view the image on the same page. So far I have found several older examples using JS but I think I should stick to native Blazor.

I think this is the start, but have failed to reference the file that was selected.

<p>
    <h1>My Camera App</h1>
</p>
<input @onchange="updateCanvas" id="capturedPic" type="file" accept="image/*" capture>
<br />
<canvas id="picCanvas"> </canvas>
<br />
<br />
@code
{
    public void updateCanvas()
    {
        //Code to place captured image in the canvas;

    }

}
1

There are 1 best solutions below

0
Francis Leishman On

Following the .NET5 introduction of InputFile, I have the following solution.

The max size of an image is 500K so the code converts the camera photo to a 100x100 thumbnail.

Many thanks to Daniel https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-5-release-candidate-1/ and Naveen https://www.learmoreseekmore.com/2020/10/blazor-webassembly-fileupload.html

   <div>
        <InputFile OnChange="@OnFileSelection"></InputFile>
        <div class="row">
            <img src="@imgUrl">
        </div>
    </div>
    @code{
        string imgUrl = string.Empty;
        private async Task OnFileSelection(InputFileChangeEventArgs e)
        {
            IBrowserFile imgFile = e.File;
            string imageType = imgFile.ContentType;
            var resizedImageFile = await imgFile.RequestImageFileAsync(imageType, 100, 100);
            var buffers = new byte[resizedImageFile.Size];
            await resizedImageFile.OpenReadStream().ReadAsync(buffers);
            imgUrl = $"data:{imageType};base64,{Convert.ToBase64String(buffers)}";
        }
    }