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

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

问题描述

在我的UWP应用中,我将图像以byte []的形式存储在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天全站免登陆