UserConvert.cs
2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/********************************************************************************
** 类名称: 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
/// <summary>
/// 根据Mat转化成绑定在Image控件的BitmapSource
/// </summary>
/// <param name="mat">数据矩阵源</param>
/// <returns>绑定在Image控件的BitmapSource</returns>
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;
}
}
}
}