此项目用C#实现了摄像头拍照及解析QR二维码,下面附上测试截图及部分源码:

拍照功能:

解析电脑拍摄的2D图片,能够正确显示文本信息

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Imaging;
using com.google.zxing;
using System.IO;namespace Camera
{public partial class Camera : Form{//APIprivate int hHwnd;private const int port = 2000;//zxingprivate CamWorker _camWorker = null;System.Timers.Timer _timer = null;string _directory = "";private int _failedCount = 0;private int _doCount = 0;public Camera(){InitializeComponent();}public struct videohdr_tag{public byte[] lpData;public int dwBufferLength;public int dwBytesUsed;public int dwTimeCaptured;public int dwUser;public int dwFlags;public int[] dwReserved;}public delegate bool CallBack(int hwnd, int lParam);///   <summary>   ///   必需的设计器变量。   ///   </summary>   [DllImport("avicap32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]public static extern int capCreateCaptureWindowA([MarshalAs(UnmanagedType.VBByRefStr)]   ref   string lpszWindowName, int dwStyle, int x, int y, int nWidth, short nHeight, int hWndParent, int nID);[DllImport("avicap32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]public static extern bool capGetDriverDescriptionA(short wDriver, [MarshalAs(UnmanagedType.VBByRefStr)]   ref   string lpszName, int cbName, [MarshalAs(UnmanagedType.VBByRefStr)]   ref   string lpszVer, int cbVer);[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]public static extern bool DestroyWindow(int hndw);[DllImport("user32", EntryPoint = "SendMessageA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]public static extern int SendMessage(int hwnd, int wMsg, int wParam, [MarshalAs(UnmanagedType.AsAny)]   object lParam);[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]public static extern int SetWindowPos(int hwnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags);[DllImport("vfw32.dll")]public static extern string capVideoStreamCallback(int hwnd, videohdr_tag videohdr_tag);[DllImport("vicap32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]public static extern bool capSetCallbackOnFrame(int hwnd, string s);private void OpenCapture(){int intWidth = this.panel1.Width;int intHeight = this.panel1.Height;int intDevice = 0;string refDevice = intDevice.ToString();//创建视频窗口并得到句柄hHwnd = Camera.capCreateCaptureWindowA(ref   refDevice, 1342177280, 0, 0, 640, 480, this.panel1.Handle.ToInt32(), 0);if (Camera.SendMessage(hHwnd, 0x40a, intDevice, 0) > 0){Camera.SendMessage(this.hHwnd, 0x435, -1, 0);Camera.SendMessage(this.hHwnd, 0x434, 0x42, 0);Camera.SendMessage(this.hHwnd, 0x432, -1, 0);Camera.SetWindowPos(this.hHwnd, 1, 0, 0, intWidth, intHeight, 6);}else{Camera.DestroyWindow(this.hHwnd);}}private void btnOpen_Click(object sender, EventArgs e){this.OpenCapture();}private void btnStop_Click(object sender, EventArgs e){//停止视频注销视频句柄Camera.SendMessage(this.hHwnd, 0x40b, 0, 0);Camera.DestroyWindow(this.hHwnd);}//截图private void btnCapture_Click(object sender, EventArgs e){try{Camera.SendMessage(this.hHwnd, 0x41e, 0, 0);IDataObject obj1 = Clipboard.GetDataObject();if (obj1.GetDataPresent(typeof(Bitmap))){Image image1 = (Image)obj1.GetData(typeof(Bitmap));SaveFileDialog SaveFileDialog1 = new SaveFileDialog();SaveFileDialog1.FileName = DateTime.Now.ToString("yyyyMMddhhmmss");SaveFileDialog1.Filter = "Image Files(*.JPG;*.GIF)|*.JPG;*.GIF|All files (*.*)|*.*";if (SaveFileDialog1.ShowDialog() == DialogResult.OK){image1.Save(SaveFileDialog1.FileName, ImageFormat.Bmp);}}}catch{}}private void btnExit_Click(object sender, EventArgs e){Application.Exit();}private void btnStart_zxing_Click(object sender, EventArgs e){_doCount = 0;_directory = Path.Combine(Application.StartupPath, "temp");if (Directory.Exists(_directory)){var files = Directory.GetFiles(_directory);for (int i = 0; i < files.Length; i++){File.Delete(files[i]);}}else{Directory.CreateDirectory(_directory);}_camWorker = new CamWorker(panel2.Handle, 0, 0, panel2.Width, panel2.Height);_camWorker.Start();_labelStatus.Text = "Cameram is working...";if (_timer != null && _timer.Enabled){_timer.Stop();_timer.Dispose();}_timer = new System.Timers.Timer(1000);_timer.Start();_timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);}void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e){_doCount++;_labelDoCount.BeginInvoke(new Action(() =>{_labelDoCount.Text = _doCount.ToString();}));string fileName = Path.Combine(_directory, System.Guid.NewGuid() + ".bmp");try{_camWorker.GrabImage(fileName);if (File.Exists(fileName)){_labelStatus.BeginInvoke(new Action(() =>{_labelStatus.Text = string.Format("Successed to find image: {0}, and decoding...", fileName);}));Image img = null;try{img = Image.FromFile(fileName);}catch (OutOfMemoryException){_failedCount++;_labelStatus.BeginInvoke(new Action(() =>{_labelStatus.Text = "Image format is not correct.";}));return;}Bitmap bmap;try{bmap = new Bitmap(img);}catch (System.IO.IOException ioe){_failedCount++;_labelStatus.BeginInvoke(new Action(() =>{_labelStatus.Text = ioe.ToString();}));return;}if (bmap == null){_failedCount++;_labelStatus.BeginInvoke(new Action(() =>{_labelStatus.Text = "Could not decode image";}));return;}LuminanceSource source = new RGBLuminanceSource(bmap, bmap.Width, bmap.Height);com.google.zxing.BinaryBitmap bitmap = new com.google.zxing.BinaryBitmap(new com.google.zxing.common.HybridBinarizer(source));Result result;try{result = new MultiFormatReader().decode(bitmap);_labelStatus.BeginInvoke(new Action(() =>{_labelStatus.Text = result.Text;}));this.pictureBox2.ImageLocation = fileName;Stop();MessageBox.Show(string.Format("Successed to decode: {0}.", result.Text));}catch (ReaderException re){_failedCount++;_labelStatus.BeginInvoke(new Action(() =>{_labelStatus.Text = re.ToString();}));return;}}_labelStatus.BeginInvoke(new Action(() =>{_labelStatus.Text = string.Format("Failed to find image: {0}...", fileName);}));}finally{if (_failedCount >= 100){_failedCount = 0;Stop();_labelStatus.BeginInvoke(new Action(() =>{_labelStatus.Text = string.Format("Application Force stop monitor,because it can not grab valid image for 100 consecutive times.", fileName);}));}}}private void btnSnap_zxing_Click(object sender, EventArgs e){SaveFileDialog diag = new SaveFileDialog();diag.Filter = "*.bmp|*.*";if (diag.ShowDialog() == System.Windows.Forms.DialogResult.OK){_camWorker.GrabImage(diag.FileName);}}private void btnStop_zxing_Click(object sender, EventArgs e){Stop();}private void Stop(){_doCount = 0;if (_timer != null && _timer.Enabled){_timer.Stop();_timer.Dispose();}_camWorker.Stop();_labelStatus.BeginInvoke(new Action(() =>{_labelStatus.Text = "Cameram has been shutdown.";}));}private void btnGen2D_Click(object sender, EventArgs e){frm2Dcode f = new frm2Dcode();f.ShowDialog();}}
}
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;
using com.google.zxing;
using COMMON = com.google.zxing.common;namespace Camera
{public partial class frm2Dcode : Form{public frm2Dcode(){InitializeComponent();}OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog();private void btnEncode_Click(object sender, EventArgs e){SaveFileDialog sFD = new SaveFileDialog();sFD.DefaultExt = "*.png|*.png";sFD.AddExtension = true;try{if (sFD.ShowDialog() == DialogResult.OK){string content = this.textBox1.Text;COMMON.ByteMatrix byteMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 350, 350);writeToFile(byteMatrix, System.Drawing.Imaging.ImageFormat.Png, sFD.FileName);}}catch (Exception ex){MessageBox.Show(ex.Message);}}private void btnDecode_Click(object sender, EventArgs e){if (this.openFileDialog1.ShowDialog() != DialogResult.OK){return;}Image img = Image.FromFile(this.openFileDialog1.FileName);Bitmap bmap;try{bmap = new Bitmap(img);}catch (System.IO.IOException ioe){MessageBox.Show(ioe.ToString());return;}if (bmap == null){MessageBox.Show("Could not decode image");return;}LuminanceSource source = new RGBLuminanceSource(bmap, bmap.Width, bmap.Height);com.google.zxing.BinaryBitmap bitmap = new com.google.zxing.BinaryBitmap(new COMMON.HybridBinarizer(source));Result result;try{result = new MultiFormatReader().decode(bitmap);}catch (ReaderException re){this.textBox1.Text = re.ToString();return;}MessageBox.Show(result.Text);}public void writeToFile(COMMON.ByteMatrix matrix, System.Drawing.Imaging.ImageFormat format, string file){Bitmap bmap = toBitmap(matrix);bmap.Save(file, format);pictureBox1.Image = bmap;}public Bitmap toBitmap(COMMON.ByteMatrix matrix){int width = matrix.Width;int height = matrix.Height;Bitmap bmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);for (int x = 0; x < width; x++){for (int y = 0; y < height; y++){bmap.SetPixel(x, y, matrix.get_Renamed(x, y) != -1 ? ColorTranslator.FromHtml("0xFF000000") : ColorTranslator.FromHtml("0xFFFFFFFF"));}}return bmap;}}
}

摄像头拍照及解析QR二维码相关推荐

  1. 手机移动端-纯js浏览器h5调用摄像头扫描识别解析 条形码+二维码

    一.场景 手机移动端-原生js 浏览器h5 解决 识别二维码 条形码功能: 不借助Hbuilder.需要自己打包成APP,比如用Hbuilder打包,浏览器端项目h5 无打包成app部署 X 不采用 ...

  2. Java解析生成二维码-log

    Java解析生成二维码 1.pom.xml依赖 <!-- 引入二维码相关的依赖--><dependency><groupId>com.google.zxing< ...

  3. QR二维码的攻击方法与防御

    Blackeagle · 2013/07/03 18:59 QR二维码(Quick Response Code)是由日本丰田子公司Denso Wave于1994年发明并开始使用的一种矩阵二维码符号.与 ...

  4. 【Matlab编程实现常见小问题之二】Matlab如何实现QR二维码的生成与识别

    本篇文章中,旨在解决如何用Matlab编程实现QR二维码的生成与识别.编程环境是Matlab2012a,所用的开源库是ZXing,ZXing是一个开源Java类库用于解析多种格式的1D/2D条形码.目 ...

  5. 初识 QR 二维码(零)

    提到二维码,想必大家每天都会接触到,扫码支付.扫码添加微信好友等都会用到.关于二维码的生成原理,网上确实有些介绍,但基本涉及到具体编码就一笔带过没有深入了.目前 Python 也有现成的模块可以调用来 ...

  6. 【OpenCV 4开发详解】QR二维码检测

    本文首发于"小白学视觉"微信公众号,欢迎关注公众号 本文作者为小白,版权归人民邮电出版社发行所有,禁止转载,侵权必究! 经过几个月的努力,小白终于完成了市面上第一本OpenCV 4 ...

  7. OpenCV4.0 快速QR二维码检测测试示例

    点击我爱计算机视觉标星,更快获取CVML新技术 近几年由于微信大力推广移动支付,二维码已经成为手机App的标配,在众多种类的二维码中,QR码是最为流行的. 刚刚发布的OpenCV4.0-Alpha新增 ...

  8. python用二维码共享文档_[源码和文档分享]基于Python的QR二维码的生成与识别程序...

    摘 要 进入二十一世纪之后,高新技术产业得到了极其迅速的发展.计算机.互联网.物联网.云计算等领域的发展,使得整个社会的信息化程度极大提高.随着技术的不断成熟,目前的一维条形码已逐渐向二维码过渡.本课 ...

  9. 生成QR二维码图片示例

    生成QR二维码图片的简单示例 QR二维码的生成,在生成QR二维条码中已经提及.不过上次是通过网站生成的,缺点是对网站的依赖.下面做了个调用zxing core实现生成QR二维码图片的示例.另外还可以通 ...

最新文章

  1. 「土行孙」机器人登上Science子刊封面,用气流在地下穿梭自如,速度达每秒4.8米...
  2. mysql讀取sql_SQL 2008连接读取mysql数据的方法
  3. 使用Qt Designer编辑资源
  4. 初学者的React全家桶完整实例
  5. Swift 语言快速入门
  6. 解决下载GitHub项目速度慢的问题(2019.1.21亲测有效)
  7. 详述 PyPI 中的远程代码执行漏洞,可引发供应链攻击
  8. java list 去除 重复值
  9. SQLyog入门教程:安装与使用
  10. 2.3 WSN的MAC协议
  11. pb 如何导出csv_如何巧用长投温度定投指数基金
  12. 翻译Guzzle摘要
  13. 进不了字节,腾讯等大厂没学历的程序员应该如何生存?
  14. List of colors (from wikipedia)
  15. [渝粤教育] 西安建筑科技大学 技术经济学 参考 资料
  16. 苹果电脑怎么更换计算机模式,苹果电脑装windows7后怎么切回来_苹果电脑安装win7后如何切换...
  17. Productivity Power Tools工具
  18. 什么是间隙锁?怎样避免间隙锁的危害?
  19. 过程计算机系统 pcs,过程控制系统(PCS)
  20. 【如何更新几十万上百万的数据在ORACLE和MYSQL】

热门文章

  1. 分布式事务框架 Seata 与 Hmily 横向比较
  2. PowerPoint课件动画制作三例
  3. 拉普拉斯矩阵(Laplacian matrix)的求解
  4. 如何查看MySQL版本号
  5. Freescale k60的GPIO的操作
  6. Could not chdir to home directory /home/xxx:Permission denied
  7. UKey税务系统开票及打票流程
  8. Domain Adaption 领域自适应
  9. 21点扑克游戏的出牌策略的研究
  10. C语言利用顺序表求两个集合的差集