完整问题是如何在Windows Phone 8.1中显示从数据库加载的图像。 图像数据已作为字节数组加载(已检查 - 加载正常)。
通过指定urisource来显示图像可以正常工作。
否则
通过指定urisource来显示图像可以正常工作。
Image img = new Image();
img.Source = new BitmapImage() {UriSource = new Uri("http://www.example.com/1.jpg") };
rootgrid.Children.Add(img);
但是当字节数组(图像)转换为BitmapImage时,什么也不会显示。
到目前为止,我找到的唯一没有异常的示例是:
public BitmapImage ConvertToBitmapImage(byte[] image)
{
InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
var bitmapImage = new BitmapImage();
var memoryStream = new MemoryStream(image);
memoryStream.CopyToAsync(ras.AsStreamForWrite());
bitmapImage.SetSourceAsync(ras);
return bitmapImage;
}
Image img = new Image();
img.Source = ConvertToBitmapImage(picturebytearray);
rootgrid.Children.Add(img);
但是没有显示图片。
微软的文档只包含从内部存储打开文件获得的流加载图像的示例。但我需要加载保存在sqlite数据库中的图像。图像数据以jpeg格式存储。
编辑: 基于freshbm的解决方案的工作代码:
public async Task<BitmapImage> ConvertToBitmapImage(byte[] image)
{
BitmapImage bitmapimage = null;
using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
{
using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
{
writer.WriteBytes((byte[])image);
await writer.StoreAsync();
}
bitmapimage = new BitmapImage();
bitmapimage.SetSource(ms);
}
return bitmapimage;
}
那么在构造函数中,可以使用以下代码:
img.Source = ConvertToBitmapImage(imagebytearray).Result;
否则
img.Source = await ConvertToBitmapImage(imagebytearray);