因為公司業務需求,需要在Windows系統下調用攝像頭識别二維碼需求,就有了這個功能。
我根據網上網友提供的一些資料,自己整合應用到項目中,效果還不錯(就是感覺像素不是太好)
現在将調用攝像頭+識别二維碼這兩個功能單獨出來寫到這裡,供大家讨論和參考。
有什麼不足或者問題大家可以提出來,共同改進共同進步
建立一個空的winform項目解決方案,我起名叫他:ScanQRCode
将Form1作為主窗體,設定相關屬性:
StartPosition:CenterScreen (窗體居中)
添加一個居中标題:
private void LoadTitleCenterData()
{
string titleMsg ="二維碼識别主界面";
Graphics g = this.CreateGraphics();
Double startingPoint = (this.Width / 2) - (g.MeasureString(titleMsg, this.Font).Width / 2);
Double widthOfASpace = g.MeasureString(" ", this.Font).Width;
String tmp = " ";
Double tmpWidth = 0;
while ((tmpWidth + widthOfASpace) < startingPoint)
{
tmp += " ";
tmpWidth += widthOfASpace;
}
this.Text = tmp + titleMsg;
}
最大最小化禁用:
public Form1()
{
this.MinimizeBox = false;
this.MaximizeBox = false;
InitializeComponent();
LoadTitleCenterData();
}
Form1中添加一個TableLayoutPanel,三行三列,比例按照百分比:10%,80%,10%這樣
在TableLayoutPanel的80%中再添加一個TableLayoutPanel,還是行比例:20%,80%這樣(二八定律)
在TableLayoutPanel中添加Panel,在其中手動在添加幾個按鈕和label
最終界面這樣(能看就行):
添加一個二維碼識别界面CameraQR:
使用Nuget添加引用,搜尋AForge,将如下程式包引入:
添加一個識别二維碼的窗體,命名名稱為:CameraQR
将VideoSourcePlayer添加到窗體中,Fill顯示:
窗體中定義幾個私有變量:
1
2
3
private AForge.Video.DirectShow.FilterInfoCollection _videoDevices;//攝像裝置
System.Timers.Timer timer;//定時器
CameraHelper _cameraHelper = new CameraHelper();//視屏裝置操作類
窗體Load事件中擷取拍照裝置清單,并将第一個裝置作為攝像裝置(如有前後兩個或多個攝像頭,自己去改一下代碼,設定成可以選擇的,在CameraHelper中的CreateFilterInfoCollection()中):
private void CameraQR_Load(object sender, EventArgs e)
{
// 擷取視訊輸入裝置
_videoDevices = _cameraHelper.CreateFilterInfoCollection();//擷取拍照裝置清單
if (_videoDevices.Count == 0)
{
MessageBox.Show("無裝置");
this.Dispose();
this.Close();
return;
}
resultStr = "";//二維碼識别字元串清空
_cameraHelper.ConnectDevice(videoSourcePlayer1);//連接配接打開裝置
}
元件初始化完成之後,添加一個定時任務,用來階段性識别攝像裝置中的圖檔資源,我寫的是每200毫秒去識别一次,如果c#教程圖檔中有二維碼,就識别二維碼;識别成功之後,關閉窗體,将識别結果傳回給上一個界面,此處需要一個有識别二維碼程式包
使用Nuget添加引用,搜尋ZXing,将如下程式包引入:
代碼如下(核心代碼基本就這些):
public CameraQR()
{
this.MinimizeBox = false;
this.MaximizeBox = false;
InitializeComponent();
LoadTitleCenterData();
CheckForIllegalCrossThreadCalls = false;//多線程中通路窗體控件資源不會異常
AddTimer();//定時識别圖檔
}
private void AddTimer()
{
timer = new System.Timers.Timer();
timer.Enabled = true;
timer.Interval = 200;
timer.Start();
timer.Elapsed += new ElapsedEventHandler(PicToQRCode);
}
private void PicToQRCode(object sender, ElapsedEventArgs e)
{
if (_cameraHelper.img == null)
return;
BinaryBitmap bitmap = null;
try
{
MemoryStream ms = new MemoryStream();
_cameraHelper.img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] bt = ms.GetBuffer();
ms.Close();
LuminanceSource source = new RGBLuminanceSource(bt, _cameraHelper.img.Width, _cameraHelper.img.Height);
bitmap = new BinaryBitmap(new ZXing.Common.HybridBinarizer(source));
}
catch (Exception ex)
{
return;
}
Result result=null;
try
{
//開始解碼
result = new MultiFormatReader().decode(bitmap);
}
catch (ReaderException ex)
{
resultStr = ex.ToString();
}
if (result != null)
{
resultStr = result.Text;
this.DialogResult = DialogResult.OK;
this.Close();
}}
窗體關閉時,記得釋放定時器 關閉攝像頭(不然異常滿天飛):
private void CameraQR_FormClosing(object sender, FormClosingEventArgs e)
{
if (timer != null)
{
timer.Dispose();
}
_cameraHelper.CloseDevice();
}
CameraHelper類:
public class CameraHelper
{
public FilterInfoCollection _videoDevices;//本機攝像硬體裝置清單
public VideoSourcePlayer _videoSourcePlayer;//視訊畫布
public Bitmap img = null;//全局變量,儲存每一次捕獲的圖像
public System.Drawing.Image CaptureImage(VideoSourcePlayer sourcePlayer = null)
{
if (sourcePlayer == null || sourcePlayer.VideoSource == null)
{
if (_videoSourcePlayer == null)
return null;
else
{
sourcePlayer = _videoSourcePlayer;
}
}
try
{
if (sourcePlayer.IsRunning)
{
System.Drawing.Image bitmap = sourcePlayer.GetCurrentVideoFrame();
return bitmap;
}
return null;
}
catch (Exception ex)
{
return null;
}
}
public FilterInfoCollection CreateFilterInfoCollection()
{
if (_videoDevices != null)
return _videoDevices;
_videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
return _videoDevices;
}
public VideoCaptureDevice ConnectDevice(VideoSourcePlayer videoSourcePlayer, FilterInfo filterInfo = null)
{
VideoCaptureDevice videoSource = new VideoCaptureDevice();
if (filterInfo == null)
{
videoSource = new VideoCaptureDevice(_videoDevices[_videoDevices.Count - 1].MonikerString);
}
else
{
videoSource = new VideoCaptureDevice(filterInfo.MonikerString);
}
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
videoSourcePlayer.VideoSource = videoSource;
videoSourcePlayer.Start();
_videoSourcePlayer = videoSourcePlayer;
return videoSource;
}
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
img = (Bitmap)eventArgs.Frame.Clone();
}
public void CloseDevice(VideoSourcePlayer videoSourcePlayer = null)
{
if (videoSourcePlayer == null)
{
if (_videoSourcePlayer == null)
return;
_videoSourcePlayer.SignalToStop();
}
else
{
videoSourcePlayer.SignalToStop();
}
}
}
我用的測試二維碼是:
最終的别結果為:
代碼:https://github.com/Binzm/ScanQRCode.git
以上就是winform 調用攝像頭掃碼識别二維碼的實作步驟的詳細内容