【问题标题】:Windows Phone 8 - Load byte[] array into XAML image with BindingWindows Phone 8 - 使用绑定将字节 [] 数组加载到 XAML 图像中
【发布时间】:2013-10-08 22:15:17
【问题描述】:

我将图像存储为 byte[] 数组,因为我无法将它们存储为 BitmapImage。 ShotItem 类将存储在 ObservableCollection 中的 IsolatedStorage 中。

namespace MyProject.Model
{
    public class ShotItem : INotifyPropertyChanged, INotifyPropertyChanging
    {
        private byte[] _shotImageSource;
        public byte[] ShotImageSource
        {
            get
            {
                return _shotImageSource;
            }
            set
            {
                NotifyPropertyChanging("ShotImageSource");

                _shotImageSource = value;
                NotifyPropertyChanged("ShotImageSource");
            }
        }
        ...
    }
}

在我的 xaml 文件中,我有以下内容:

<Image Source="{Binding ShotImageSource}" Width="210" Height="158" Margin="12,0,235,0" VerticalAlignment="Top" />

不幸的是,我无法将图像作为字节直接加载到 xaml 中的 Image 容器中。我不知何故需要将 ShotImageSource byte[] 转换为 BitmapImage。我正在加载很多图像,所以这也必须异步完成。

我尝试使用转换器绑定,但不确定如何使其工作。任何帮助将不胜感激:)。

【问题讨论】:

  • 您需要有一个绑定转换器,可以从字节数组创建一个 BitmapSource。如果字节数组包含编码图像(PNG 或 JPEG),您可以从中创建一个流并调用BitmapSource.SetSourceAsync。如果字节数组是原始像素缓冲区,您可以创建一个 WriteableBitmap 并将像素复制到其PixelBuffer

标签: c# wpf windows xaml windows-phone-8


【解决方案1】:

这是 Converter 的代码,它将您的 byte[] 转换为 BitmapImage

public class BytesToImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null && value is byte[])
        {
            byte[] bytes = value as byte[];
            MemoryStream stream = new MemoryStream(bytes);
            BitmapImage image = new BitmapImage();

            image.SetSource(stream);

            return image;
        }

        return null;

    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

【讨论】:

  • 除了这个转换器,您还应该在 XAML 中指定它:<image source="{Binding ShotImageSource, Converter={StaticResource BytesToImageConverter}}"></image>
  • 如果你使用的是win8.1,它都是异步的,所以内存流的东西不再适用。解决方案在这里chrispeerman.info/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-23
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多