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转换一个url供Blazor去读取。
** 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