NEWS

[C#] Hướng dẫn scan multi QRCode, Barcode Realtime sử dụng Zxing.Net và AForge

[C#] Hướng dẫn scan multi QRCode, Barcode Realtime sử dụng Zxing.Net và AForge
Đăng bởi: Thảo Meo - Lượt xem: 12676 22:45:53, 08/06/2020ANDROID

Xin chào các bạn, bài viết hôm nay mình sẽ hướng dẫn các bạn cách viết ứng dụng đọc QRCode, Barcode 1D, 2D sử dụng thư viện AForge và Zxing.NET trong lập trình C# Winform.

[C#] Scan Multi QRcode, Barcode Realtime in Winform

Dưới đây là video demo của ứng dụng Read Qrcode C#:

scan_qr

Trong bài viết này mình sử dụng 2 thư viện: Aforge và ZXing.NET 

  1. Thư viện Aforge dùng để đọc video vào picturebox
  2. Thư viện Zxing dùng để decode mã vạch QRcode, Barcode từ hình ảnh sang dạng Text.

Ở giao diện demo trên, các bạn thấy mình có vẽ một hình vuông bao quanh mã vạch Qrcode mà ứng dụng scan được, và hiện thị kết quả trực tiếp lên trên giao diện PictureBox.

Từ Nuget Console các bạn cài đặt AForge và ZXing.NET bằng lệnh sau:

PM> Install-Package AForge.Video.DirectShow -Version 2.2.5
PM> Install-Package ZXing.Net -Version 0.16.5

Full source code ứng dụng C#:

using AForge.Video;
using AForge.Video.DirectShow;
using System;
using System.Drawing;
using System.Media;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZXing;

namespace ScanQR
{
    public partial class Form1 : Form
    {
        FilterInfoCollection filterInfoCollection;
        VideoCaptureDevice videoCaptureDevice;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            filterInfoCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            foreach (FilterInfo Device in filterInfoCollection)
                cboCamera.Items.Add(Device.Name);
            if (cboCamera.Items.Count > 0)
            {
                cboCamera.SelectedIndex = 0;
                videoCaptureDevice = new VideoCaptureDevice();
            }
           
        }
        CancellationTokenSource cancellationToken;
        private void button1_Click(object sender, EventArgs e)
        {
            if(button1.Text == "Bắt đầu")
            {
                videoCaptureDevice = new VideoCaptureDevice(filterInfoCollection[cboCamera.SelectedIndex].MonikerString);
                videoCaptureDevice.NewFrame += FinalFrame_NewFrame;
                videoCaptureDevice.Start();
                cancellationToken = new CancellationTokenSource();
                var sourcetoken = cancellationToken.Token;
                onStartScan(sourcetoken);
                button1.Text = "Dừng lại!";
            }
            else
            {
                button1.Text = "Bắt đầu";
                cancellationToken.Cancel();
                if (videoCaptureDevice != null)
                    if (videoCaptureDevice.IsRunning == true)
                        videoCaptureDevice.Stop();
            }

           
        }
        private void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
        }

        public void onStartScan(CancellationToken sourcetoken)
        {
            Task.Factory.StartNew(new Action(() =>
            {
                while (true)
                {
                    if (sourcetoken.IsCancellationRequested)
                    {
                        return;
                    }
                    Thread.Sleep(50);
                    BarcodeReader Reader = new BarcodeReader();                   
                    pictureBox1.BeginInvoke(new Action(() =>
                    {
                        if (pictureBox1.Image != null)
                        {
                            try
                            {
                                var results = Reader.DecodeMultiple((Bitmap)pictureBox1.Image);
                                if (results != null)
                                {
                                    foreach (Result result in results)
                                    {
                                        lbl_result.Text = result.ToString() + $"- Type: { result.BarcodeFormat.ToString()}";

                                        SystemSounds.Beep.Play();
                                        if (result.ResultPoints.Length > 0)
                                        {
                                            var offsetX = pictureBox1.SizeMode == PictureBoxSizeMode.Zoom
                                               ? (pictureBox1.Width - pictureBox1.Image.Width) / 2 :
                                               0;
                                            var offsetY = pictureBox1.SizeMode == PictureBoxSizeMode.Zoom
                                               ? (pictureBox1.Height - pictureBox1.Image.Height) / 2 :
                                               0;
                                            var rect = new Rectangle((int)result.ResultPoints[0].X + offsetX, (int)result.ResultPoints[0].Y + offsetY, 1, 1);
                                            foreach (var point in result.ResultPoints)
                                            {
                                                if (point.X + offsetX < rect.Left)
                                                    rect = new Rectangle((int)point.X + offsetX, rect.Y, rect.Width + rect.X - (int)point.X - offsetX, rect.Height);
                                                if (point.X + offsetX > rect.Right)
                                                    rect = new Rectangle(rect.X, rect.Y, rect.Width + (int)point.X - (rect.X - offsetX), rect.Height);
                                                if (point.Y + offsetY < rect.Top)
                                                    rect = new Rectangle(rect.X, (int)point.Y + offsetY, rect.Width, rect.Height + rect.Y - (int)point.Y - offsetY);
                                                if (point.Y + offsetY > rect.Bottom)
                                                    rect = new Rectangle(rect.X, rect.Y, rect.Width, rect.Height + (int)point.Y - (rect.Y - offsetY));
                                            }
                                            using (var g = pictureBox1.CreateGraphics())
                                            {
                                                using (Pen pen = new Pen(Color.Green, 5))
                                                {                                                  
                                                    g.DrawRectangle(pen, rect);

                                                    pen.Color = Color.Yellow;
                                                    pen.DashPattern = new float[] { 5, 5 };
                                                    g.DrawRectangle(pen, rect);
                                                }
                                                g.DrawString(result.ToString(), new Font("Tahoma", 16f), Brushes.Blue, new Point(rect.X - 60, rect.Y - 50));
                                            }
                                        }


                                    }

                                }
                            }
                            catch (Exception)
                            {                               
                            }
                        }

                    }));
                   
                }
            }), sourcetoken);
        }
      

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(videoCaptureDevice != null)
            if (videoCaptureDevice.IsRunning == true)
                videoCaptureDevice.Stop();
        }
    }
}

Video demo ứng dụng:

Thanks for watching!

DOWNLOAD SOURCE

Tags: scan qrcode c#scan barcode realtime c#

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn scan multi QRCode, Barcode Realtime sử dụng Zxing.Net và AForge
Đăng bởi: Thảo Meo - Lượt xem: 12676 22:45:53, 08/06/2020ANDROID

CÁC BÀI CÙNG CHỦ ĐỀ

.