问题描述
大家好,我有一个字节 [],我从 Xamarin Essentials 媒体选择器中保存了它,我想在我的 XAML 页面上显示图像,所以我只有一个带有 StackLayout 的空白 XAML 页面,在我的代码中我做了以下:
Stream stream = new MemoryStream(filebyte);
var imageSource = ImageSource.FromStream(() => stream);
Image test = new Image();
test.source = imageSource;
test.WidthRequest = 50;
test.HeightRequest = 50;
ImageStack.Children.Add(test);
但是当页面加载时什么都没有。我错过了什么。我什至在一个使用最新版本的 Xamarin Forms 和 Xamarin Essential 的新项目中尝试了这个
解决方法
imgByteArray 是 Byte[],使用下面的代码通过后面的代码添加图像。
var stream1 = new MemoryStream(imgByteArray);
image.Source = ImageSource.FromStream(() => stream1);
image.WidthRequest = 50;
image.HeightRequest = 50;
imagestack.Children.Add(image);
更新:
在Forms中添加一张图片,设置Build action为Embedded resource,然后将此图片转换成byte[],使用这个byte[]来展示Image。我没有问题。
var image = new Xamarin.Forms.Image();
var assembly = this.GetType().GetTypeInfo().Assembly;
byte[] imgByteArray = null;
var s = assembly.GetManifestResourceStream("FormsSample.f19.png");
if (s != null)
{
var length = s.Length;
imgByteArray = new byte[length];
s.Read(imgByteArray,(int)length);
var stream1 = new MemoryStream(imgByteArray);
image.Source = ImageSource.FromStream(() => stream1);
image.WidthRequest = 50;
image.HeightRequest = 50;
imagestack.Children.Add(image);
}