Saltar al pie de página
USO DE IRONBARCODE

Cómo Leer un Código de Barras desde la Cámara en VB .NET

In the rapidly evolving landscape of technology, barcode scanner devices have become an integral part of various industries, ranging from retail and logistics to healthcare and manufacturing. Visual Basic .NET from Microsoft, a versatile and powerful programming language, provides developers with a robust framework for creating applications that can read barcodes directly from a camera feed. This article aims to provide a comprehensive barcode reader tutorial using a camera in Visual Basic using the IronBarcode library from Iron Software.

IronBarcode library allows you to read barcode image files and also when streamed from cameras. It also supports the reading of barcodes from a PDF document. It is able to scan a maximum of one barcode at a time. The barcode type needs to be specified at the time of reading the barcode image in the VB.NET barcode reader SDK.

How to Read a Barcode from Camera in VB .NET

  1. Create a new VB.NET Project in Visual Studio
  2. Install the IronBarcode Library and apply it to your project
  3. Get the barcode from the camera as an image using the AForge Library
  4. Decode the barcode image using IronBarcode

Prerequisites

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

Step 1: Create a New Visual Basic .NET Project in Visual Studio

Create a new VB.NET Windows Forms application (or use an existing project) where you want to host the code to read the barcode from your camera.

How to Read a Barcode from Camera in VB .NET: Figure 1 - Create new VB.NET Windows form application

In the next step, you can provide the solution and project names.

How to Read a Barcode from Camera in VB .NET: Figure 2 - Configuring the project with the name and solution

Select the .NET version and click the "Create" button.

Step 2: Install the IronBarcode Library

Open your VB.NET project and install the IronBarcode library using the NuGet Package Manager Console:

Install-Package BarCode

How to Read a Barcode from Camera in VB .NET: Figure 3 - Installing the NuGet IronBarcode package

The NuGet package can also be installed using Visual Studio's NuGet Package Manager, as shown below.

How to Read a Barcode from Camera in VB .NET: Figure 4 - Installing IronBarcode through Visual Studio's Package Manager

Step 3: Reading the Barcode from the Camera

To scan the feed and capture the image from the camera, we need the AForge Library. Install it as below from the NuGet package manager.

How to Read a Barcode from Camera in VB .NET: Figure 5 - AForge library package's that are found in Visual Studio Package Manager

The next step is to add the PictureBox control from the ToolBox to the forms. This is used to capture the image from the camera.

How to Read a Barcode from Camera in VB .NET: Figure 6 - Adding the PictureBox control

Then copy the below code to the forms application and create the VB .NET barcode reader component from IronBarcode.

Imports IronBarCode
Imports AForge.Video
Imports AForge.Video.DirectShow

Public Class Form1
    Private videoDevices As FilterInfoCollection
    Private videoSource As VideoCaptureDevice

    ' Event handler for form load
    Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        videoDevices = New FilterInfoCollection(FilterCategory.VideoInputDevice)
        If videoDevices.Count > 0 Then
            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

    ' Event handler for capturing and processing new frame from the video source
    Private Sub VideoSource_NewFrame(sender As Object, eventArgs As NewFrameEventArgs)
        pictureBoxCamera.Image = DirectCast(eventArgs.Frame.Clone(), Bitmap)

        ' Process each frame for barcode recognition
        Dim image = DirectCast(pictureBoxCamera.Image, Bitmap)
        Dim result = BarcodeReader.QuicklyReadOneBarcode(image, BarcodeEncoding.QRCode Or BarcodeEncoding.Code128)

        If result IsNot Nothing Then
            ' Barcode found, handle the new result (e.g., display the barcode value)
            Dim barcodeValue As String = result.Text
            ShowBarcodeResult(barcodeValue)
        End If
    End Sub

    ' Method to display the barcode result
    Private Sub ShowBarcodeResult(barcodeValue As String)
        ' Invoke on UI thread to update UI controls
        If InvokeRequired Then
            Invoke(New Action(Of String)(AddressOf ShowBarcodeResult), barcodeValue)
        Else
            ' Display the barcode value in a MessageBox or any other UI element
            MessageBox.Show("Barcode Value: " & barcodeValue, "Barcode Detected")
        End If
    End Sub

    ' Event handler for form closing
    Private Sub MainForm_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        If videoSource IsNot Nothing AndAlso videoSource.IsRunning Then
            videoSource.SignalToStop()
            videoSource.WaitForStop()
        End If
    End Sub
End Class
Imports IronBarCode
Imports AForge.Video
Imports AForge.Video.DirectShow

Public Class Form1
    Private videoDevices As FilterInfoCollection
    Private videoSource As VideoCaptureDevice

    ' Event handler for form load
    Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        videoDevices = New FilterInfoCollection(FilterCategory.VideoInputDevice)
        If videoDevices.Count > 0 Then
            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

    ' Event handler for capturing and processing new frame from the video source
    Private Sub VideoSource_NewFrame(sender As Object, eventArgs As NewFrameEventArgs)
        pictureBoxCamera.Image = DirectCast(eventArgs.Frame.Clone(), Bitmap)

        ' Process each frame for barcode recognition
        Dim image = DirectCast(pictureBoxCamera.Image, Bitmap)
        Dim result = BarcodeReader.QuicklyReadOneBarcode(image, BarcodeEncoding.QRCode Or BarcodeEncoding.Code128)

        If result IsNot Nothing Then
            ' Barcode found, handle the new result (e.g., display the barcode value)
            Dim barcodeValue As String = result.Text
            ShowBarcodeResult(barcodeValue)
        End If
    End Sub

    ' Method to display the barcode result
    Private Sub ShowBarcodeResult(barcodeValue As String)
        ' Invoke on UI thread to update UI controls
        If InvokeRequired Then
            Invoke(New Action(Of String)(AddressOf ShowBarcodeResult), barcodeValue)
        Else
            ' Display the barcode value in a MessageBox or any other UI element
            MessageBox.Show("Barcode Value: " & barcodeValue, "Barcode Detected")
        End If
    End Sub

    ' Event handler for form closing
    Private Sub MainForm_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        If videoSource IsNot Nothing AndAlso videoSource.IsRunning Then
            videoSource.SignalToStop()
            videoSource.WaitForStop()
        End If
    End Sub
End Class
VB .NET

In this sample code, we have configured it to read QR codes and Code 128 barcodes. First, we use a PictureBox to capture barcode images from a webcam or any camera device by scanning the barcode. Then we create a bitmap image, which is then provided as input to the IronBarcode BarcodeReader class. This application reads the 2D barcode from images and decodes them. If a positive result is obtained after decoding, then the result is displayed in the message box.

Licensing (Free Trial Available)

To use IronBarcode, you need to place a license key in your appsettings.json.

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

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

How to Read a Barcode from Camera in VB .NET: Figure 7 - Popup after successfully submitting a trial form

Conclusion

Implementing barcode reading from a camera in VB.NET is a powerful feature that can enhance various applications across different industries. By leveraging libraries like IronBarcode and integrating them into your VB.NET project, you can create efficient and reliable barcode scanning applications that meet the demands of today's technology-driven world. This guide serves as a starting point, and developers can further customize and optimize the solution based on their specific requirements, barcode types, and use cases.

Preguntas Frecuentes

¿Cómo puedo leer códigos de barras desde una cámara usando VB.NET?

Para leer códigos de barras desde una cámara en VB.NET, puedes usar la biblioteca IronBarcode para decodificar imágenes capturadas de la transmisión de una cámara. Primero, configura un proyecto VB.NET en Visual Studio, instala IronBarcode a través de NuGet y utiliza la biblioteca AForge para gestionar la entrada de la cámara.

¿Qué pasos se involucran en la configuración de un proyecto lector de códigos de barras en VB.NET?

Comienza creando una nueva aplicación de formularios Windows en VB.NET en Visual Studio. Instala la biblioteca IronBarcode utilizando NuGet y configura un PictureBox para capturar imágenes de tu cámara. Usa la biblioteca AForge para manejar las transmisiones de la cámara y IronBarcode para decodificar códigos de barras.

¿Cómo integrarme con capacidades de captura de cámara en una aplicación VB.NET?

Puedes integrar capacidades de captura de cámara en una aplicación VB.NET usando la biblioteca AForge para acceder y gestionar las transmisiones de la cámara. Estas transmisiones entonces se pueden procesar para capturar imágenes para decodificación de códigos de barras usando IronBarcode.

¿Qué tipos de códigos de barras se pueden decodificar usando IronBarcode en un proyecto de VB.NET?

IronBarcode soporta la decodificación de una amplia gama de tipos de códigos de barras, incluyendo códigos QR y código 128, en un proyecto VB.NET. La biblioteca es versátil y se puede configurar para reconocer diferentes formatos de códigos de barras.

¿Cuáles son los componentes necesarios para desarrollar una aplicación de escaneo de códigos de barras en VB.NET?

Para desarrollar una aplicación de escaneo de códigos de barras en VB.NET, necesitas Visual Studio, una cámara compatible, la biblioteca IronBarcode instalada a través de NuGet y la biblioteca AForge para manejar la entrada de la cámara.

¿Cómo puedo solucionar problemas comunes al leer códigos de barras desde una cámara en VB.NET?

Asegúrate de que tu cámara esté correctamente conectada y reconocida por tu sistema. Verifica que las bibliotecas IronBarcode y AForge estén correctamente instaladas y que tu aplicación tenga acceso a la transmisión de la cámara. Revisa la sintaxis del código y las referencias de la biblioteca para detectar errores.

¿Cuál es el proceso para mostrar los resultados del escaneo de códigos de barras en una aplicación VB.NET?

Una vez que un código de barras es decodificado usando IronBarcode, puedes mostrar el resultado en tu aplicación VB.NET mostrándolo en un componente de interfaz de usuario como un MessageBox o una Label para presentar los datos del código de barras al usuario.

¿Puedo probar la biblioteca de códigos de barras antes de comprarla, y cómo obtengo la prueba?

Sí, puedes probar la biblioteca de códigos de barras obteniendo una clave de licencia de prueba desde el sitio web de Iron Software. Envía tu dirección de correo electrónico y recibirás la clave de prueba por correo electrónico para usar en tus proyectos VB.NET.

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