c# - 如何从 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
但它再次返回相同的错误。
解决方案
我觉得处理这个问题的最简单方法是直接在 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 随时回复
推荐阅读
- javascript - 检查对象属性的值和检查属性是否在对象中的区别
- cmake - find_library 如何处理版本号?
- javascript - Event.target.value 返回空字符串或空白
- ruby-on-rails - 在测试环境中禁用伪造保护时,测试如何抛出 InvalidAuthenticityToken?
- angular - Angular 中的 @Input 和 @HostBinding 装饰器有什么区别?
- python - Django:唯一约束失败:user.username
- bitbucket-pipelines - 为什么类星体“构建”不是一个已知命令?
- react-native - 在 Arduino 和 React Native 应用程序之间设置加密密钥
- python - 使用浮点列表进行循环
- sql - 在 Google Big Query 中将两个数组连接在一起