Wpf MVVM,如何将ImageSource转换为字节数组

时间:2018-02-12 04:28:36

标签: wpf mvvm

在我的应用程序中,我从实时视频拍摄快照,然后我将其分配给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; }

1 个答案:

答案 0 :(得分: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