'.net maui blazor - Show image from android internal storage

Im using the .net maui blazor to get the device to take a photo, then as its taken it, i wish to display it on the screen so the user can see what image they have just taken.

I found on the MS docs how to take a photo using var photo = await MediaPicker.CapturePhotoAsync();

and then it gives a simple way of storing this to the cache of the device using:

async Task LoadPhotoAsync(FileResult photo)
{
    // canceled
    if (photo == null)
    {
        PhotoPath = null;
        return;
    }
    // save the file into local storage
    var newFile = Path.Combine(FileSystem.CacheDirectory, photo.FileName);
    using (var stream = await photo.OpenReadAsync())
    using (var newStream = File.OpenWrite(newFile))
        await stream.CopyToAsync(newStream);

    PhotoPath = newFile;
}

Which i understand, its generating the file path, using the base class of FileResult that holds the steam, and then creating and dumping that onto the device.

However my issue comes form trying to display that image in the html.

I saw one Stackoverflow suggestion using

myImg.Source = PhotoPath;//Show on the front page

But I believe this is just for .net maui,

With the blazor and HTML elements I would like it to be using the

I'm currently storing the string in the PhotoPath, and then calling it from the HTML element as

<img src="@PhotoPath" ...>

but its just coming up with the "image not found" icon, im not sure if i have to set up a reader to go in and grab that image, and then display it though bytes.

Thanks



Solution 1:[1]

You can create a variable and assign the value after storing the photo.

Different from local image , we need to convert the data to Base64 string with bytes and specify its format , so that it could be displayed properly .

Sample code

@if (imageSource is not null)
{
    <div>
        <img src="@imageSource" width="200" height="200" />
    </div>
}

@code {
    private string? imageSource;

    protected override void OnInitialized()
    {
        var newFile = filePath;
        var imageBytes  = File.ReadAllBytes(newFile);
        imageSource = Convert.ToBase64String(imageBytes);
        imageSource = string.Format("data:image/png;base64,{0}", imageSource);
    }

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ColeX - MSFT