WPF MVVM,如何将ImageSource转换为字节数组 [英] Wpf MVVM, How to convert ImageSource to byte array

查看:280
本文介绍了WPF MVVM,如何将ImageSource转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

in my application i am taking snapshot from live video which i then assign to ImageSource, Now i want to Convert ImageSource to 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; }

推荐答案

尝试一下:

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

You can take other encoder as well.

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

参考:&

这篇关于WPF MVVM,如何将ImageSource转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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