using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows;

namespace OVCS.ClientWpf.Tools
{
    public static class ExtenseMethod
    {
        [DllImport("gdi32.dll", SetLastError = true)]
        private static extern bool DeleteObject(IntPtr hObject);

        public static ImageSource GetImageSource(this Image image, string DefaultImg = null)
        {
            Bitmap bitmap1 = new Bitmap(image);
            return bitmap1.Bitmap2ImageSource();
        }

        public static ImageSource Bitmap2ImageSource(this Bitmap bitmap)
        {
            IntPtr hBitmap = bitmap.GetHbitmap();
            ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
            if (!DeleteObject(hBitmap))//记得要进行内存释放。否则会有内存不足的报错。
            {
                throw new System.ComponentModel.Win32Exception();
            }
            return wpfBitmap;
        }

        /// <summary>
        /// 是否显示控件
        /// </summary>
        /// <param name="show">必须传入一个布尔值</param>
        /// <returns></returns>
        public static Visibility GetVisibility(this bool show)
        {
            if (show)
            {
                return Visibility.Visible;
            }
            return Visibility.Collapsed;
        }
    }
}
