Commit a62b84e3 LN

增加codeLibary代码

1 个父辈 8d9482bc
using Basler.Pylon;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class BaslerCamera
{
public static BaslerCamera Instance= new BaslerCamera();
/// <summary>
/// 当前相机
/// </summary>
private Camera cameraCur = null;
/// <summary>
/// 所有相机列表
/// </summary>
private List<ICameraInfo> cameraAll;
/// <summary>
/// 所有相机的名称
/// </summary>
private List<string> cameraName;
/// <summary>
/// 获取连续图像
/// </summary>
public delegate void GrabImageEvent();
/// <summary>
/// 获取连续图像事件,需要跨线程操作
/// </summary>
public event GrabImageEvent GrabImage;
private BaslerCamera()
{
Load();
}
/// <summary>
/// 错误信息
/// </summary>
public string ErrInfo { set; get; }
/// <summary>
/// 相机总数
/// </summary>
public int Count
{
get { return cameraAll == null ? 0 : cameraAll.Count; }
}
/// <summary>
/// 相机名称,ModelName,SerialNumber
/// </summary>
public string[] CameraName
{
get {
if (cameraName == null)
{
cameraName = new List<string>();
}
return cameraName.ToArray(); }
}
/// <summary>
/// 当前相机是否打开
/// </summary>
public bool IsOpen
{
get
{
if (cameraCur == null)
return false;
else
return cameraCur.IsOpen;
}
}
/// <summary>
/// 相机图像宽度
/// </summary>
public int Width { set; get; }
/// <summary>
/// 相机图像高度
/// </summary>
public int Height { set; get; }
/// <summary>
/// 相机32位缓存
/// </summary>
public byte[] Buffer { get; private set; }
/// <summary>
/// 相机32位图像
/// </summary>
public Bitmap Image { get; private set; }
/// <summary>
/// 加载相机
/// </summary>
public void Load()
{
try
{
cameraAll = CameraFinder.Enumerate();
cameraName = new List<string>();
foreach (ICameraInfo info in cameraAll)
cameraName.Add(info[CameraInfoKey.ModelName].ToString() + " (" + info[CameraInfoKey.SerialNumber].ToString() + ")");
}
catch (Exception ex)
{
HDLogUtil.error("Basler Load Error:" + ex.StackTrace);
}
}
/// <summary>
/// 打开指定相机
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public bool Open(string name)
{
int n = cameraName.FindIndex(s => s == name);
if (n == -1)
return false;
else
return Open(n);
}
/// <summary>
/// 打开指定相机
/// </summary>
/// <param name="idx">索引</param>
/// <returns></returns>
public bool Open(int idx)
{
if (idx < 0 || idx >= cameraAll.Count) return false;
if (cameraCur != null) Close();
try
{
cameraCur = new Camera(cameraAll[idx]);
//cameraCur.ConnectionLost += OnConnectionLost;
//cameraCur.CameraOpened += OnCameraOpened;
//cameraCur.CameraClosed += OnCameraClosed;
//cameraCur.StreamGrabber.GrabStarted += OnGrabStarted;
cameraCur.StreamGrabber.ImageGrabbed += OnImageGrabbed;
//cameraCur.StreamGrabber.GrabStopped += OnGrabStopped;
cameraCur.Open();
Width = Convert.ToInt32(cameraCur.Parameters[PLCamera.Width].GetValue());
Height = Convert.ToInt32(cameraCur.Parameters[PLCamera.Height].GetValue());
cameraCur.Parameters[PLCamera.UserSetSelector].SetValue(PLCamera.UserSetSelector.UserSet1); //加载用户设置1
bool bln = cameraCur.Parameters[PLCamera.UserSetLoad].TryExecute(); //执行设置
return true;
}
catch (Exception ex)
{
ErrInfo = ex.Message;
return false;
}
}
/// <summary>
/// 关闭当前相机
/// </summary>
public void Close()
{
if (cameraCur != null)
{
cameraCur.Close();
cameraCur.Dispose();
cameraCur = null;
}
}
/// <summary>
/// 停止抓取数据
/// </summary>
public void Stop()
{
if (cameraCur != null)
cameraCur.StreamGrabber.Stop();
}
/// <summary>
/// 抓取一张图像
/// </summary>
public void GrabOne()
{
cameraCur.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.SingleFrame);
//cameraCur.StreamGrabber.Start();
//IGrabResult grabResult = cameraCur.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
IGrabResult grabResult = cameraCur.StreamGrabber.GrabOne(5000);
if (!grabResult.IsValid) return;
Image = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
BitmapData bmpData = Image.LockBits(new Rectangle(0, 0, grabResult.Width, grabResult.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
IntPtr ptrBmp = bmpData.Scan0;
int picSize = bmpData.Stride * grabResult.Height;
PixelDataConverter conv = new PixelDataConverter();
conv.OutputPixelFormat = PixelType.BGRA8packed;
conv.Convert(ptrBmp, picSize, grabResult);
Buffer = new byte[picSize];
System.Runtime.InteropServices.Marshal.Copy(ptrBmp, Buffer, 0, picSize);
Image.UnlockBits(bmpData);
//cameraCur.StreamGrabber.Stop();
}
/// <summary>
/// 抓取连续图像,触发GrabImage事件
/// </summary>
public void GrabContinuous()
{
cameraCur.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
cameraCur.StreamGrabber.Start(GrabStrategy.OneByOne, GrabLoop.ProvidedByStreamGrabber);
}
private void OnImageGrabbed(object sender, ImageGrabbedEventArgs e)
{
try
{
IGrabResult grabResult = e.GrabResult;
if (!grabResult.IsValid) return;
Image = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
BitmapData bmpData = Image.LockBits(new Rectangle(0, 0, grabResult.Width, grabResult.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
IntPtr ptrBmp = bmpData.Scan0;
int picSize = bmpData.Stride * grabResult.Height;
PixelDataConverter conv = new PixelDataConverter();
conv.OutputPixelFormat = PixelType.BGRA8packed;
conv.Convert(ptrBmp, picSize, grabResult);
Buffer = new byte[picSize];
System.Runtime.InteropServices.Marshal.Copy(ptrBmp, Buffer, 0, picSize);
Image.UnlockBits(bmpData);
GrabImage?.Invoke();
}
catch (Exception ex)
{
ErrInfo = ex.Message;
}
finally
{
e.DisposeGrabResultIfClone();
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{2E0D9598-CB37-46DC-9C9B-D36D4D344451}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CodeLibrary</RootNamespace>
<AssemblyName>CodeLibrary</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Basler.Pylon, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e389355f398382ab, processorArchitecture=x86">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\dll\Basler.Pylon.dll</HintPath>
</Reference>
<Reference Include="halcondotnet">
<HintPath>..\dll\halcondotnet.dll</HintPath>
</Reference>
<Reference Include="log4net">
<HintPath>..\dll\log4net.dll</HintPath>
</Reference>
<Reference Include="MvCameraControl.Net">
<HintPath>..\dll\MvCameraControl.Net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="camera\Basler.cs" />
<Compile Include="camera\Common.cs" />
<Compile Include="camera\HIK.cs" />
<Compile Include="FrmBase.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmBase.Designer.cs">
<DependentUpon>FrmBase.cs</DependentUpon>
</Compile>
<Compile Include="FrmCodeLearn.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmCodeLearn.Designer.cs">
<DependentUpon>FrmCodeLearn.cs</DependentUpon>
</Compile>
<Compile Include="FrmCodeDecode.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmCodeDecode.Designer.cs">
<DependentUpon>FrmCodeDecode.cs</DependentUpon>
</Compile>
<Compile Include="HDCodeHelper.cs" />
<Compile Include="HDCodeLearnHelper.cs" />
<Compile Include="HDLogUtil.cs" />
<Compile Include="ImageHelper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="CodeResourceControl.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="FrmBase.resx">
<DependentUpon>FrmBase.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="FrmCodeLearn.resx">
<DependentUpon>FrmCodeLearn.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="FrmCodeDecode.resx">
<DependentUpon>FrmCodeDecode.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Content Include="resources\resources.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="记录.txt" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
\ No newline at end of file \ No newline at end of file
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CodeLibrary
{
public class CodeResourceControl
{
//public delegate string GetStrDelegate(string id, string defaultStr);
//public static event GetStrDelegate GetStrEvent;
//public delegate string GetStringDelegate(string id, string defaultStr, params object[] param);
//public static event GetStringDelegate GetStringEvent;
public static bool OpenResourceLog = false;
public static string China = "zh-CN";
public static string English = "en-US";
private static Dictionary<string, string> chineseMap = new Dictionary<string, string>();
internal static string GetString(object selCamera, string v)
{
throw new NotImplementedException();
}
private static Dictionary<string, string> englishMap = new Dictionary<string, string>();
public delegate string GetLanguageDelegate();
public static event GetLanguageDelegate GetLanguageEvent;
public static string GetLanguage()
{
if (GetLanguageEvent == null)
{
return China;
}
string result = GetLanguageEvent?.Invoke();
if (result == null)
{
return "";
}
return result;
}
private static string spiltStr = "_";
private static string Text = "Text";
public static string GetTextIdStr(string className, string controlName)
{
return className + spiltStr + controlName + spiltStr + Text;
}
public static string GetTextIdStr(string className)
{
return className + spiltStr + Text;
}
public static string GetString(string id, string defaultStr)
{
string strCurLanguage = "";
try
{
if (GetLanguage().Equals(China))
{
chineseMap.TryGetValue(id,out strCurLanguage);
}else if (GetLanguage().Equals(English))
{
englishMap.TryGetValue(id, out strCurLanguage);
}
if ((strCurLanguage==null||strCurLanguage.Equals("") )&& (!defaultStr.Equals("")))
{
strCurLanguage = defaultStr;
NoIdLog(id, defaultStr);
}
}
catch (Exception ex)
{
if (defaultStr.Equals(""))
{
}
else
{
strCurLanguage = "No id:[" + id + "], please add.";
strCurLanguage = defaultStr;
NoIdLog(id, defaultStr);
}
}
return strCurLanguage;
}
public static string GetString(string id, string defaultStr, params object[] param)
{
string strCurLanguage = GetString(id, defaultStr);
return String.Format(strCurLanguage, param);
}
private static void NoIdLog(string id, string defaultStr)
{
if (OpenResourceLog)
{
HDLogUtil.info("No id:[" + id + "], please add,use default string :" + defaultStr);
}
}
static CodeResourceControl()
{
try
{
chineseMap = new Dictionary<string, string>();
englishMap = new Dictionary<string, string>();
string path = Application.StartupPath + @"\resources\resources.txt";
string[] lines = File.ReadAllLines(path);
foreach (string line in lines)
{
string[] array = line.Split(',');
if (array.Length >= 3)
{
string key = array[0];
string chinese = array[1];
string english = array[2];
if (chineseMap.ContainsKey(key))
{
chineseMap.Remove(key);
}
if (englishMap.ContainsKey(key))
{
englishMap.Remove(key);
}
chineseMap.Add(key, chinese);
englishMap.Add(key, english);
}
}
HDLogUtil.error("加载中英文配置文件完成,长度【" + chineseMap.Count + "】");
}
catch (Exception ex)
{
HDLogUtil.error("CodeResourceControl" + ex.ToString());
}
}
/// <summary>
/// 请先选择相机
/// </summary>
public static string selCamera = "selCamera";
/// <summary>
/// 请先选择图片
/// </summary>
public static string selImage = "selImage";
/// <summary>
/// 提示
/// </summary>
public static string title = "title";
/// <summary>
/// 获取二维码图片为空
/// </summary>
public static string imageIsNull = "imageIsNull";
/// <summary>
/// 确定删除文件:
/// </summary>
public static string sureDelete = "sureDelete";
}
}
using HalconDotNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class DHBarCodeHelper
{ /// <summary>
/// 根据图片解析二维码
/// </summary>
/// <param name="ho_Image">Halcon中的图片对象</param>
/// <param name="codeCount">二维码数量</param>
/// <param name="codeParamPath">二维码参数路径,""表示不使用参数</param>
/// <param name="paramType">二维码类型,不传类型默认Data Matrix ECC 200</param>
/// <returns>解析到的二维码</returns>
public static List<CodeInfo> DecodeCode(HObject ho_Image, int codeCount, string codeParamPath, params string[] paramType)
{
List<string> codeType = new List<string>(paramType.ToList());
if (codeType.Count<string>() <= 0)
{
codeType.Add("CODE_39");
}
List<CodeInfo> codeList = new List<CodeInfo>();
foreach (string t in codeType)
{
List<CodeInfo> array = GetCode(ho_Image, t, codeParamPath, codeCount);
codeList.AddRange(array.ToArray<CodeInfo>());
}
return codeList;
}
private static List<CodeInfo> GetCode(HObject ho_Image, string symbolType, string hv_model_path, int codeCount)
{
List<CodeInfo> codeList = new List<CodeInfo>();
try
{
HTuple hv_Area = null;
HTuple hv_Row1 = null;
HTuple hv_Column = null;
HTuple hv_PointOrder = null;
HObject ho_SymbolXLDs;
HTuple hv_ResultHandles = null;
HTuple hv_DecodedDataStrings = null;
HTuple hv_DataCodeHandle = null;
HOperatorSet.GenEmptyObj(out ho_SymbolXLDs);
HOperatorSet.CreateBarCodeModel(symbolType, "default_parameters", "maximum_recognition", out hv_DataCodeHandle);
//string hv_model_path = GetCodeParamFilePath(symbolType);
if (!hv_model_path.Equals("") && File.Exists(hv_model_path))
{
HOperatorSet.ReadDataCode2dModel(hv_model_path, out hv_DataCodeHandle);
}
ho_SymbolXLDs.Dispose();
if (codeCount <= 0)
{
HOperatorSet.FindDataCode2d(ho_Image, out ho_SymbolXLDs, hv_DataCodeHandle,
new HTuple(), new HTuple(), out hv_ResultHandles, out hv_DecodedDataStrings);
}
else
{
HOperatorSet.FindDataCode2d(ho_Image, out ho_SymbolXLDs, hv_DataCodeHandle,
"stop_after_result_num", codeCount, out hv_ResultHandles, out hv_DecodedDataStrings);
}
HOperatorSet.AreaCenterXld(ho_SymbolXLDs, out hv_Area, out hv_Row1, out hv_Column, out hv_PointOrder);
if (HalconWindow != null)
{
ShowImage(HalconWindow, ho_Image, ho_SymbolXLDs);
}
HOperatorSet.ClearDataCode2dModel(hv_DataCodeHandle);
string[] resultList = hv_DecodedDataStrings.SArr;
if (resultList.Length > 0)
{
for (int i = 0; i < hv_DecodedDataStrings.SArr.Length; i++)
{
try
{
int x = (int)Math.Round(hv_Column.DArr[i]);
int y = (int)Math.Round(hv_Row1.DArr[i]);
string str = hv_DecodedDataStrings.SArr[i];
CodeInfo code = new CodeInfo(str, x, y);
codeList.Add(code);
}
catch (Exception ex)
{
HDLogUtil.error("处理二维码出错:索引=" + i + "," + resultList.ToString());
}
}
}
return codeList;
}
catch (Exception ex)
{
return codeList;
}
}
}
}
namespace CodeLibrary
{
partial class FrmBase
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// FrmBase
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Name = "FrmBase";
this.Text = "FrmBase";
this.VisibleChanged += new System.EventHandler(this.FrmBase_VisibleChanged);
this.ResumeLayout(false);
}
#endregion
}
}
\ No newline at end of file \ No newline at end of file
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CodeLibrary
{
public partial class FrmBase : Form
{
public string CurrLanguage = "";
public string ClassName
{
get
{
return this.GetType().Name;
}
set
{
}
}
public FrmBase()
{
InitializeComponent();
}
public void LanguageProcess()
{
if (CurrLanguage.Equals(CodeResourceControl.GetLanguage()))
{
return;
}
string className = this.ClassName;
CurrLanguage = CodeResourceControl.GetLanguage();
string name= CodeResourceControl.GetString(CodeResourceControl.GetTextIdStr(className), this.Text);
if (!name.Equals("")) { this.Text=name; }
foreach (Control con in this.Controls)
{
if (con is Label || con is Button || con is RadioButton || con is CheckBox)
{
string newStr = CodeResourceControl.GetString(CodeResourceControl.GetTextIdStr(className, con.Name), con.Text);
if (!newStr.Equals(""))
{
con.Text = newStr;
con.Tag = newStr;
}
if (CurrLanguage.Equals(CodeResourceControl.English))
{
con.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
}
else
{
con.Font = new System.Drawing.Font("微软雅黑", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
}
}
else if (con.Controls.Count > 0)
{
PreControlLanaguage(con);
}
}
}
private void PreControlLanaguage(Control partentControl)
{
string className = this.ClassName;
string newStr = CodeResourceControl.GetString(CodeResourceControl.GetTextIdStr(className, partentControl.Name), partentControl.Text);
if (!newStr.Equals(""))
{
partentControl.Text = newStr;
}
foreach (Control con in partentControl.Controls)
{
if (con is Label || con is Button || con is RadioButton || con is CheckBox)
{
newStr = CodeResourceControl.GetString(CodeResourceControl.GetTextIdStr(className, con.Name), con.Text);
if (!newStr.Equals(""))
{ con.Text = newStr; }
if (CurrLanguage.Equals(CodeResourceControl.English))
{
con.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
}
else
{
con.Font = new System.Drawing.Font("微软雅黑", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
}
}
else if (con.Controls.Count > 0)
{
PreControlLanaguage(con);
}
}
}
private void FrmBase_VisibleChanged(object sender, EventArgs e)
{
if (this.Visible.Equals(true))
{
LanguageProcess();
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
\ No newline at end of file \ No newline at end of file
using HalconDotNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CodeLibrary;
namespace CodeLibrary
{
public partial class FrmCodeLearn : FrmBase
{
private List<string> baslerNameList = new List<string>();
private List<string> hikNameList = new List<string>();
public FrmCodeLearn()
{
InitializeComponent();
}
private string selCamera =CodeResourceControl.GetString(CodeResourceControl.selCamera, "请先选择相机");
private string selImage = CodeResourceControl.GetString(CodeResourceControl.selImage, "请先选择图片");
private string title = CodeResourceControl.GetString(CodeResourceControl.title, "提示");
private string imageIsNull = CodeResourceControl.GetString(CodeResourceControl.imageIsNull, "获取二维码图片为空");
private string sureDelete = CodeResourceControl.GetString(CodeResourceControl.sureDelete, "确定删除文件:");
private Bitmap GetCameraBitmap()
{
Bitmap bitmap = null;
int index = cmbCamera.SelectedIndex;
string camerName = cmbCamera.Text;
if (index < 0)
{
MessageBox.Show(selCamera);
return null;
}
//if (baslerNameList.Contains(camerName))
//{
// BaslerCamera.Instance.Open(camerName);
// BaslerCamera.Instance.GrabOne();
// bitmap = BaslerCamera.Instance.Image;
// BaslerCamera.Instance.Close();
//}
//else
//{
// HIKCamera.Instance.Open(camerName);
// HIKCamera.Instance.GrabOne();
// bitmap = HIKCamera.Instance.Image;
// HIKCamera.Instance.Close();
//}
bitmap = Camera._cam.GrabOneImage(camerName);
return bitmap;
}
private void btnOpen_Click(object sender, EventArgs e)
{
string filePath = txtParamPath.Text;
string cameraName = "";
string codeType = this.cmbCodeType.Text;
int count = cmbCount.SelectedIndex + 1;
if (chbUseCamera.Checked)
{
if (chbHalcon.Checked)
{
cameraName = cmbHalconCamera.Text;
if (cameraName.Equals(""))
{
MessageBox.Show(selCamera,title, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
else
{
Bitmap bitmap = GetCameraBitmap();
if (bitmap != null)
{
HDLogUtil.info("从相机【" + cmbCamera.Text + "】获取到一张图片");
pictureBox1.Image = bitmap;
HObject hoImage = HDCodeHelper.Bitmap2HObjectBpp24(bitmap);
HDCodeLearnHelper.DefaultImage = hoImage;
}
else
{
return;
}
}
}
else
{
if (pictureBox1.Image == null)
{
MessageBox.Show(selImage,title ,MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
Bitmap bitmap = new Bitmap( pictureBox1.Image);
HObject Image = HDCodeHelper.Bitmap2HObjectBpp24(bitmap);
HDCodeLearnHelper.DefaultImage = Image;
}
Task.Factory.StartNew(delegate ()
{
HDCodeLearnHelper.StartLearn(this.hWindowControl1.HalconWindow, cameraName, codeType, filePath, count,5000);
});
FormStatus(true);
}
private void LoadCamera()
{
//string[] camerName = BaslerCamera.Instance.CameraName;
//baslerNameList.AddRange(camerName);
cmbCamera.Items.Clear();
foreach (string str in Camera._cam.Name)
{
cmbCamera.Items.Add(str);
}
//camerName = HIKCamera.Instance.CameraName;
//hikNameList.AddRange(camerName);
//foreach (string str in camerName)
//{
// cmbCamera.Items.Add(str);
//}
if (cmbCamera.Items.Count > 0)
{
cmbCamera.SelectedIndex = 0;
}
}
private void FormStatus(bool open)
{
btnOpen.Enabled = !open;
btnStop.Enabled = open;
}
private void btnStop_Click(object sender, EventArgs e)
{
HDCodeLearnHelper.StopLearn();
FormStatus(false);
}
private void FrmCamera_Load(object sender, EventArgs e)
{
cmbCount.SelectedIndex = 0;
chbTest.Checked = HDCodeLearnHelper.IsNeedTest;
CheckForIllegalCrossThreadCalls = false;
HDLogUtil.logBox = this.richTextBox2;
if (HDCodeLearnHelper.codeTypeList.Count <= 0)
{
HDCodeLearnHelper.LoadConfig("", "");
}
LoadCamera();
FormStatus(false);
cmbHalconCamera.DataSource = HDCodeLearnHelper.cameraNameList;
if (HDCodeLearnHelper.cameraNameList.Count > 0)
{
cmbHalconCamera.SelectedIndex = 0;
}
cmbCodeType.DataSource = HDCodeLearnHelper.codeTypeList;
if (HDCodeLearnHelper.codeTypeList.Count > 0)
{
cmbCodeType.SelectedIndex = 0;
}
string filePath =HDCodeHelper.GetCodeParamFilePath(cmbCodeType.Text);
txtParamPath.Text = filePath;
cmbCount.Items.Clear();
for(int i = 1; i <= 300; i++)
{
cmbCount.Items.Add(i);
}
cmbCount.SelectedIndex = 0;
chbUseCamera.Checked = true;
timer1.Start();
}
private void FrmCamera_FormClosed(object sender, FormClosedEventArgs e)
{
if (btnStop.Enabled.Equals(true))
{
btnStop_Click(null, null);
HDLogUtil.logBox = null;
FormStatus(false);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (HDCodeLearnHelper.IsRun)
{
if (btnOpen.Enabled)
{
btnOpen.Enabled = false ;
}
}
else
{
if (btnOpen.Enabled.Equals(false))
{
btnOpen.Enabled = true;
}
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void cmbCodeType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbCodeType.SelectedIndex >= 0)
{
txtParamPath.Text = HDCodeHelper.GetCodeParamFilePath(cmbCodeType.Text );
}
}
private void btnClearLog_Click(object sender, EventArgs e)
{
HDLogUtil.ClearLog();
}
private void chbTest_CheckedChanged(object sender, EventArgs e)
{
HDCodeLearnHelper.IsNeedTest = chbTest.Checked;
}
private void btnSelImage_Click(object sender, EventArgs e)
{
System.Windows.Forms.OpenFileDialog openDialog = new System.Windows.Forms.OpenFileDialog();
openDialog.Title = selImage;
openDialog.Filter = "(*.jpg;*.png;*.bmp)|*.jpg;*.png;*.bmp";
//openDialog.DefaultExt = "png";
System.Windows.Forms.DialogResult result = openDialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.Cancel)
{
return;
}
txtPath.Text = openDialog.FileName;
string filename = txtPath.Text;
if (string.IsNullOrEmpty(filename))
{
MessageBox.Show(imageIsNull);
}
pictureBox1.Image = null;
//读取图片内容
Image img = (Image)Image.FromFile(filename).Clone();
pictureBox1.Image = img;
}
private void chbUseCamera_CheckedChanged(object sender, EventArgs e)
{
if (chbUseCamera.Checked)
{
cmbHalconCamera.Enabled = true ;
btnSelImage.Enabled = false;
}
else
{
cmbHalconCamera.Enabled = false ;
btnSelImage.Enabled = true ;
}
}
private void btnDelOld_Click(object sender, EventArgs e)
{
string path = txtParamPath.Text;
if (path.Equals(""))
{
return;
}
FileInfo file = new FileInfo(path);
DialogResult result = MessageBox.Show(sureDelete +file.Name+ "", title, MessageBoxButtons.YesNo);
if (result.Equals(DialogResult.Yes))
{
File.Delete(path);
}
}
private void chbHalcon_CheckedChanged(object sender, EventArgs e)
{
if (chbHalcon.Checked)
{
cmbHalconCamera.Visible = true;
cmbCamera.Visible = false;
}
else
{
cmbHalconCamera.Visible = false ;
cmbCamera.Visible = true ;
}
}
}
}
using log4net;
using log4net.Config;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class HDLogUtil
{
private static string logName = "";
public static string LogName
{
get { return logName; }
set
{
logName = value;
LOGGER = LogManager.GetLogger(LogName);
}
}
private static ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static Dictionary<int, DateTime> lastErrorLogTime = new Dictionary<int, DateTime>();
public static System.Windows.Forms.RichTextBox logBox = null;
public static int showCount = 50;
public static bool debug_opened = false;
static HDLogUtil()
{
XmlConfigurator.Configure();
}
public static void info(string msg)
{
LOGGER.Info("HDLogUtil" + " - " + msg);
AddToBox(msg);
}
public static void debug(string msg)
{
LOGGER.Debug("HDLogUtil" + " - " + msg);
if (debug_opened)
{
AddToBox(msg);
}
}
public static void error(string errorMsg)
{
LOGGER.Error("HDLogUtil" + " - " + errorMsg);
AddToBox(errorMsg);
}
private static void AddToBox(string msg)
{
try
{
if (logBox == null)
{
return;
}
ShowLogPro(msg);
}
catch (Exception ex)
{
LOGGER.Error("出错:" + ex.StackTrace);
}
}
private static int count = 0;
private static void ShowLogPro(string msg)
{
try
{
if (count > showCount)
{
count = 0;
logBox.Clear();
}
System.DateTime now = System.DateTime.Now;
logBox.AppendText(now.ToLongTimeString() + " " + msg + Environment.NewLine);
count++;
}
catch (Exception ex)
{
LOGGER.Error("出错:" + ex.ToString());
}
}
public static void ClearLog()
{
if (logBox != null)
{
logBox.Text = "";
count = 0;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class ImageHelper
{ /// <summary>
/// 图像灰度化
/// </summary>
/// <param name="bmp"></param>
/// <returns></returns>
public static Bitmap ToGray(Bitmap bmp)
{
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
//获取该点的像素的RGB的颜色
Color color = bmp.GetPixel(i, j);
//利用公式计算灰度值
int gray = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11);
Color newColor = Color.FromArgb(gray, gray, gray);
bmp.SetPixel(i, j, newColor);
}
}
return bmp;
}
/// <summary>
/// 图像灰度反转
/// </summary>
/// <param name="bmp"></param>
/// <returns></returns>
public static Bitmap GrayReverse(Bitmap bmp)
{
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
//获取该点的像素的RGB的颜色
Color color = bmp.GetPixel(i, j);
Color newColor = Color.FromArgb(255 - color.R, 255 - color.G, 255 - color.B);
bmp.SetPixel(i, j, newColor);
}
}
return bmp;
}
/// <summary>
/// 图像二值化1:取图片的平均灰度作为阈值,低于该值的全都为0,高于该值的全都为255
/// </summary>
/// <param name="bmp"></param>
/// <returns></returns>
public static Bitmap ConvertTo1Bpp1(Bitmap bmp)
{
int average = 0;
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
Color color = bmp.GetPixel(i, j);
average += color.B;
}
}
average = (int)average / (bmp.Width * bmp.Height);
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
//获取该点的像素的RGB的颜色
Color color = bmp.GetPixel(i, j);
int value = 255 - color.B;
Color newColor = value > average ? Color.FromArgb(0, 0, 0) : Color.FromArgb(255, 255, 255);
bmp.SetPixel(i, j, newColor);
}
}
return bmp;
}
/// <summary>
/// 图像二值化2
/// </summary>
/// <param name="img"></param>
/// <returns></returns>
public static Bitmap ConvertTo1Bpp2(Bitmap img)
{
int w = img.Width;
int h = img.Height;
Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed);
BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);
for (int y = 0; y < h; y++)
{
byte[] scan = new byte[(w + 7) / 8];
for (int x = 0; x < w; x++)
{
Color c = img.GetPixel(x, y);
if (c.GetBrightness() >= 0.5) scan[x / 8] |= (byte)(0x80 >> (x % 8));
}
Marshal.Copy(scan, 0, (IntPtr)((int)data.Scan0 + data.Stride * y), scan.Length);
}
return bmp;
}
/// <summary>
/// 图像明暗调整
/// </summary>
/// <param name="b">原始图</param>
/// <param name="degree">亮度[-255, 255]</param>
/// <returns></returns>
public static Bitmap KiLighten(Bitmap b, int degree)
{
if (b == null)
{
return null;
}
if (degree < -255) degree = -255;
if (degree > 255) degree = 255;
try
{
int width = b.Width;
int height = b.Height;
int pix = 0;
BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
unsafe
{
byte* p = (byte*)data.Scan0;
int offset = data.Stride - width * 3;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// 处理指定位置像素的亮度
for (int i = 0; i < 3; i++)
{
pix = p[i] + degree;
if (degree < 0) p[i] = (byte)Math.Max(0, pix);
if (degree > 0) p[i] = (byte)Math.Min(255, pix);
} // i
p += 3;
} // x
p += offset;
} // y
}
b.UnlockBits(data);
return b;
}
catch
{
return null;
}
} // end of Lighten
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("CodeLibrary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CodeLibrary")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("2e0d9598-cb37-46dc-9c9b-d36d4d344451")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyVersion("1.0.0.0")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyFileVersion("1.0.*")]
\ No newline at end of file \ No newline at end of file
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZXing;
using ZXing.Common;
using ZXing.Multi.QrCode;
namespace CodeLibrary
{
public class ZXingCodeHelper
{
public static List<string> DeCodes(Bitmap map, string codeType)
{
if (codeType.ToUpper().Equals("QR CODE"))
{
return DecodeQRCodes(map);
}
else if (codeType.ToUpper().Equals("DATA MATRIX ECC 200"))
{
return DecodeCodes(map);
}
else if (codeType.ToUpper().Equals("BARCODE"))
{
return DecodeCodes(map);
}
else
{
return DecodeCodes(map);
}
}
public static List<string> DecodeCodes(Bitmap bmp)
{
MultiFormatReader mreader = new MultiFormatReader();
ZXing.Multi.GenericMultipleBarcodeReader genericMultiple = new ZXing.Multi.GenericMultipleBarcodeReader(mreader);
LuminanceSource source = new BitmapLuminanceSource(bmp);
BinaryBitmap binarybitmap = new BinaryBitmap(new HybridBinarizer(source));
Result[] rr = genericMultiple.decodeMultiple(binarybitmap);
List<string> result = new List<string>();
if (rr != null)
{
foreach (Result res in rr)
{
if (res != null)
{
string text = res.ToString();
if (!IsGBCode(text))
{
text = ConvertISO88591ToEncoding(text, Encoding.Default);
}
result.Add(text);
}
}
}
return result;
}
public static List<string> DecodeBarCodes(Bitmap bmp)
{
List<string> result = new List<string>();
BarcodeReader br = new BarcodeReader();
DecodingOptions decodeOption = new DecodingOptions();
decodeOption.PossibleFormats = new List<BarcodeFormat>() { BarcodeFormat.CODE_39, BarcodeFormat.CODE_128 };
br.Options = decodeOption;
Result res = br.Decode(bmp);
if (res != null)
{
result.Add(res.ToString());
}
return result;
}
public static List<string> DecodeDMCodes(Bitmap bmp)
{
ZXing.Datamatrix.DataMatrixReader qc = new ZXing.Datamatrix.DataMatrixReader();
List<string> result = new List<string>();
LuminanceSource source = new BitmapLuminanceSource(bmp);
BinaryBitmap binarybitmap = new BinaryBitmap(new HybridBinarizer(source));
IDictionary<DecodeHintType, object> hints = new Dictionary<DecodeHintType, object>();
hints.Add(DecodeHintType.CHARACTER_SET, "UTF-8");
hints.Add(DecodeHintType.TRY_HARDER, "3");
Result res = qc.decode(binarybitmap, hints);
if (res != null)
{
result.Add(res.ToString());
}
return result;
}
public static List<string> DecodeQRCodes(Bitmap bmp)
{
QRCodeMultiReader qc = new QRCodeMultiReader();
List<string> result = new List<string>();
LuminanceSource source = new BitmapLuminanceSource(bmp);
BinaryBitmap binarybitmap = new BinaryBitmap(new HybridBinarizer(source));
IDictionary<DecodeHintType, object> hints = new Dictionary<DecodeHintType, object>();
hints.Add(DecodeHintType.CHARACTER_SET, "GB2312");
hints.Add(DecodeHintType.TRY_HARDER, "3");
Result[] r = qc.decodeMultiple(binarybitmap, hints);
if (r != null)
{
foreach (Result res in r)
{
if (res != null)
{
string text = res.ToString();
//if (!IsGBCode(text))
//{
// string chStr = "生产日期(或厂家批次):";
// int index = text.IndexOf(chStr);
// if (index > 0)
// {
// string sub1 = text.Substring(0, index);
// int sub3startIndex =index+ chStr.Length;
// string sub3 = text.Substring(sub3startIndex,text.Length- sub3startIndex);
// string sub1r = ConvertISO88591ToEncoding(sub1, Encoding.Default);
// string sub3r = ConvertISO88591ToEncoding(sub3, Encoding.Default);
// text = sub1r + chStr + sub3r;
// }
// else
// {
// text = ConvertISO88591ToEncoding(text, Encoding.Default);
// }
//}
result.Add(text);
}
}
}
return result;
}
//public static string DecodeQRCode(Bitmap bmp)
//{
// string text = "";
// DecodingOptions option = new DecodingOptions();
// //option.PossibleFormats = new List<BarcodeFormat>() { BarcodeFormat.QR_CODE, BarcodeFormat.All_1D };
// option.PossibleFormats = new List<BarcodeFormat>() { BarcodeFormat.QR_CODE };
// BarcodeReader br = new BarcodeReader();
// br.Options = option;
// Result rs = br.Decode(bmp);
// if (rs == null)
// {
// text = "";
// }
// else
// {
// text = rs.ToString();
// if (!IsGBCode(text))
// {
// text = ConvertISO88591ToEncoding(text, Encoding.Default);
// }
// }
// return text;
//}
//转换
private static string ConvertISO88591ToEncoding(string srcString, Encoding dstEncode)
{
String sResult;
Encoding ISO88591Encoding = Encoding.GetEncoding("ISO-8859-1");
Encoding GB2312Encoding = Encoding.GetEncoding("GB2312"); //这个地方很特殊,必须利用GB2312编码
byte[] srcBytes = ISO88591Encoding.GetBytes(srcString);
//将原本存储ISO-8859-1的字节数组当成GB2312转换成目标编码(关键步骤)
byte[] dstBytes = Encoding.Convert(GB2312Encoding, dstEncode, srcBytes);
char[] dstChars = new char[dstEncode.GetCharCount(dstBytes, 0, dstBytes.Length)];
dstEncode.GetChars(dstBytes, 0, dstBytes.Length, dstChars, 0);//利用char数组存储字符
sResult = new string(dstChars);
return sResult;
}
/// <summary>
/// 判断一个word是否为GB2312编码的汉字
/// </summary>
/// <param name="word"></param>
/// <returns></returns>
private static bool IsGBCode(string word)
{
byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(word);
if (bytes.Length <= 1) // if there is only one byte, it is ASCII code or other code
{
return false;
}
else
{
byte byte1 = bytes[0];
byte byte2 = bytes[1];
if (byte1 >= 176 && byte1 <= 247 && byte2 >= 160 && byte2 <= 254) //判断是否是GB2312
{
return true;
}
else
{
return false;
}
}
}
}
}
using Basler.Pylon;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class BaslerCManager
{
/// <summary>
/// 当前相机
/// </summary>
// private Camera cameraCur = null;
private static Dictionary<string, BaslerCameraBean> cameraMap = new Dictionary<string, BaslerCameraBean>();
/// <summary>
/// 所有相机列表
/// </summary>
private static List<ICameraInfo> cameraAll;
/// <summary>
/// 所有相机的名称
/// </summary>
private static List<string> cameraName;
/// <summary>
/// 获取连续图像
/// </summary>
public delegate void GrabImageEvent();
///// <summary>
///// 获取连续图像事件,需要跨线程操作
///// </summary>
//public event GrabImageEvent GrabImage;
private BaslerCManager()
{
Load();
}
/// <summary>
/// 错误信息
/// </summary>
public static string ErrInfo { set; get; }
/// <summary>
/// 相机总数
/// </summary>
public int Count
{
get { return cameraAll == null ? 0 : cameraAll.Count; }
}
/// <summary>
/// 相机名称,ModelName,SerialNumber
/// </summary>
public static string[] CameraName
{
get
{
if (cameraName == null)
{
cameraName = new List<string>();
}
return cameraName.ToArray();
}
}
public static BaslerCameraBean GetCamera(string cName)
{
if (cameraMap.ContainsKey(cName))
{
return cameraMap[cName];
}
return null;
}
public static void AddCamera(string name, BaslerCameraBean bean)
{
if (cameraMap.ContainsKey(name))
{
cameraMap.Remove(name);
}
cameraMap.Add(name, bean);
}
/// <summary>
/// 当前相机是否打开
/// </summary>
public static bool IsOpen(string name)
{
BaslerCameraBean bean = GetCamera(name);
if (bean == null)
{ return false; }
else
{
return bean.cameraCur.IsOpen;
}
}
/// <summary>
/// 加载相机
/// </summary>
public static void Load()
{
try
{
cameraAll = CameraFinder.Enumerate();
cameraName = new List<string>();
foreach (ICameraInfo info in cameraAll)
cameraName.Add(info[CameraInfoKey.ModelName].ToString() + " (" + info[CameraInfoKey.SerialNumber].ToString() + ")");
}
catch (Exception ex)
{
HDLogUtil.error("Basler Load Error:" + ex.StackTrace);
}
}
/// <summary>
/// 打开指定相机
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static bool Open(string name, GrabImageEvent grab=null)
{
int n = cameraName.FindIndex(s => s == name);
if (n == -1)
return false;
else
{
if (cameraMap.ContainsKey(name))
{
if (cameraMap[name].cameraCur != null)
{
cameraMap[name].cameraCur.Close();
}
cameraMap.Remove(name);
}
Camera cameraCur = null;
if (n < 0 || n >= cameraAll.Count) { return false ; }
try
{
cameraCur = new Camera(cameraAll[n]);
BaslerCameraBean bean = new BaslerCameraBean(cameraCur);
bean.Open( );
AddCamera(name, bean);
}
catch (Exception ex)
{
ErrInfo = ex.Message;
return false ;
}
return true;
}
}
/// <summary>
/// 关闭当前相机
/// </summary>
public static void Close(string name)
{
BaslerCameraBean bean = GetCamera(name);
if (bean != null && bean.cameraCur != null)
{
bean.Close();
}
}
public static void CloseAll()
{
foreach(string key in cameraMap.Keys)
{
Close(key);
}
}
/// <summary>
/// 停止抓取数据
/// </summary>
public static void Stop(string name)
{
BaslerCameraBean bean = GetCamera(name);
if (bean != null)
{
bean.Stop();
}
}
/// <summary>
/// 抓取一张图像
/// </summary>
public static Bitmap GrabOne(string name)
{
BaslerCameraBean bean = GetCamera(name);
if (bean != null && bean.cameraCur != null)
{
return bean.GrabOne();
}
return null;
}
}
}
using Basler.Pylon;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static CodeLibrary.BaslerCamera;
namespace CodeLibrary
{
public class BaslerCameraBean
{
public Camera cameraCur = null;
/// <summary>
/// 相机图像宽度
/// </summary>
public int Width { set; get; }
/// <summary>
/// 相机图像高度
/// </summary>
public int Height { set; get; }
/// <summary>
/// 相机32位缓存
/// </summary>
public byte[] Buffer { get; private set; }
/// <summary>
/// 相机32位图像
/// </summary>
public Bitmap Image { get; private set; }
/// <summary>
/// 获取连续图像事件,需要跨线程操作
/// </summary>
public event GrabImageEvent GrabImage;
/// <summary>
/// 错误信息
/// </summary>
public string ErrInfo { set; get; }
public BaslerCameraBean (Camera c)
{
this.cameraCur = c;
}
public BaslerCameraBean (Camera c ,int width,int height)
{
this.cameraCur = c;
this.Width = width;
this.Height = height;
}
public void Open()
{
cameraCur.StreamGrabber.ImageGrabbed += OnImageGrabbed;
//cameraCur.StreamGrabber.GrabStopped += OnGrabStopped;
cameraCur.Open();
int Width = Convert.ToInt32(cameraCur.Parameters[PLCamera.Width].GetValue());
int Height = Convert.ToInt32(cameraCur.Parameters[PLCamera.Height].GetValue());
cameraCur.Parameters[PLCamera.UserSetSelector].SetValue(PLCamera.UserSetSelector.UserSet1); //加载用户设置1
bool bln = cameraCur.Parameters[PLCamera.UserSetLoad].TryExecute(); //执行设置
}
/// <summary>
/// 关闭当前相机
/// </summary>
public void Close()
{
if (cameraCur != null)
{
cameraCur.Close();
cameraCur.Dispose();
cameraCur = null;
}
}
/// <summary>
/// 停止抓取数据
/// </summary>
public void Stop()
{
if (cameraCur != null)
cameraCur.StreamGrabber.Stop();
}
/// <summary>
/// 抓取一张图像
/// </summary>
public Bitmap GrabOne()
{
cameraCur.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.SingleFrame);
//cameraCur.StreamGrabber.Start();
//IGrabResult grabResult = cameraCur.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
IGrabResult grabResult = cameraCur.StreamGrabber.GrabOne(5000);
if (!grabResult.IsValid) return null ;
Image = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
BitmapData bmpData = Image.LockBits(new Rectangle(0, 0, grabResult.Width, grabResult.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
IntPtr ptrBmp = bmpData.Scan0;
int picSize = bmpData.Stride * grabResult.Height;
PixelDataConverter conv = new PixelDataConverter();
conv.OutputPixelFormat = PixelType.BGRA8packed;
conv.Convert(ptrBmp, picSize, grabResult);
Buffer = new byte[picSize];
System.Runtime.InteropServices.Marshal.Copy(ptrBmp, Buffer, 0, picSize);
Image.UnlockBits(bmpData);
return Image;
//cameraCur.StreamGrabber.Stop();
}
/// <summary>
/// 抓取连续图像,触发GrabImage事件
/// </summary>
public void GrabContinuous()
{
cameraCur.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
cameraCur.StreamGrabber.Start(GrabStrategy.OneByOne, GrabLoop.ProvidedByStreamGrabber);
}
private void OnImageGrabbed(object sender, ImageGrabbedEventArgs e)
{
try
{
IGrabResult grabResult = e.GrabResult;
if (!grabResult.IsValid) return;
Image = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
BitmapData bmpData = Image.LockBits(new Rectangle(0, 0, grabResult.Width, grabResult.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
IntPtr ptrBmp = bmpData.Scan0;
int picSize = bmpData.Stride * grabResult.Height;
PixelDataConverter conv = new PixelDataConverter();
conv.OutputPixelFormat = PixelType.BGRA8packed;
conv.Convert(ptrBmp, picSize, grabResult);
Buffer = new byte[picSize];
System.Runtime.InteropServices.Marshal.Copy(ptrBmp, Buffer, 0, picSize);
Image.UnlockBits(bmpData);
GrabImage?.Invoke();
}
catch (Exception ex)
{
ErrInfo = ex.Message;
}
finally
{
e.DisposeGrabResultIfClone();
}
}
}
}
using System;
using Basler.Pylon;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;
namespace CodeLibrary
{
partial class Basler : ClsCamera
{
/// <summary>
/// 当前相机
/// </summary>
private global::Basler.Pylon.Camera[] cameraCurr;
/// <summary>
/// 所有相机列表
/// </summary>
private List<ICameraInfo> cameraAll;
///// <summary>
///// 所有相机的名称
///// </summary>
//private List<string> cameraName;
///// <summary>
///// 连续抓图事件
///// </summary>
//public event Continuous Continuous_Event;
public override void Close(string name)
{
int index = Array.FindIndex(_name, s => s == name);
if (index == -1)
return;
if (cameraCurr[index] != null)
{
_isOpen[index] = false;
cameraCurr[index].Close();
cameraCurr[index].Dispose();
cameraCurr[index] = null;
}
}
public override void Close(int index)
{
if (cameraCurr[index] != null)
{
_isOpen[index] = false;
cameraCurr[index].Close();
cameraCurr[index].Dispose();
cameraCurr[index] = null;
}
}
public override void CloseAll()
{
for (int i = 0; i < cameraCurr.Length; i++)
{
if (cameraCurr[i] != null)
{
_isOpen[i] = false;
cameraCurr[i].Close();
cameraCurr[i].Dispose();
cameraCurr[i] = null;
}
}
}
public override Bitmap GrabOne(int index)
{
if (cameraCurr[index] != null)
{
try
{
cameraCurr[index].Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.SingleFrame);
//cameraCur.StreamGrabber.Start();
//IGrabResult grabResult = cameraCur.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
IGrabResult grabResult = cameraCurr[index].StreamGrabber.GrabOne(5000);
if (!grabResult.IsValid)
{
_errInfo = grabResult.ErrorDescription;
return null;
}
Bitmap _image = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format24bppRgb);
BitmapData bmpData = _image.LockBits(new Rectangle(0, 0, grabResult.Width, grabResult.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
IntPtr ptrBmp = bmpData.Scan0;
int picSize = bmpData.Stride * grabResult.Height;
PixelDataConverter conv = new PixelDataConverter();
conv.OutputPixelFormat = PixelType.BGR8packed;
conv.Convert(ptrBmp, picSize, grabResult);
//_buffer = new byte[picSize];
//System.Runtime.InteropServices.Marshal.Copy(ptrBmp, _buffer, 0, picSize);
_image.UnlockBits(bmpData);
_errInfo = "OK";
return _image;
}
catch (Exception ex)
{
_errInfo = ex.Message;
return null;
}
}
return null;
}
public override Bitmap GrabOne(string name)
{
int idx = Array.FindIndex(_name, s => s == name);
if (idx == -1)
return null;
else
return GrabOne(idx);
}
//public override void GrabStop(int index)
//{
// if (cameraCurr[index] != null)
// cameraCurr[index].StreamGrabber.Stop();
//}
public override bool Load()
{
try
{
cameraAll = CameraFinder.Enumerate();
cameraName = new List<string>();
foreach (ICameraInfo info in cameraAll)
cameraName.Add(info[CameraInfoKey.ModelName].ToString() + " (" + info[CameraInfoKey.SerialNumber].ToString() + ")");
_name = cameraName.ToArray();
_count = cameraName.Count;
_isOpen = new bool[_count];
_width = new int[_count];
_height = new int[_count];
cameraCurr = new global::Basler.Pylon.Camera[_count];
_errInfo = "OK";
return true;
}
catch (Exception ex)
{
_errInfo = ex.Message;
return false;
}
}
public override bool Open(int index)
{
// _index = index;
if (index < 0 || index >= _count)
{
_errInfo = "Not find";
return false;
}
if (cameraCurr[index] != null) Close(index);
try
{
cameraCurr[index] = new global::Basler.Pylon.Camera(cameraAll[index]);
//cameraCur.ConnectionLost += OnConnectionLost;
//cameraCur.CameraOpened += OnCameraOpened;
//cameraCur.CameraClosed += OnCameraClosed;
//cameraCur.StreamGrabber.GrabStarted += OnGrabStarted;
// cameraCurr[index].StreamGrabber.ImageGrabbed += OnImageGrabbed;
//cameraCur.StreamGrabber.GrabStopped += OnGrabStopped;
cameraCurr[index].Open();
_width[index] = Convert.ToInt32(cameraCurr[index].Parameters[PLCamera.Width].GetValue());
_height[index] = Convert.ToInt32(cameraCurr[index].Parameters[PLCamera.Height].GetValue());
cameraCurr[index].Parameters[PLCamera.UserSetSelector].SetValue(PLCamera.UserSetSelector.UserSet1); //加载用户设置1
bool bln = cameraCurr[index].Parameters[PLCamera.UserSetLoad].TryExecute(); //执行设置
_isOpen[index] = true;
_errInfo = "OK";
return true;
}
catch (Exception ex)
{
_errInfo = ex.Message;
return false;
}
}
public override bool Open(string name)
{
int n = cameraName.FindIndex(s => s == name);
if (n == -1)
{
_errInfo = "Not find";
return false;
}
else
return Open(n);
}
public override bool OpenAll()
{
bool rtn = true;
for (int i = 0; i < cameraName.Count; i++)
{
rtn = Open(i);
if (!rtn) break;
}
return rtn;
}
public override Bitmap GrabOneImage(string name)
{
int n = cameraName.FindIndex(s => s == name);
if (n == -1)
{
_errInfo = "Not find";
return null;
}
if (cameraCurr[n] != null)
{
return GrabOne(name);
}
return null;
}
}
}
\ No newline at end of file \ No newline at end of file
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace CodeLibrary
{
/// <summary>
/// 相机
/// </summary>
public class Camera
{
public static ClsCamera _cam;
private static CameraType _type;
/// <summary>
/// 相机
/// </summary>
private Camera()
{ }
/// <summary>
/// 相机类型
/// </summary>
public static CameraType Type
{
set
{
if (_cam != null)
{
return;
// _cam.CloseAll();
}
_type = value;
switch (_type)
{
case CameraType.HIK:
_cam = new HIK();
// ((HIK)_cam).Continuous_Event += Camera_Continuous_Event;
break;
case CameraType.Basler:
_cam = new Basler();
// ((Basler)_cam).Continuous_Event += Camera_Continuous_Event;
break;
}
}
get
{
return _type;
}
}
}
/// <summary>
/// 相机类型
/// </summary>
public enum CameraType
{
/// <summary>
/// 海康
/// </summary>
HIK,
/// <summary>
/// Basle
/// </summary>
Basler
}
public abstract class ClsCamera
{
/// <summary>
/// 所有相机的名称
/// </summary>
protected List<string> cameraName;
protected string _errInfo;
protected bool[] _isOpen;
protected int _count;
protected string[] _name;
protected int[] _width;
protected int[] _height;
//protected byte[] _buffer;
// protected Bitmap _image;
// protected int _index;
public delegate void Continuous();
public virtual string ErrInfo => _errInfo;
public virtual bool[] IsOpen => _isOpen;
public virtual int Count => _count;
public virtual string[] Name => _name;
//public virtual int[] Width => _width;
//public virtual int[] Height => _height;
//public virtual byte[] Buffer => _buffer;
// public virtual Bitmap Image => _image;
public abstract bool Load();
public abstract bool OpenAll();
public abstract bool Open(int index);
public abstract bool Open(string name);
public abstract void CloseAll();
public abstract void Close(int index);
public abstract void Close(string name);
// public abstract bool GrabOne();
public abstract Bitmap GrabOne(int index);
public abstract Bitmap GrabOne(string name);
// public abstract bool GrabContinuous(int index);
// public abstract void GrabStop(int index);
public abstract Bitmap GrabOneImage(string name);
}
}
using MvCamCtrl.NET;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class HIKCManager
{ /// <summary>
/// 当前相机
/// </summary>
// private Camera cameraCur = null;
private static Dictionary<string, HIKCameraBean> cameraMap = new Dictionary<string, HIKCameraBean>();
/// <summary>
/// 当前相机
/// </summary>
// private MyCamera cameraCurr;
/// <summary>
/// 所有相机列表
/// </summary>
private static MyCamera.MV_CC_DEVICE_INFO_LIST cameraAll;
/// <summary>
/// 所有相机的名称
/// </summary>
private static List<string> cameraName = new List<string>();
/// <summary>
/// 海康相机
/// </summary>
public HIKCManager()
{
cameraAll = new MyCamera.MV_CC_DEVICE_INFO_LIST();
Load();
}
public static HIKCameraBean GetCamera(string cName)
{
if (cameraMap.ContainsKey(cName))
{
return cameraMap[cName];
}
return null;
}
public static void AddCamera(string name, HIKCameraBean bean)
{
if (cameraMap.ContainsKey(name))
{
cameraMap.Remove(name);
}
cameraMap.Add(name, bean);
}
/// <summary>
/// 错误信息
/// </summary>
public static string ErrInfo { set; get; }
/// <summary>
/// 相机总数
/// </summary>
public static int Count
{
get { return (int)cameraAll.nDeviceNum; }
}
/// <summary>
/// 相机名称,ModelName,SerialNumber
/// </summary>
public static string[] CameraName
{
get
{
if (cameraName == null)
{
cameraName = new List<string>();
}
return cameraName.ToArray();
}
}
/// <summary>
/// 当前相机是否打开
/// </summary>
public static bool IsOpen(string cName)
{
HIKCameraBean bean = GetCamera(cName);
if (bean == null || bean.cameraCur == null)
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 加载相机
/// </summary>
public static void Load()
{
try
{
int rtn = MyCamera.MV_CC_EnumDevices_NET(MyCamera.MV_GIGE_DEVICE | MyCamera.MV_USB_DEVICE, ref cameraAll);
if (rtn != MyCamera.MV_OK) return;
cameraName.Clear();
string s = "";
for (int i = 0; i < cameraAll.nDeviceNum; i++)
{
MyCamera.MV_CC_DEVICE_INFO device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(cameraAll.pDeviceInfo[i], typeof(MyCamera.MV_CC_DEVICE_INFO));
if (device.nTLayerType == MyCamera.MV_GIGE_DEVICE)
{
IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(device.SpecialInfo.stGigEInfo, 0);
MyCamera.MV_GIGE_DEVICE_INFO gigeInfo = (MyCamera.MV_GIGE_DEVICE_INFO)Marshal.PtrToStructure(buffer, typeof(MyCamera.MV_GIGE_DEVICE_INFO));
s = "GigE:" + gigeInfo.chModelName + " (" + gigeInfo.chSerialNumber + ")";
}
else if (device.nTLayerType == MyCamera.MV_USB_DEVICE)
{
IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(device.SpecialInfo.stUsb3VInfo, 0);
MyCamera.MV_USB3_DEVICE_INFO usbInfo = (MyCamera.MV_USB3_DEVICE_INFO)Marshal.PtrToStructure(buffer, typeof(MyCamera.MV_USB3_DEVICE_INFO));
s = "USB:" + usbInfo.chModelName + " (" + usbInfo.chSerialNumber + ")";
}
cameraName.Add(s);
}
}
catch (Exception ex)
{
HDLogUtil.error("HIK Load Error:" + ex.StackTrace);
}
}
/// <summary>
/// 打开指定相机
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static bool Open(string name)
{
int n = cameraName.FindIndex(s => s == name);
if (n == -1)
return false;
else
{
if (cameraMap.ContainsKey(name))
{
if (cameraMap[name].cameraCur != null)
{
cameraMap[name].Close();
}
cameraMap.Remove(name);
}
if (n < 0 || n >= cameraAll.pDeviceInfo.Length) { return false; }
try
{
MyCamera.MV_CC_DEVICE_INFO device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(cameraAll.pDeviceInfo[n], typeof(MyCamera.MV_CC_DEVICE_INFO));
MyCamera cameraCur = new MyCamera();
HIKCameraBean bean = new HIKCameraBean(cameraCur);
bean.Open(device);
AddCamera(name, bean);
}
catch (Exception ex)
{
ErrInfo = ex.Message;
return false;
}
return true;
}
}
/// <summary>
/// 关闭当前相机
/// </summary>
public static void Close(string cName)
{
HIKCameraBean bean = GetCamera(cName);
if (bean != null && bean.cameraCur != null)
{
bean.cameraCur.MV_CC_CloseDevice_NET();
bean.cameraCur.MV_CC_DestroyDevice_NET();
bean.cameraCur = null;
}
}
public static void CloseAll()
{
foreach (string key in cameraMap.Keys)
{
Close(key);
}
}
/// <summary>
/// 停止抓取数据
/// </summary>
public static void Stop(string cName)
{
HIKCameraBean bean = GetCamera(cName);
if (bean == null || bean.cameraCur != null)
{ return; }
if (bean.cameraCur == null) return;
int rtn = bean.cameraCur.MV_CC_StopGrabbing_NET();
if (rtn != MyCamera.MV_OK) return;
}
/// <summary>
/// 抓取一张图像
/// </summary>
public static Bitmap GrabOne(string cName)
{
HIKCameraBean bean = GetCamera(cName);
if (bean == null || bean.cameraCur != null)
{ return null; }
return bean.GrabOne();
}
/// <summary>
/// 抓取连续图像,触发GrabImage事件
/// </summary>
/// <param name="hWnd"></param>
public static void GrabContinuous(string cName, IntPtr hWnd)
{
HIKCameraBean bean = GetCamera(cName);
if (bean == null || bean.cameraCur != null)
{ return ; }
int rtn = bean.cameraCur.MV_CC_StartGrabbing_NET();
if (rtn != MyCamera.MV_OK) return;
rtn = bean.cameraCur.MV_CC_Display_NET(hWnd);
if (rtn != MyCamera.MV_OK) return;
}
}
}
using MvCamCtrl.NET;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class HIKCameraBean
{
/// <summary>
/// 当前相机
/// </summary>
public MyCamera cameraCur;
/// <summary>
/// 海康相机
/// </summary>
internal HIKCameraBean(MyCamera cameraCur)
{
this.cameraCur = cameraCur;
}
/// <summary>
/// 错误信息
/// </summary>
public string ErrInfo { set; get; }
/// <summary>
/// 当前相机是否打开
/// </summary>
public bool IsOpen
{
get
{
if (cameraCur == null)
return false;
else
return true;
}
}
/// <summary>
/// 相机图像宽度
/// </summary>
public int Width { set; get; }
/// <summary>
/// 相机图像高度
/// </summary>
public int Height { set; get; }
/// <summary>
/// 相机32位缓存
/// </summary>
public byte[] Buffer { get; private set; }
/// <summary>
/// 相机32位图像
/// </summary>
public Bitmap Image { get; private set; }
/// <summary>
/// 打开指定相机
/// </summary>
/// <param name="idx">索引</param>
/// <returns></returns>
public bool Open(MyCamera.MV_CC_DEVICE_INFO device)
{
if (cameraCur == null) return false;
int nRet = cameraCur.MV_CC_CreateDevice_NET(ref device);
if (nRet != MyCamera.MV_OK) return false;
nRet = cameraCur.MV_CC_OpenDevice_NET();
if (nRet != MyCamera.MV_OK)
{
cameraCur.MV_CC_DestroyDevice_NET();
return false;
}
if (device.nTLayerType == MyCamera.MV_GIGE_DEVICE)
{
int nPacketSize = cameraCur.MV_CC_GetOptimalPacketSize_NET();
if (nPacketSize > 0) nRet = cameraCur.MV_CC_SetIntValue_NET("GevSCPSPacketSize", (uint)nPacketSize);
}
cameraCur.MV_CC_SetEnumValue_NET("AcquisitionMode", 2); //工作在连续模式
cameraCur.MV_CC_SetEnumValue_NET("TriggerMode", 0); //连续模式
MyCamera.MVCC_INTVALUE pstValue = new MyCamera.MVCC_INTVALUE();
nRet = cameraCur.MV_CC_GetWidth_NET(ref pstValue);
Width = (int)pstValue.nCurValue;
nRet = cameraCur.MV_CC_GetHeight_NET(ref pstValue);
Height = (int)pstValue.nCurValue;
return true;
}
/// <summary>
/// 关闭当前相机
/// </summary>
public void Close()
{
if (cameraCur != null)
{
cameraCur.MV_CC_CloseDevice_NET();
cameraCur.MV_CC_DestroyDevice_NET();
cameraCur = null;
}
}
/// <summary>
/// 停止抓取数据
/// </summary>
public void Stop()
{
if (cameraCur == null) return;
int rtn = cameraCur.MV_CC_StopGrabbing_NET();
if (rtn != MyCamera.MV_OK) return;
}
/// <summary>
/// 抓取一张图像
/// </summary>
public Bitmap GrabOne()
{
int rtn = cameraCur.MV_CC_StartGrabbing_NET();
if (rtn != MyCamera.MV_OK) return null;
MyCamera.MVCC_INTVALUE stParam = new MyCamera.MVCC_INTVALUE();
rtn = cameraCur.MV_CC_GetIntValue_NET("PayloadSize", ref stParam);
if (rtn != MyCamera.MV_OK) return null;
uint dataSize = stParam.nCurValue;
byte[] dataArr = new byte[dataSize];
uint buffSize = dataSize * 3 + 2048;
byte[] buffArr = new byte[buffSize];
IntPtr pData = Marshal.UnsafeAddrOfPinnedArrayElement(dataArr, 0);
MyCamera.MV_FRAME_OUT_INFO_EX stFrameInfo = new MyCamera.MV_FRAME_OUT_INFO_EX();
rtn = cameraCur.MV_CC_GetOneFrameTimeout_NET(pData, dataSize, ref stFrameInfo, 100000);
if (rtn != MyCamera.MV_OK) return null;
MyCamera.MvGvspPixelType enDstPixelType = stFrameInfo.enPixelType;
switch (stFrameInfo.enPixelType)
{
case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono8:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono10:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono10_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono12:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono12_Packed:
enDstPixelType = stFrameInfo.enPixelType; break;
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR8:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG8:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB8:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG8:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR10:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG10:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB10:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG10:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR12:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG12:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB12:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG12:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR10_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG10_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB10_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG10_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR12_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG12_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB12_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG12_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_RGB8_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_YUV422_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_YUV422_YUYV_Packed:
case MyCamera.MvGvspPixelType.PixelType_Gvsp_YCBCR411_8_CBYYCRYY:
enDstPixelType = MyCamera.MvGvspPixelType.PixelType_Gvsp_RGB8_Packed; break;
}
IntPtr pImage = Marshal.UnsafeAddrOfPinnedArrayElement(buffArr, 0);
MyCamera.MV_PIXEL_CONVERT_PARAM stConverPixelParam = new MyCamera.MV_PIXEL_CONVERT_PARAM();
stConverPixelParam.nWidth = stFrameInfo.nWidth;
stConverPixelParam.nHeight = stFrameInfo.nHeight;
stConverPixelParam.pSrcData = pData;
stConverPixelParam.nSrcDataLen = stFrameInfo.nFrameLen;
stConverPixelParam.enSrcPixelType = stFrameInfo.enPixelType;
stConverPixelParam.enDstPixelType = enDstPixelType;
stConverPixelParam.pDstBuffer = pImage;
stConverPixelParam.nDstBufferSize = buffSize;
rtn = cameraCur.MV_CC_ConvertPixelType_NET(ref stConverPixelParam);
if (rtn != MyCamera.MV_OK) return null;
if (enDstPixelType == MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono8)
{
Image = new Bitmap(stFrameInfo.nWidth, stFrameInfo.nHeight, stFrameInfo.nWidth * 1, PixelFormat.Format8bppIndexed, pImage);
ColorPalette cp = Image.Palette;
for (int i = 0; i < 256; i++)
cp.Entries[i] = Color.FromArgb(i, i, i);
Image.Palette = cp;
int picSize = Image.Width * Image.Height;
Buffer = new byte[picSize];
Array.Copy(buffArr, Buffer, picSize);
//Rectangle rect = new Rectangle(0, 0, Image.Width, Image.Height);
//BitmapData bmpData = Image.LockBits(rect, ImageLockMode.ReadWrite, Image.PixelFormat);
//IntPtr iPtr = bmpData.Scan0;
//int picSize = Image.Width * Image.Height;
//Buffer = new byte[picSize];
//Marshal.Copy(iPtr, Buffer, 0, picSize);
//Image.UnlockBits(bmpData);
}
else
{
for (int i = 0; i < stFrameInfo.nHeight; i++)
{
for (int j = 0; j < stFrameInfo.nWidth; j++)
{
byte chRed = buffArr[i * stFrameInfo.nWidth * 3 + j * 3];
buffArr[i * stFrameInfo.nWidth * 3 + j * 3] = buffArr[i * stFrameInfo.nWidth * 3 + j * 3 + 2];
buffArr[i * stFrameInfo.nWidth * 3 + j * 3 + 2] = chRed;
}
}
Image = new Bitmap(stFrameInfo.nWidth, stFrameInfo.nHeight, stFrameInfo.nWidth * 3, PixelFormat.Format24bppRgb, pImage);
int picSize = Image.Width * Image.Height * 3;
Buffer = new byte[picSize];
Array.Copy(buffArr, Buffer, picSize);
return Image;
}
rtn = cameraCur.MV_CC_StopGrabbing_NET();
if (rtn != MyCamera.MV_OK)
{
}
return null;
}
/// <summary>
/// 抓取连续图像,触发GrabImage事件
/// </summary>
/// <param name="hWnd"></param>
public void GrabContinuous(IntPtr hWnd)
{
int rtn = cameraCur.MV_CC_StartGrabbing_NET();
if (rtn != MyCamera.MV_OK) return;
rtn = cameraCur.MV_CC_Display_NET(hWnd);
if (rtn != MyCamera.MV_OK) return;
}
}
}
FrmCodeDecode_Text,二维码识别,Qr code recognition
FrmCodeDecode_label4_Text,参数路径,Parameters of the path
FrmCodeDecode_chbUseParam_Text,使用参数,operation parameter
FrmCodeDecode_btnAn_Text,变暗,darken
FrmCodeDecode_btnLight_Text,提亮,brighten
FrmCodeDecode_btnCopyN_Text,复制名称,Copy Name
FrmCodeDecode_label3_Text,条码类型:,Bar code type:
FrmCodeDecode_label2_Text,相机列表:,Camera list:
FrmCodeDecode_btnExit_Text,退出,Exit
FrmCodeDecode_btnCameraImage_Text,相机获取图片,camera image
FrmCodeDecode_lblCount_Text,条码数量:,Barcode number:
FrmCodeDecode_btnClearLog_Text,清理日志,Clear log
FrmCodeDecode_btnDCode_Text,二维码识别,Qr code recognition
FrmCodeDecode_btnLearn_Text,学习,learn
FrmCodeDecode_btnbarCode_Text,一维码识别,One dimensional code recognition
FrmCodeDecode_btnGray_Text,图像转灰,Turning grey
FrmCodeDecode_btnErZhi_Text,二值化,binaryzation 
FrmCodeDecode_btnSelImage_Text,打开本地图片,Open local image
FrmCodeDecode_label1_Text,图片路径,Image path
FrmCodeLearn_Text,条码参数学习,Bar code parameter learning
FrmCodeLearn_chbHalcon_Text,Halcon获取图片,Halcon Get photo
FrmCodeLearn_label4_Text,图片路径,Image path
FrmCodeLearn_btnDelOld_Text,删除旧参数,Delete old parameter
FrmCodeLearn_chbUseCamera_Text,相机获取实时图片,camera image
FrmCodeLearn_btnSelImage_Text,打开本地图片,Open local image
FrmCodeLearn_chbTest_Text,学习结束自动识别测试,Automatic identification test
FrmCodeLearn_btnClearLog_Text,清理日志,Clear log
FrmCodeLearn_lblCount_Text,条码数量:,Barcode number:
FrmCodeLearn_label3_Text,参数路径,Parameters of the path
FrmCodeLearn_label2_Text,类型:,Type:
FrmCodeLearn_label1_Text,相机:,camera:
FrmCodeLearn_btnExit_Text,退出,Exit
FrmCodeLearn_btnStop_Text,结束学习,End of learning
FrmCodeLearn_btnOpen_Text,开始学习,start to learn
selCamera,请先选择相机,Please select camera
selImage,请先选择图片,Please select picture
title,提示,Notice
imageIsNull,获取二维码图片为空,Get the two-dimensional code picture is empty
sureDelete,确定删除文件:,Make sure to delete the file:
\ No newline at end of file \ No newline at end of file
20181123
增加相机本身获取图片的代码,后续扫码都直接从相机中获取图片,然后扫码
20190731
RC29西安三台料仓的二维码使用halcon无法识别,增加zxing的识别方式。
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!