DEV Community

Cover image for How to Scan Barcode in C# (Developer Tutorial)
Zeeshan Wazir
Zeeshan Wazir

Posted on

How to Scan Barcode in C# (Developer Tutorial)

Introduction

Barcode scanning is a critical part of many industries, from inventory management to retail and logistics. In this article, I'll demonstrate how to create a Windows Forms Application in C# for barcode scanning using IronBarcode. It will use webcam to scan the barcode and then utilize the IronBarcode to reveal the information. IronBarcode is a powerful C# barcode generation and scanning library that simplifies working with all type of barcodes.

IronBarcode

IronBarcode is a popular .NET barcode generation and scanning library. It provides a simple way to generate barcodes and scan them from saved images or captured frames from live video feeds. With IronBarcode, you can read and generate various barcode types, including QR codes, UPC, and more. It simplifies barcode-related tasks in C# applications, making it a valuable tool for developers.

Prerequisites

Before creating a Windows Forms Application for barcode scanning with IronBarcode, make sure you have the following prerequisites:

  • Visual Studio (or any C# development environment).
  • IronBarcode and OpenCVSharp4 packages.
  • Basic knowledge of C# programming.

Create a Windows Forms Application

  • Create a new Windows Forms Application in Visual Studio.

  • Configure the project by giving it a suitable name and click next.

Image description

  • Then, select latest .NET Framework for compatibility and click create.

Image description

  • In Form1.cs[Design] window, design your form with the necessary controls from the Toolbox.

  • Drag and drop the following controls from Toolbox and set necessary properties: a PictureBox(name: cameraFrame) for displaying the camera feed, a RichTextBox(name: barcodeInfoBox) for displaying barcode information, and labels for displaying some text.

  • Set the form title to Barcode Scanner and labels to your preferred text to provide a user-friendly interface. Here is the screenshot of the designer window with all the controls:

Image description

Install OpenCVSharp4 and IronBarcode

To work with the camera and perform barcode scanning, we will need to install OpenCVSharp4 and IronBarcode using the NuGet Package Manager from either tools menu or by right-clicking Solution Explorer:

  • Install OpenCVSharp4: In the NuGet Package Manager browse tab, search for "OpenCvSharp4.Windows". Install this package to access the camera.

Image description

  • Install IronBarcode: Now search for "IronBarCode" in the NuGet Package Manager and install it. IronBarcode will help with barcode decoding.

Image description

Steps to Scan with IronBarcode

After setting up everything, now its time to write the code for our Barcode reader application. Open Form1.cs file and follow the steps to correctly initialize camera and scan barcode formats easily using Iron software.

Step 1: Necessary Imports

Add the following imports at the the top of the file:

using OpenCvSharp;
using IronBarCode;
using IronSoftware.Drawing;
Enter fullscreen mode Exit fullscreen mode

Step 2: Declare Necessary Fields

Let's first declare the following fields in our Form1 class:

private VideoCapture videoCapture;
private Mat frame;
private AnyBitmap imageBitmap;
Enter fullscreen mode Exit fullscreen mode
  • private VideoCapture videoCapture;: This field represents the video capture device and is used to initialize and manage the camera feed. It allows us to capture frames from the camera.

  • private Mat frame;: The Mat class is part of OpenCVSharp and represents a matrix or an image frame. We use this field to store each frame captured from the camera.

  • private AnyBitmap imageBitmap;: AnyBitmap is an IronSoftware.Drawing specific class that represents an image that can be processed by IronBarcode. We'll use this field to convert the Mat frame into a format that IronBarcode can work with.

Step 3: Initialize the Camera Feed

In the Form1_Load event, initialize the camera feed using OpenCVSharp.VideoCapture class. The (0) argument specifies that the default camera should be used. Check if the camera is available, and if not, display an error message.

private void Form1_Load(object sender, EventArgs e)
{
    videoCapture = new VideoCapture(0);

    if (!videoCapture.IsOpened())
    {
        MessageBox.Show("Camera not found. Make sure the camera is connected.", "Camera Error");
        Close();
    }

    Application.Idle += new EventHandler(ProcessFrame);
}
Enter fullscreen mode Exit fullscreen mode

The code Application.Idle += new EventHandler(ProcessFrame); connects the ProcessFrame method to the Application.Idle event. When the application is idle, the method is automatically executed, making it suitable for continuous actions like real-time video frame processing.

Step 4: Process Camera Frames

Now, lets create an event handler ProcessFrame to continuously capture frames from the camera which will be triggered in the Form1_Load method when .Net barcode scanner application is idle. This handler is attached to the Application.Idle event as shown in previous step.

private void ProcessFrame(object sender, EventArgs e)
{
    frame = new Mat();
    videoCapture.Read(frame);

    if (!frame.Empty())
    {
        imageBitmap = new AnyBitmap(frame.ToBytes());
        cameraFrame.Image = imageBitmap;
    }
}

Enter fullscreen mode Exit fullscreen mode

In this above code, we're doing a few things:

  • frame = new Mat();: We use Mat frame object to hold an image (or frame) from the camera.

  • videoCapture.Read(frame);: The VideoCapture.Read() method in OpenCVSharp returns a bool value, which indicates whether a frame was successfully read from the video stream. If a frame was successfully read, the Read() method also returns the frame as a Mat object.

  • if (!frame.Empty()): We check if there's an actual image in the frame (sometimes the camera feed might be empty).

  • imageBitmap = new AnyBitmap(frame.ToBytes());: AnyBitmap(frame.ToBytes()) is responsible for converting an image, represented as a matrix (frame) first to bytes array, and then from there into a format that can be displayed in the PictureBox.

  • cameraFrame.Image = imageBitmap;: Finally, we display this imageBitmap in a cameraFrame named PictureBox.

On successful execution of the application, the camera will initialize when the Form is loaded. Here's how it looks:

Image description

Step 5: Scan for Barcodes using IronBarcode

The following code will help read barcodes from the captured frame and display it on screen:

BarcodeReaderOptions barcodeReaderOptions = new BarcodeReaderOptions();
barcodeReaderOptions.ExpectMultipleBarcodes = true;
barcodeReaderOptions.ExpectBarcodeTypes = BarcodeEncoding.All;
BarcodeResults barcodeReader = BarcodeReader.Read(imageBitmap, barcodeReaderOptions);
if (barcodeReader.Values().Length != 0)
{
    foreach (var value in barcodeReader.Values())
    {
        barcodeInfoBox.Text = value;
        Clipboard.SetText(value);
        MessageBox.Show("Barcode Information: " + value + 
            "\nNote: Clicking Ok will also copy the information to clipboard.",
            "Barcode Detected!",
            MessageBoxButtons.OK,
            MessageBoxIcon.Information);
    }
}
else
{
    barcodeInfoBox.Text = "No Barcode Detected";
}
Enter fullscreen mode Exit fullscreen mode

In the above source code:

  • We customize the barcode scanning process using BarcodeReaderOptions.

  • Setting ExpectMultipleBarcodes to true enables the reader to find multiple barcodes in a single frame. Setting it to false makes it focus on detecting just one barcode for faster scanning.

  • By setting ExpectBarcodeTypes to BarcodeEncoding.All, we ensure that the reader considers all possible barcode types. This boosts accuracy. There are other BarcodeReaderOptions which you can explore from this code examples page.

  • To read the barcodes, we use the Read() method provided by the BarcodeReader class.

  • We provide it with an AnyBitmap image file, which represents our camera frame, and the BarcodeReaderOptions we've configured.

  • The Read() method returns a BarcodeResults object, which contains the information about any detected barcodes in the camera frame.

  • If a barcode is detected, we display the barcode information in the barcodeInfoBox, and copy it to the clipboard for later use, and also show a MessageBox with the information.

  • If no barcode is detected, display a message on barcodeInfoBox indicating that no barcode was found.

This code will be placed in the ProcessFrame action method. Here is the complete code:

private void ProcessFrame(object sender, EventArgs e)
{
    frame = new Mat();
    videoCapture.Read(frame);

    if (!frame.Empty())
    {
        imageBitmap = new AnyBitmap(frame.ToBytes());
        cameraFrame.Image = imageBitmap;
        BarcodeReaderOptions barcodeReaderOptions = new BarcodeReaderOptions();
        barcodeReaderOptions.ExpectMultipleBarcodes = true;
        barcodeReaderOptions.ExpectBarcodeTypes = BarcodeEncoding.All;
        BarcodeResults barcodeReader = BarcodeReader.Read(imageBitmap, barcodeReaderOptions);
        if (barcodeReader.Values().Length != 0)
        {
            foreach (var value in barcodeReader.Values())
            {
                barcodeInfoBox.Text = value;
                Clipboard.SetText(value);
                MessageBox.Show("Barcode Information: " + value + 
                    "\nNote: Clicking Ok will also copy the information to clipboard.",
                    "Barcode Detected!",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }
        }
        else
        {
            barcodeInfoBox.Text = "No Barcode Detected";
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

To further enhance barcode scanners .NET applications for faster barcode scanning and to read barcodes from PDF document, imperfect scans, automatically managed multiple documents, please visit this read barcode tutorial link.

Step 6: Clean Up

Release the camera feed and dispose of the frame when the application is closing.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (videoCapture != null)
        videoCapture.Release();
    if (frame != null)
        frame.Dispose();
}
Enter fullscreen mode Exit fullscreen mode

Barcode Reader Output

1. Scan Real-Time Object with no Barcode

Image description

The above screenshot shows the application is working correctly and IronBarcode didn't detected any Barcode data.

2. Scan Real-Time Object with Barcode Image

Image description

The above screenshot displays the Barcode images information in the box as well as MessageBox. This ensures the accuracy and efficiency of IronBarcode and QR code library.

3. Scan Barcode Data from Image Files

Image description

This clearly shows IronBarcode is versatility enough for barcode reading from data matrix, binary data, either from camera feed or multiple images.

Conclusion

Creating a C# Barcode Scanner using IronBarcode and OpenCVSharp4 allows you to efficiently scan barcodes from live video feeds. By following the steps outlined above, you can build a Windows Forms Application that captures camera frames, processes them for barcodes, and provides user-friendly feedback.

This application can be a valuable tool for various industries, including retail, logistics, and inventory management. IronBarcode simplifies the process of reading barcodes, making it accessible to C# developers.

IronBarcode is free for development purposes but it can be licensed for commercial use. A 30-day free trail is also available to test out its complete functionality. You can download the software from here.

Top comments (0)