来自 MemoryStream 的 UWP BitmapImage SetSource 挂起 [英] UWP BitmapImage SetSource from MemoryStream hangs

查看:12
本文介绍了来自 MemoryStream 的 UWP BitmapImage SetSource 挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my UWP app i store images in an SQLite db in form of byte[]. Then as i retrieve my objects from the db i bind them to a GridView data template which has an Image control. As i cant bind the Image's Source directly to the array, so i have created a BitmapImage property in my object's class to bind the Image control to:

    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 来解决:

The problem is, my app hangs on the img.SetSource line. After some experimenting, i have found that this problem can be overcome with a second 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;
            }
        }
    }

由于某种原因它有效,不会挂起.我想知道为什么?以及如何妥善处理这种情况?谢谢!

For some reason it works, does not hang. I wonder why? And how to deal with this situation properly? Thanks!

推荐答案

我建议您在应用中显示图像之前使用 IValueConverter 接口.

i'll suggest you use the IValueConverter interface before showing the image in your app.

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();
    }
}

这篇关于来自 MemoryStream 的 UWP BitmapImage SetSource 挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆