摄像头拍照及解析QR二维码

来源:互联网 发布:怎么下载windows 编辑:程序博客网 时间:2024/06/07 04:07

此项目用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    {        //API        private int hHwnd;        private const int port = 2000;        //zxing        private 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;        }    }}


       

 

原创粉丝点击