/******************************************************************************** ** 类名称: Convert ** 描述 : 图片数据转换对象 ** 作者 : 丁书杰 ** 创建时间:2018/08/10 ** 版权所有 (C) :中科视语(北京)科技有限公司 *********************************************************************************/ using OpenCvSharp; using System; using System.Drawing; using System.Windows; using System.Windows.Interop; using System.Windows.Media.Imaging; namespace OS.Spin.Common { public class UserConvert { [System.Runtime.InteropServices.DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); #region Mat2BitmapSource /// /// 根据Mat转化成绑定在Image控件的BitmapSource /// /// 数据矩阵源 /// 绑定在Image控件的BitmapSource public static BitmapSource Mat2BitmapSource(Mat mat) { try { if (null == mat || mat.Cols * mat.Rows == 0 || mat.Depth() != MatType.CV_8U) { return null; } var formart = System.Drawing.Imaging.PixelFormat.Format24bppRgb; if (mat.Channels() == 1) { formart = System.Drawing.Imaging.PixelFormat.Format8bppIndexed; ; } var bmpImg = new Bitmap(mat.Cols, mat.Rows, (int)mat.Step(), formart, mat.Data); return Bitmap2BitmapSource((Bitmap)bmpImg.Clone()); } catch (Exception ex) { LogisTrac.WriteLog(string.Format("Mat2BitmapSource(Mat mat):{0}", ex.Message)); return null; } } #endregion public static BitmapSource Bitmap2BitmapSource(Bitmap bmpImg) { try { if (null == bmpImg) { return null; } IntPtr hBitmap = bmpImg.GetHbitmap(); var source = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); DeleteObject(hBitmap); return source.Clone(); } catch (Exception ex) { LogisTrac.WriteLog(string.Format("Bitmap2BitmapSource(Bitmap bmpImg):{0}", ex.Message)); return null; } } } }