来自MemoryStream的UWP BitmapImage SetSource挂起

在我的UWP应用程序中,我以byte []的forms将图像存储在SQLite数据库中。 然后当我从db中检索我的对象时,我将它们绑定到具有Image控件的GridView数据模板。 由于我无法将Image的Source直接绑定到数组,因此我在对象的类中创建了一个BitmapImage属性,以将Image控件绑定到:

public BitmapImage Icon { get { using (var stream = new MemoryStream(icon)) { stream.Seek(0, SeekOrigin.Begin); var img = new BitmapImage(); img.SetSource(stream.AsRandomAccessStream()); return img; } } } 

问题是,我的应用程序挂在img.SetSource行上。 经过一些实验,我发现第二个MemoryStream可以解决这个问题:

  public BitmapImage Icon { get { using (var stream = new MemoryStream(icon)) { stream.Seek(0, SeekOrigin.Begin); var s2 = new MemoryStream(); stream.CopyTo(s2); s2.Position = 0; var img = new BitmapImage(); img.SetSource(s2.AsRandomAccessStream()); s2.Dispose(); return img; } } } 

出于某种原因,它可以工作,不会挂起。 我想知道为什么? 以及如何妥善处理这种情况? 谢谢!

我建议您在应用程序中显示图像之前使用IValueConverter界面。

 class ImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { if (value == null || !(value is byte[])) return null; using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream()) { using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0))) { writer.WriteBytes((byte[])value); writer.StoreAsync().GetResults(); } var image = new BitmapImage(); image.SetSource(ms); return image; } } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } 

我使用我在转换器中使用的扩展方法:

  public static BitmapImage AsBitmapImage(this byte[] byteArray) { if (byteArray != null) { using (var stream = new InMemoryRandomAccessStream()) { stream.WriteAsync(byteArray.AsBuffer()).GetResults(); // I made this one synchronous on the UI thread; // this is not a best practice. var image = new BitmapImage(); stream.Seek(0); image.SetSource(stream); return image; } } return null; } 

为什么不使用Base64? 在sqlite数据库列中保存Base64图像并轻松将其绑定到Image控件。

  

从sqlite db中绑定Gridview中的图像要容易得多。