The best choice to display local pictures in MAUI Blazor? - Support Windows\macOS\Android\iOS

The best choice to display local pictures in MAUI Blazor? - Support Windows\macOS\Android\iOS

In MAUI Blazor, external files cannot be directly read and displayed, but you can display them through base64. However, base64 is too long, which may affect the interface jam...

最后更新 1/10/2023 9:59 PM
dotnet-simple
预计阅读 3 分钟
分类
MAUI Blazor
标签
.NET C# Blazor MAUI

The sample code in this article can be used to dynamically load local pictures. For the convenience of the demonstration, the code file path in the text is written dead.

First of all, external files cannot be directly read and displayed in MAUI Blazor, but you can display them through base64. However, because base64 is too long, it may affect the interface jam...

这个时候我们可以使用 blob 链接去加载外部图片,它不需要copy文件到wwwroot中,它会将byte转换一个urlBlazor去读取。

** Let's see the realization: **

首先第一步在wwwroot中的index.html添加一个js方法 用来将byte转换blob链接 将以下方法复制进去

<script>
/**
 * 将图片字节数组转换blob url
 */
function imgToLink(blob) {
    var myBlob = new Blob([blob], { type: "image/png" });
    return (window.URL || window.webkitURL || window || {}).createObjectURL(myBlob);
}

</script>

我们在Index.razor中添加以下代码

@page "/"
@inject IJSRuntime JS

<img src="@url" height="200px" width="200"/>

@code
{
    private string url;
    protected override async Task OnInitializedAsync()
    {
        // 放在项目目录下的logo.png会被打包到cache文件夹中 这里你也可以放外部文件链接 但是你需要保证再读取前有读取权限负责会报错
        var logo = Path.Combine(FileSystem.CacheDirectory, "logo.png");
        // 读取转换byte[]
        var data = await File.ReadAllBytesAsync(logo);
        // 通过js转换blob链接
        url = await JS.InvokeAsync<string>("imgToLink", data);
        await base.OnInitializedAsync();
    }
}

When we are done, we will add the pictures to the project:

Modify the image attribute to always copy:

Then execute the program directly:

这种效果比转base64更好,不会在界面残留太多字符串,极力推荐使用,如果你有更好的办法请推荐给我,欢迎在下方留言。

Example code:

  • gitee:https://gitee.com/hejiale010426/img-to-blob
  • github:https://github.com/239573049/ImgToBlob

Sharing from token

Technical exchange group: 737776595

This article comes from reprint.

Author: dotnet-simple

Original title: Maui reads external files and displays them in Blazor

Original link: www.cnblogs.com/hejiale010426/p/17040997.html

Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 1/12/2023

Maui Blazor uses a camera

Since the interface in Maui Blazor is rendered by WebView, it cannot be obtained when using the Android camera again, because the native camera needs to be bound with interface components.

继续阅读
同分类 / 同标签 4/26/2022

Using Masa Blazor in MAUI

Using. NET MAUI, you can develop applications that can run from a single shared code base on Android, iOS, macOS, Windows, and Linux(community support), with one set of codes running on multiple ends.

继续阅读