2

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; }
Usman Ali
  • 778
  • 8
  • 21

1 Answers1

4

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

Clemens
  • 123,504
  • 12
  • 155
  • 268
Gaurang Dave
  • 3,956
  • 2
  • 15
  • 34