using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Media.Imaging;

namespace JianGongYun.TRTC.Utils
{
    public static class WriteableBitmapToMat
    {
        /// <summary>
        /// WriteableBitmap转Mat
        /// </summary>
        /// <param name="writeableBitmap"></param>
        /// <returns></returns>
        public static Mat ToMat(this WriteableBitmap writeableBitmap)
        {
            using (var bmp = writeableBitmap.ToBitmap())
            {
                var mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);
                return mat;
            }
        }
        /// <summary>
        /// WriteableBitmap转Bitmap
        /// </summary>
        /// <param name="writeableBitmap"></param>
        /// <returns></returns>
        public static Bitmap ToBitmap(this WriteableBitmap writeableBitmap)
        {
            using (MemoryStream outStream = new MemoryStream())
            {
                //System.Windows.Media.Imaging.WmpBitmapEncoder
                BitmapEncoder enc = new BmpBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create(writeableBitmap));
                enc.Save(outStream);
                return new System.Drawing.Bitmap(outStream);
            }
        }

        public static string ToFile(this WriteableBitmap writeableBitmap, string fileName)
        {
            using (var file = File.Create(fileName))
            {
                BitmapEncoder enc = new BmpBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create(writeableBitmap));
                enc.Save(file);
                return fileName;
            }
        }
    }
}
