如何在.Net MAUI Blazor中显示本地图像以及资源图像

Zia*_*mim 5 maui maui-blazor

在 .Net MAUI Blazor 中,我可以使用 img 标签来显示 wwwroot 文件夹中的图像。但是如何显示设备内部存储中的图像呢?以及如何显示应用程序资源中的图像?

Col*_*SFT 5

来自内部存储

我们可以将其读入bytes并将其转换为base64字符串,然后显示在img标签上。

假设我们已经将一个名为的图像放入文件夹dog.png中。FileSystem.CacheDirectory

示例代码

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

@code {
    private string? imageSource;

    protected override void OnInitialized()
    {
        var newFile = Path.Combine(FileSystem.CacheDirectory, "dog.png");
        var imageBytes  = File.ReadAllBytes(newFile);
        imageSource = Convert.ToBase64String(imageBytes);
        imageSource = string.Format("data:image/png;base64,{0}", imageSource);
    }
}
Run Code Online (Sandbox Code Playgroud)


Pou*_*tor 5

根据我的研究:您实际上可以使用以下命令获取 razor 应用程序中 wwwroot 文件夹的路径:AppDomain.CurrentDomain.BaseDirectory。在 Windows 中,您可以在此文件夹中添加可通过 Blazor HTML 访问的文件。但是,在 Android 中,wwwroot 文件夹嵌入在应用程序中,并且无法访问(AppDomain.CurrentDomain.BaseDirectory返回空文件夹)。

在查看课程中的 .NET MAUI github 存储库后,BlazorWebView我发现:

public virtual IFileProvider CreateFileProvider(string contentRootDir)
{
    // Call into the platform-specific code to get that platform's asset file provider
    return ((BlazorWebViewHandler)(Handler!)).CreateFileProvider(contentRootDir);
}
Run Code Online (Sandbox Code Playgroud)

可用于将文件传递到 Blazor。例如,如果您想访问 AppDataDirectory 中的所有文件:

using Microsoft.AspNetCore.Components.WebView.Maui;
using Microsoft.Extensions.FileProviders;

public class CustomFilesBlazorWebView : BlazorWebView
{
    public override IFileProvider CreateFileProvider(string contentRootDir)
    {
        var lPhysicalFiles = new PhysicalFileProvider(FileSystem.Current.AppDataDirectory);
        return new CompositeFileProvider(lPhysicalFiles, base.CreateFileProvider(contentRootDir));
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在MainPage.xaml

<local:CustomFilesBlazorWebView HostPage="wwwroot/index.html" x:Name="WebView">
    <BlazorWebView.RootComponents>
        <RootComponent Selector="#app" ComponentType="{x:Type local:Main}" />
    </BlazorWebView.RootComponents>
</local:CustomFilesBlazorWebView>
Run Code Online (Sandbox Code Playgroud)

例如,如果 AppDataDirectory 中的images/user.png任何 Blazor 组件中有一个文件,您可以使用:

    <img src="images/user.png" />
Run Code Online (Sandbox Code Playgroud)


Too*_*eve 2

要从资源显示,请参阅\xe2\x80\xa6 Blazor Hybrid static Files / .Net Maui

\n
    \n
  • 将文件添加到项目中名为 Resources/Raw 的文件夹中。
  • \n
  • 确保文件/属性/构建操作= MauiAsset。
  • \n
  • 创建一个剃刀组件:\n
      \n
    • 调用Microsoft.Maui.Storage.FileSystem.OpenAppPackageFileAsync以获取资源的 Stream。
    • \n
    • 使用 StreamReader 读取流。
    • \n
    • 调用 StreamReader.ReadToEndAsync 来读取文件。
    • \n
    \n
  • \n
\n

剃刀代码示例(来自该链接):

\n
@page "/static-asset-example"\n@using System.IO\n@using Microsoft.Extensions.Logging\n@using Microsoft.Maui.Storage\n@inject ILogger<StaticAssetExample> Logger\n\n<h1>Static Asset Example</h1>\n\n<p>@dataResourceText</p>\n\n@code {\n    public string dataResourceText = "Loading resource ...";\n\n    protected override async Task OnInitializedAsync()\n    {\n        try\n        {\n            using var stream = \n                await FileSystem.OpenAppPackageFileAsync("Data.txt");\n            using var reader = new StreamReader(stream);\n\n            dataResourceText = await reader.ReadToEndAsync();\n        }\n        catch (FileNotFoundException ex)\n        {\n            dataResourceText = "Data file not found.";\n            Logger.LogError(ex, "\'Resource/Raw/Data.txt\' not found.");\n        }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

要从 razor 代码访问本地文件(不是资源中的资产),您\xe2\x80\x99 需要给service定文件名(或相对路径),将文件内容作为流返回。

\n

我\xe2\x80\x99m 没有找到文档说明如何为毛伊岛做到这一点,然后将其注入到剃刀代码中。

\n

此类服务将使用.Net 文件系统帮助程序来访问文件。这与上面的 MauiAsset 示例类似,但使用路径助手之一,而不是调用 OpenAppPackageFileAsync。

\n

TBD - 有人给出参考链接或示例吗?

\n