Saltar al pie de página
USO DE IRONBARCODE

Lector de Código QR en C# (Tutorial Paso a Paso para Principiantes)

In today's digitally driven world, QR codes (Quick Response Codes) have become ubiquitous, seamlessly connecting physical and digital realms. From marketing to logistics, finance to healthcare, QR codes play a pivotal role in facilitating efficient data exchange.

In this article, we delve into the realm of C# development, exploring how IronQR, one of the best QR code libraries in the market, empowers developers to harness the power of QR code recognition, effortlessly decode data, and innovate across various domains.

IronQR from Iron Software stands out as a robust .NET QR code reader library. The advanced machine learning model implemented by IronQR empowers your applications to decode QR codes with unmatched accuracy and efficiency, even in challenging scenarios.

How to Read QR Codes using C# with IronQR

  1. Create a Visual Studio project with a .NET Windows Forms Application template.
  2. Install IronQR from the NuGet package manager.
  3. Get the QR code from the camera as an image using the AForge library.
  4. Read QR Codes using IronQR.

IronQR stands out as the premier C# QR code reader library designed to both scan and generate QR code images within the .NET framework. Through the utilization of cutting-edge ML technology, IronQR has elevated QR code reading to unprecedented levels.

Whether you are scanning QR codes from images, videos, or live camera feeds, the ML-powered solution guarantees swift and reliable information retrieval.

This innovative approach not only streamlines data extraction but also enhances security by discerning between authentic QR codes and potential threats. With its intuitive API, developers can seamlessly integrate QR code capabilities into their .NET projects in a matter of minutes.

IronQR seamlessly integrates with .NET Core (8, 7, 6, 5, and 3.1+), .NET Standard (2.0+), and .NET Framework (4.6.2+). The present .NET Core version extends its support to client operating systems like Linux, Unix, and macOS, along with compatibility to develop mobile apps.

Prerequisites

  1. Visual Studio: Make sure you have Visual Studio or any other .NET development environment installed.
  2. Compatible Camera: Ensure that the camera is connected to your device.
  3. NuGet Package Manager: Verify that you can utilize NuGet to manage packages in your project.

Step 1: Create a Visual Studio project with a .NET Windows Forms Application template

Let's get started by creating a Windows Forms .NET application to read QR code barcodes from camera video streams or image files. Open Visual Studio, select Create New Project, and then select the .NET Windows Forms Application template.

Visual Studio Setup

Click Next and enter the project name.

Project Naming

Select the desired .NET Versions and then click the Create button.

Create Project

Step 2: Install IronQR from the NuGet package manager

IronQR can be installed using the NuGet package manager or Visual Studio Package Manager.

NuGet Installation

Below shows how you can do it using Visual Studio.

Visual Studio NuGet

Step 3: Get the QR code from the camera as an image using the AForge Library

To scan QR codes from camera devices, we need to install the AForge.Video.DirectShow library. This can be done using the Visual Studio package manager. Right-click on the Solution Explorer and open the Package Manager.

AForge Installation Step 1

This library can also be installed using the NuGet package console as shown below. Click the Install button to install the library.

AForge Installation Step 2

Step 4: Read QR Codes using IronQR

The next step is to create a PictureBox component in the Form, which is required to scan the QR code image from the camera device connected to the machine.

This can be done by dragging and dropping from the toolbox. This PictureBox is required to read the QR code data from the camera device.

Add PictureBox

Next, drag and drop a Text box to show the read QR codes.

Add TextBox

Add the below code to read QR codes and decode them using IronQR.

using AForge.Video.DirectShow;
using AForge.Video;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using IronQR;

namespace ReadQR
{
    public partial class Form1 : Form
    {
        // Declare a video capture device
        private VideoCaptureDevice videoSource;

        public Form1()
        {
            InitializeComponent();
            this.Load += Form1_Load;
            this.FormClosing += Form1_FormClosing;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // Stop the video source when the form is closing
            if (videoSource != null && videoSource.IsRunning)
            {
                videoSource.SignalToStop();
                videoSource.WaitForStop();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Retrieve video input devices connected to the machine
            FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

            if (videoDevices.Count > 0)
            {
                // Use the first available video device
                videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
                videoSource.NewFrame += VideoSource_NewFrame;
                videoSource.Start();
            }
            else
            {
                MessageBox.Show("No video devices found.");
                Close();
            }
        }

        private void VideoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            // Update the PictureBox with the new frame from the camera
            pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();

            var image = (Bitmap)eventArgs.Frame.Clone();

            // Set the license key for IronQR. Replace "YourKey" with your actual key
            License.LicenseKey = "YourKey";

            // Prepare the image for QR code reading
            QrImageInput imageInput = new QrImageInput(image);

            // Create a QR reader object
            QrReader reader = new QrReader();

            // Read QR codes from the image
            IEnumerable<QrResult> results = reader.Read(imageInput);

            // Display the first QR code result in a MessageBox
            if (results.Any())
            {
                MessageBox.Show(results.First().Value);
            }
        }
    }
}
using AForge.Video.DirectShow;
using AForge.Video;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using IronQR;

namespace ReadQR
{
    public partial class Form1 : Form
    {
        // Declare a video capture device
        private VideoCaptureDevice videoSource;

        public Form1()
        {
            InitializeComponent();
            this.Load += Form1_Load;
            this.FormClosing += Form1_FormClosing;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // Stop the video source when the form is closing
            if (videoSource != null && videoSource.IsRunning)
            {
                videoSource.SignalToStop();
                videoSource.WaitForStop();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Retrieve video input devices connected to the machine
            FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

            if (videoDevices.Count > 0)
            {
                // Use the first available video device
                videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
                videoSource.NewFrame += VideoSource_NewFrame;
                videoSource.Start();
            }
            else
            {
                MessageBox.Show("No video devices found.");
                Close();
            }
        }

        private void VideoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            // Update the PictureBox with the new frame from the camera
            pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();

            var image = (Bitmap)eventArgs.Frame.Clone();

            // Set the license key for IronQR. Replace "YourKey" with your actual key
            License.LicenseKey = "YourKey";

            // Prepare the image for QR code reading
            QrImageInput imageInput = new QrImageInput(image);

            // Create a QR reader object
            QrReader reader = new QrReader();

            // Read QR codes from the image
            IEnumerable<QrResult> results = reader.Read(imageInput);

            // Display the first QR code result in a MessageBox
            if (results.Any())
            {
                MessageBox.Show(results.First().Value);
            }
        }
    }
}
Imports AForge.Video.DirectShow
Imports AForge.Video
Imports System
Imports System.Collections.Generic
Imports System.Drawing
Imports System.Linq
Imports System.Windows.Forms
Imports IronQR

Namespace ReadQR
	Partial Public Class Form1
		Inherits Form

		' Declare a video capture device
		Private videoSource As VideoCaptureDevice

		Public Sub New()
			InitializeComponent()
			AddHandler Me.Load, AddressOf Form1_Load
			AddHandler Me.FormClosing, AddressOf Form1_FormClosing
		End Sub

		Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs)
			' Stop the video source when the form is closing
			If videoSource IsNot Nothing AndAlso videoSource.IsRunning Then
				videoSource.SignalToStop()
				videoSource.WaitForStop()
			End If
		End Sub

		Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
			' Retrieve video input devices connected to the machine
			Dim videoDevices As New FilterInfoCollection(FilterCategory.VideoInputDevice)

			If videoDevices.Count > 0 Then
				' Use the first available video device
				videoSource = New VideoCaptureDevice(videoDevices(0).MonikerString)
				AddHandler videoSource.NewFrame, AddressOf VideoSource_NewFrame
				videoSource.Start()
			Else
				MessageBox.Show("No video devices found.")
				Close()
			End If
		End Sub

		Private Sub VideoSource_NewFrame(ByVal sender As Object, ByVal eventArgs As NewFrameEventArgs)
			' Update the PictureBox with the new frame from the camera
			pictureBox1.Image = DirectCast(eventArgs.Frame.Clone(), Bitmap)

			Dim image = DirectCast(eventArgs.Frame.Clone(), Bitmap)

			' Set the license key for IronQR. Replace "YourKey" with your actual key
			License.LicenseKey = "YourKey"

			' Prepare the image for QR code reading
			Dim imageInput As New QrImageInput(image)

			' Create a QR reader object
			Dim reader As New QrReader()

			' Read QR codes from the image
			Dim results As IEnumerable(Of QrResult) = reader.Read(imageInput)

			' Display the first QR code result in a MessageBox
			If results.Any() Then
				MessageBox.Show(results.First().Value)
			End If
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Input Image file

The encoded text in the QR code is: I Love IronQR

QR Code Example

Output

QR Code Result

Example Code Explanation

  1. We have registered two events in Windows Forms: Form1_Load and Form1_FormClosing.
  2. We have also registered VideoSource_NewFrame to an instance of videoSource from the AForge.Video.DirectShow library.
  3. We read the QR codes from the live video stream.
  4. When a QR code is detected, we show a MessageBox with the decoded text.

Licensing (Free Trial Available)

IronQR requires a license key. A trial key can be obtained from the website here. This key needs to be placed in appsettings.json.

{
    "IronQR.LicenseKey": "MYLICENSE.KEY.TRIAL"
}

Provide the email ID to get a trial license, and after submitting, the key will be delivered via email.

License Key

Conclusion

In conclusion, QR codes have transcended their origins to become indispensable in our digital ecosystem. With IronQR, C# developers can harness the power of QR code recognition, decode data in various types of QR codes with ease, and innovate across various domains.

As QR codes continue to evolve and integrate into new technologies, their importance in facilitating seamless data exchange and enhancing user experiences will only grow. Embrace the potential of QR codes with IronQR and embark on a journey of innovation and efficiency in C# development.

Preguntas Frecuentes

¿Cómo puedo configurar un proyecto en C# para leer códigos QR?

Para configurar un proyecto en C# para leer códigos QR, comienza creando una nueva aplicación de formularios de Windows en Visual Studio. Instala la biblioteca IronQR desde el Administrador de Paquetes NuGet y asegúrate de tener la biblioteca AForge.Video.DirectShow para capturar transmisiones de video desde una cámara.

¿Cuáles son los beneficios de usar IronQR para la lectura de códigos QR?

IronQR proporciona capacidades robustas para la lectura de códigos QR aprovechando modelos avanzados de aprendizaje automático. Asegura una decodificación precisa incluso en condiciones desafiantes y es compatible con varios marcos .NET y sistemas operativos.

¿Cómo decodifico un código QR usando IronQR en una aplicación C#?

Para decodificar un código QR en una aplicación C# con IronQR, captura una imagen desde la transmisión de la cámara usando AForge, luego utiliza la biblioteca IronQR para procesar y decodificar el código QR desde la imagen capturada.

¿Puede IronQR decodificar códigos QR de transmisiones de video en vivo?

Sí, IronQR puede decodificar códigos QR de transmisiones de video en vivo integrándose con la biblioteca AForge.Video.DirectShow para capturar cuadros y procesarlos en tiempo real.

¿Qué bibliotecas son esenciales para construir un lector de códigos QR en C#?

Las bibliotecas esenciales para construir un lector de códigos QR en C# incluyen IronQR para decodificar los códigos QR y AForge.Video.DirectShow para capturar transmisiones de video desde la cámara.

¿Cómo asegura IronQR la integridad de los datos durante la decodificación de códigos QR?

IronQR mejora la seguridad y asegura la integridad de los datos al distinguir con precisión entre códigos QR auténticos y potenciales amenazas, manteniendo así la fiabilidad de la información decodificada.

¿Es posible escanear códigos QR desde imágenes usando IronQR?

Sí, IronQR puede escanear códigos QR no solo desde transmisiones en vivo sino también desde imágenes estáticas, proporcionando flexibilidad para diversas necesidades de aplicación.

¿Cómo obtengo una licencia de prueba para IronQR?

Puede obtener una licencia de prueba para IronQR desde el sitio web de Iron Software, lo que le permite probar las características de la biblioteca colocando la clave de prueba en el archivo appsettings.json de su aplicación.

¿Qué papel juega el componente PictureBox en una aplicación de lector de códigos QR?

En una aplicación de lector de códigos QR, el componente PictureBox muestra la transmisión de video en vivo desde la cámara, permitiendo a IronQR capturar y decodificar códigos QR desde los cuadros entrantes.

¿Cómo puedo solucionar problemas con la decodificación de códigos QR en C#?

Si encuentra problemas con la decodificación de códigos QR, asegúrese de que las bibliotecas IronQR y AForge estén correctamente instaladas, verifique que la transmisión de la cámara esté correctamente integrada y asegúrese de que su aplicación esté capturando y procesando correctamente los cuadros de video.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más