【问题标题】:How to display local image as well as resources image in .Net MAUI Blazor如何在.Net MAUI Blazor 中显示本地图片和资源图片
【发布时间】:2022-11-25 05:40:52
【问题描述】:

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

【问题讨论】:

    标签: maui maui-blazor


    【解决方案1】:

    要从资源中显示,请参阅… Blazor Hybrid static Files / .Net Maui

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

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

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

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

    我没有找到文档说明如何为 Maui 执行此操作,然后将其注入剃须刀代码。

    这样的服务将使用.Net File System Helpers 来访问该文件。这类似于上面的 MauiAsset 示例,但使用其中一个路径助手,而不是调用 OpenAppPackageFileAsync。

    待定 - 有人提供参考链接或示例吗?

    【讨论】:

      【解决方案2】:

      从内部存储

      我们可以将它读入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);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2022-11-13
        • 2015-08-02
        • 2012-05-20
        • 2014-10-19
        • 2022-06-23
        • 1970-01-01
        • 1970-01-01
        • 2022-11-19
        • 1970-01-01
        相关资源
        最近更新 更多