Dan Schnau

Upload and render image in Blazor WASM client-side application

Here's some sample code for a blazor client-side component that allows uploading and rending an image. The cool thing about this is that it all happens client-side and allows working with the image in .NET. All that is needed is some interop javascript code, borrowed from this document: https://learn.microsoft.com/en-us/aspnet/core/blazor/images?view=aspnetcore-7.0#stream-image-data

@page "/"
@using Microsoft.AspNetCore.Components.Forms
@inject IHttpClientFactory HttpClientFactory
@inject IJSRuntime JS

<InputFile OnChange="@Upload_And_Render_Image" />

<img id="myImage" />

<script>
  window.setImage = async (imageElementId, imageStream) => {
    const arrayBuffer = await imageStream.arrayBuffer();
    const blob = new Blob([arrayBuffer]);
    const url = URL.createObjectURL(blob);
    const image = document.getElementById(imageElementId);
    image.onload = () => {
      URL.revokeObjectURL(url);
    }
    image.src = url;
  }
</script>

@code {

    public async Task Upload_And_Render_Image(InputFileChangeEventArgs e)
    {
        Stream ms = new MemoryStream();
        await e.File.OpenReadStream().CopyToAsync(ms);
        ms.Position = 0;
        var dotnetImageStream = new DotNetStreamReference(ms);
        await JS.InvokeVoidAsync("setImage", "myImage", dotnetImageStream);
    }

}