Wpf MVVM, How to convert ImageSource to byte array

1.5k views Asked by At

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

There are 1 answers

0
Gaurang Dave On BEST ANSWER

Try this:

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

REFERENCE: this & this