首页 > 解决方案 > 如何从 Base64 字符串在 CollectionView 中显示图像?

问题描述

我正在尝试CollectionView在数据库中显示以 Base64 字符串形式存储的图像SQLite

XAML:

<CollectionView x:Name="PhotoView" HeightRequest="100" WidthRequest="400" HorizontalOptions="EndAndExpand">
   <CollectionView.ItemTemplate>
      <DataTemplate>
         <ViewCell>
             <Image Source="{Binding Image}"/>
         </ViewCell>
      </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

C#:

// This class is NOT stored in SQLite, I don't think you can store type ImageSource in a SQLite instance. It is only used for setting the CollectionView's ItemsSource.
private class Photos
        {
            public string UUID { get; set; }
            public string Base64 { get; set; }
            public ImageSource Image { get; set; }
        }

// Method called in constructor to update CollectionView
private void UpdatePhotoView()
{
   using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
   {
      PhotoView.ItemsSource = null;
      List<string> base64strings = conn.Query<Base64Table>("select * from Base64Table where Id = ?", thisPage.Id)
         .Select(x => x.Base64String)
         .ToList();
      List<Photos> photoview = new List<Photos>();
      foreach(var b64 in base64strings)
      {
         ImageSource i = Xamarin.Forms.ImageSource.FromStream(
                            () => new MemoryStream(Convert.FromBase64String(image)));
         Photos p = new Photos()
         {
            UUID = thisPage.Id,
            Base64 = b64,
            Image = i
         };
         photoview.Add(p);
      }
      PhotoView.ItemsSource = photoview;
   }
}

所发生的一切是,在加载它抛出的页面时System.InvalidCastException: 'Specified cast is not valid.'

我尝试将ImageCell换成ViewCell-enclosedImage对象,但发生了同样的错误。

我也尝试将原始 Base64 字符串设置为 a List<string>ItemsSource但它再次返回相同的错误。

标签: c#xamarinxamarin.formsbase64

解决方案


我觉得处理这个问题的最简单方法是直接在 base64 上使用转换器

转换器

using System;
using System.Globalization;
using Xamarin.Forms;

namespace xxxx
{

public class Base64ToImageSource : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string base64Image = (string)value;
        return base64Image.GetImageSourceFromBase64String();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }
}
}

然后添加这个字符串扩展方法

 public static ImageSource GetImageSourceFromBase64String(this string base64)
    {
        if (base64 == null)
        {
            return null;
        }

        byte[] Base64Stream = Convert.FromBase64String(base64);
        return ImageSource.FromStream(() => new MemoryStream(Base64Stream));
    }

然后直接使用这个转换器到你的源

<Image Source="{Binding Base64,Converter={StaticResource Base64ToImageSource}}"

确保将其添加到您的页面资源中,

如果您有任何问题,Goodluck 随时回复


推荐阅读