【问题标题】:Wpf MVVM, How to convert ImageSource to byte array [duplicate]Wpf MVVM,如何将 ImageSource 转换为字节数组 [重复]
【发布时间】:2018-02-12 04:28:35
【问题描述】:

在我的应用程序中,我从实时视频中拍摄快照,然后将其分配给 ImageSource,现在我想将 ImageSource 转换为 Byte[]

private ImageSource mSnapshotTaken;
    public ImageSource SnapshotTaken
    {
        get => mSnapshotTaken;
        set
        {
            if (value == null)
            {

            }
            else
            {
                mSnapshotTaken = value;

                // SnapshotToByte = mSnapshotTaken 


                OnPropertyChanged("SnapshotTaken");
            }
        }
    }
    public byte[] SnapshotToByte { get; set; }

【问题讨论】:

    标签: wpf mvvm


    【解决方案1】:

    试试这个:

    您也可以使用其他编码器。

    private ImageSource mSnapshotTaken;
    public ImageSource SnapshotTaken
    {
        get => mSnapshotTaken;
        set
        {
             mSnapshotTaken = value;
             SnapshotToByte = ImageSourceToBytes(mSnapshotTaken);
             OnPropertyChanged("SnapshotTaken");
             OnPropertyChanged("SnapshotToByte");
        }
    }
    
    public byte[] SnapshotToByte { get; set; }
    
    public byte[] ImageSourceToBytes(ImageSource imageSource)
    {
        byte[] bytes = null;
        var bitmapSource = imageSource as BitmapSource;
    
        if (bitmapSource != null)
        {
            var encoder = new JpegBitmapEncoder(); 
            encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
    
            using (var stream = new MemoryStream())
            {
                encoder.Save(stream);
                bytes = stream.ToArray();
            }
        }
    
        return bytes;
    }
    

    参考:this & this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-12
      • 1970-01-01
      • 2014-12-03
      • 2012-07-24
      • 2011-10-25
      • 2018-04-25
      • 1970-01-01
      相关资源
      最近更新 更多