Przejdź do treści stopki
KORZYSTANIE Z IRONBARCODE

Zbuduj czytnik kodów kreskowych używając kamery internetowej w C#

A barcode scanner using webcam in C# eliminates the need for physical barcode scanners by turning any connected camera into a powerful barcode reader. In this article, we'll walk you through building a console-based webcam barcode scanner that captures live video frames and decodes barcodes and QR codes in real time, all with just a few lines of code.

Whether you're prototyping an inventory system, building a check-in kiosk, or just curious about how barcode scanning works under the hood, this guide delivers working source code you can run immediately.

Zacznij z IronBarcode teraz.
green arrow pointer

Can a Webcam Replace a Dedicated Barcode Scanner?

Absolutely. Any standard web camera or USB video capture device attached to a Windows, macOS, or Linux machine can serve as a barcode scanner when paired with the right software. The process works by capturing video frames from the camera, converting each frame into a bitmap image, and then passing that image to a barcode reader library for decoding.

Traditional barcode scanning setups involving tools like the Dynamsoft Barcode Reader SDK or DirectShow.NET often require you to manually configure a filter graph, set up a capture graph, and wire together a frame callback pipeline just to get frames out of the camera. IronBarcode simplifies this dramatically, there's no need to build complex video stream infrastructure. You supply the image data, and the BarcodeReader class handles the rest, supporting everything from standard bar codes to QR codes out of a single read method.

How to Set Up the Camera and Install Dependencies?

Getting video frames from a webcam into a .NET console application requires a camera access library. OpenCvSharp4 is a lightweight, cross-platform .NET wrapper around OpenCV that makes this straightforward. Combined with IronBarcode, it gives you everything needed to create a real-time barcode scanner without wrestling with low-level video capture device enumeration or frame rate configuration.

Install both packages via NuGet:

dotnet add package OpenCvSharp4.Windows
dotnet add package OpenCvSharp4.Extensions
dotnet add package BarCode
dotnet add package OpenCvSharp4.Windows
dotnet add package OpenCvSharp4.Extensions
dotnet add package BarCode
```
dotnet add package OpenCvSharp4.Windows
dotnet add package OpenCvSharp4.Extensions
dotnet add package BarCode
```
$vbLabelText   $csharpLabel

With those three packages installed, your project gains camera access through OpenCvSharp and barcode decoding through IronBarcode. No additional system dependencies or external SDKs to configure, just install and go.

How to Capture Video Frames and Read Barcodes Data in Real Time?

The following code example creates a console-based barcode scanner in Visual Studio that opens your default webcam, captures frames continuously, and scans each one for barcodes. When a barcode is detected, the data is written to the console and the frame is saved as a snapshot

using OpenCvSharp;
using OpenCvSharp.Extensions;
using IronBarCode;
using IronSoftware.Drawing;
// Open the default camera (device index 0)
using var capture = new VideoCapture(0);
if (!capture.IsOpened())
{
    Console.WriteLine("No camera found. Check connected devices.");
    return;
}
// Configure the barcode reader for real-time scanning
var options = new BarcodeReaderOptions
{
    ExpectMultipleBarcodes = false,
    ExpectBarcodeTypes = BarcodeEncoding.All,
    Speed = ReadingSpeed.Faster
};
Console.WriteLine("Barcode scanner active. Press 'Q' to quit.");
using var frame = new Mat();
bool scanning = true;
while (scanning)
{
    capture.Read(frame);
    if (frame.Empty())
        continue;
    // Convert the captured frame to a bitmap for barcode processing
    var bitmap = BitmapConverter.ToBitmap(frame);
    var anyBitmap = new AnyBitmap(bitmap);
    // Scan the frame for barcodes
    var results = BarcodeReader.Read(anyBitmap, options);
    foreach (var result in results)
    {
        Console.WriteLine($"Barcode detected: {result.Value}");
        Console.WriteLine($"  Format: {result.BarcodeType}");
        // Save a snapshot of the frame where the barcode was found
        bitmap.Save("barcode_snapshot.png");
        Console.WriteLine("  Snapshot saved to barcode_snapshot.png");
    }
    // Check for quit key
    if (Cv2.WaitKey(1) == 'q')
        scanning = false;
}
Console.WriteLine("Scanner stopped.");
using OpenCvSharp;
using OpenCvSharp.Extensions;
using IronBarCode;
using IronSoftware.Drawing;
// Open the default camera (device index 0)
using var capture = new VideoCapture(0);
if (!capture.IsOpened())
{
    Console.WriteLine("No camera found. Check connected devices.");
    return;
}
// Configure the barcode reader for real-time scanning
var options = new BarcodeReaderOptions
{
    ExpectMultipleBarcodes = false,
    ExpectBarcodeTypes = BarcodeEncoding.All,
    Speed = ReadingSpeed.Faster
};
Console.WriteLine("Barcode scanner active. Press 'Q' to quit.");
using var frame = new Mat();
bool scanning = true;
while (scanning)
{
    capture.Read(frame);
    if (frame.Empty())
        continue;
    // Convert the captured frame to a bitmap for barcode processing
    var bitmap = BitmapConverter.ToBitmap(frame);
    var anyBitmap = new AnyBitmap(bitmap);
    // Scan the frame for barcodes
    var results = BarcodeReader.Read(anyBitmap, options);
    foreach (var result in results)
    {
        Console.WriteLine($"Barcode detected: {result.Value}");
        Console.WriteLine($"  Format: {result.BarcodeType}");
        // Save a snapshot of the frame where the barcode was found
        bitmap.Save("barcode_snapshot.png");
        Console.WriteLine("  Snapshot saved to barcode_snapshot.png");
    }
    // Check for quit key
    if (Cv2.WaitKey(1) == 'q')
        scanning = false;
}
Console.WriteLine("Scanner stopped.");
Imports OpenCvSharp
Imports OpenCvSharp.Extensions
Imports IronBarCode
Imports IronSoftware.Drawing

' Open the default camera (device index 0)
Using capture As New VideoCapture(0)
    If Not capture.IsOpened() Then
        Console.WriteLine("No camera found. Check connected devices.")
        Return
    End If

    ' Configure the barcode reader for real-time scanning
    Dim options As New BarcodeReaderOptions With {
        .ExpectMultipleBarcodes = False,
        .ExpectBarcodeTypes = BarcodeEncoding.All,
        .Speed = ReadingSpeed.Faster
    }
    Console.WriteLine("Barcode scanner active. Press 'Q' to quit.")

    Using frame As New Mat()
        Dim scanning As Boolean = True
        While scanning
            capture.Read(frame)
            If frame.Empty() Then
                Continue While
            End If

            ' Convert the captured frame to a bitmap for barcode processing
            Dim bitmap = BitmapConverter.ToBitmap(frame)
            Dim anyBitmap As New AnyBitmap(bitmap)

            ' Scan the frame for barcodes
            Dim results = BarcodeReader.Read(anyBitmap, options)
            For Each result In results
                Console.WriteLine($"Barcode detected: {result.Value}")
                Console.WriteLine($"  Format: {result.BarcodeType}")

                ' Save a snapshot of the frame where the barcode was found
                bitmap.Save("barcode_snapshot.png")
                Console.WriteLine("  Snapshot saved to barcode_snapshot.png")
            Next

            ' Check for quit key
            If Cv2.WaitKey(1) = AscW("q"c) Then
                scanning = False
            End If
        End While
    End Using
End Using

Console.WriteLine("Scanner stopped.")
$vbLabelText   $csharpLabel

Using Webcam for Barcode Scanning in C

Build a Barcode Scanner Using Webcam in C#: Image 1 - Using our barcode scanner using webcam in C#

This code uses top-level statements to keep things clean. The VideoCapture object opens the first connected camera source and begins pulling frames in a loop. Each frame is converted from an OpenCvSharp Mat to a Bitmap and then wrapped in an AnyBitmap, the cross-platform image format that IronBarcode's BarcodeReader.Read method accepts.

The BarcodeReaderOptions object controls the scanning behavior. Setting Speed to ReadingSpeed.Faster optimizes for real-time video where you need quick responses per frame. The ExpectBarcodeTypes property is set to BarcodeEncoding.All, meaning the scanner will detect every supported format, from Code 128 and EAN-13 to Data Matrix and QR codes. If your use case only involves a specific format, narrowing this down will boost scan performance. For more on configuring these options, check the BarcodeReaderOptions reference.

The foreach loop iterates over each BarcodeResult in the returned collection. The Value property contains the decoded barcode data, while BarcodeType identifies the format. The method returns a BarcodeResults collection, making it easy to process multiple barcodes if needed.

How to Fine-Tune the Barcode Reader for Different Use Cases?

Real-world barcode scanning often involves imperfect conditions, poor lighting, skewed angles, or damaged labels. IronBarcode's reader options let you balance speed against accuracy depending on what you're working with.

using IronBarCode;
// Optimized options for scanning QR codes from a camera feed
var qrOptions = new BarcodeReaderOptions
{
    ExpectMultipleBarcodes = true,
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.PDF417,
    Speed = ReadingSpeed.Detailed,
    AutoRotate = true
};
// Decode barcodes from a saved image captured by the webcam
var imageResults = BarcodeReader.Read("barcode_snapshot.png", qrOptions);
foreach (var barcode in imageResults)
{
    Console.WriteLine($"Data: {barcode.Value}");
    Console.WriteLine($"Type: {barcode.BarcodeType}");
    Console.WriteLine($"Page: {barcode.PageNumber}");
}
using IronBarCode;
// Optimized options for scanning QR codes from a camera feed
var qrOptions = new BarcodeReaderOptions
{
    ExpectMultipleBarcodes = true,
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.PDF417,
    Speed = ReadingSpeed.Detailed,
    AutoRotate = true
};
// Decode barcodes from a saved image captured by the webcam
var imageResults = BarcodeReader.Read("barcode_snapshot.png", qrOptions);
foreach (var barcode in imageResults)
{
    Console.WriteLine($"Data: {barcode.Value}");
    Console.WriteLine($"Type: {barcode.BarcodeType}");
    Console.WriteLine($"Page: {barcode.PageNumber}");
}
Imports IronBarCode

' Optimized options for scanning QR codes from a camera feed
Dim qrOptions As New BarcodeReaderOptions With {
    .ExpectMultipleBarcodes = True,
    .ExpectBarcodeTypes = BarcodeEncoding.QRCode Or BarcodeEncoding.PDF417,
    .Speed = ReadingSpeed.Detailed,
    .AutoRotate = True
}

' Decode barcodes from a saved image captured by the webcam
Dim imageResults = BarcodeReader.Read("barcode_snapshot.png", qrOptions)
For Each barcode In imageResults
    Console.WriteLine($"Data: {barcode.Value}")
    Console.WriteLine($"Type: {barcode.BarcodeType}")
    Console.WriteLine($"Page: {barcode.PageNumber}")
Next
$vbLabelText   $csharpLabel

Output for Reading Different Barcodes: Example with QR Code

Build a Barcode Scanner Using Webcam in C#: Image 2 - Reading QR code with our barcode scanner

Switching Speed to ReadingSpeed.Detailed tells the decoder to apply more thorough image analysis, which is ideal for handling noisy or skewed input data. Enabling AutoRotate allows IronBarcode to automatically correct rotated barcodes in the image, a common scenario when users hold items at odd angles in front of the camera. This is one of the areas where IronBarcode truly stands out as a QR code library and barcode reader: its built-in image preprocessing handles these challenges without requiring you to wire up external image correction filters.

You can also scan barcodes from saved image files, PDFs, and multi-frame TIFFs using the same BarcodeReader API, making it versatile well beyond webcam use cases. If you're building a web-based scanner instead, the IronBarcode Blazor integration guide covers webcam scanning through a browser using JavaScript interop.

What Makes This Approach Simpler Than Alternatives?

Many webcam barcode scanner tutorials in C# rely on multi-library combinations, typically ZXing.NET for decoding paired with AForge.NET or DirectShow.NET for camera access. That approach requires setting up a filter graph for video capture, manually configuring frame callbacks to extract frames from the video stream, and handling device enumeration through low-level Windows APIs. The Dynamsoft Barcode Reader SDK follows a similar pattern, requiring DirectShow.NET plumbing to access the webcam.

IronBarcode cuts through that complexity. The barcode scanning logic lives entirely in BarcodeReader.Read, which accepts a Bitmap, a byte array, a file path, or a Stream. There's no capture graph to build, no object sender and EventArgs e event wiring for frame capture, just hand it image data and get barcode information back. This means less code to write, fewer dependencies to maintain, and more time spent on the features that actually matter in your application.

For teams building across .NET Core, .NET Framework, or .NET 8+, IronBarcode provides consistent cross-platform support on Windows, macOS, Linux, Docker, Azure, and AWS. Explore the full feature set or browse additional code examples to see what else is possible.

Ready to Build Your Own Barcode Scanner?

Turning a webcam into a barcode scanner in C# takes minimal code when you have the right tools. IronBarcode handles the heavy lifting of decoding, from standard barcodes to QR codes, while OpenCvSharp manages camera access cleanly. Together, they create a scanner that's easy to build, easy to extend, and ready for production.

Start a free trial to try it with your own project, or explore licensing options when you're ready to deploy.

Często Zadawane Pytania

Jak mogę stworzyć skaner kodów kreskowych z użyciem kamery internetowej w C#?

Można stworzyć skaner kodów kreskowych z użyciem kamery internetowej w C# korzystając z IronBarcode. Obejmuje to przechwytywanie klatek wideo z kamery internetowej i dekodowanie kodów kreskowych oraz kodów QR w czasie rzeczywistym przy minimalnej ilości kodu.

Jakie są korzyści z używania kamery internetowej do skanowania kodów kreskowych?

Użycie kamery internetowej do skanowania kodów kreskowych eliminuje potrzebę stosowania dedykowanego sprzętu, pozwalając dowolnej podłączonej kamerze stać się potężnym czytnikiem kodów kreskowych. Jest to ekonomiczne i wszechstronne rozwiązanie dla różnych aplikacji.

Czy można dekodować kody QR za pomocą kamery internetowej w C#?

Tak, z IronBarcode można dekodować kody QR za pomocą kamery internetowej w C#. Biblioteka przechwytuje klatki wideo na żywo i przetwarza je, aby płynnie wyodrębnić dane z kodów QR.

Jakie aplikacje mogą skorzystać z kamery internetowej do skanowania kodów kreskowych w C#?

Aplikacje w sprzedaży detalicznej, zarządzaniu zapasami i logistyce mogą skorzystać z kamery internetowej do skanowania kodów kreskowych w C#. Zapewnia to elastyczne i ekonomiczne rozwiązanie do skanowania kodów kreskowych i kodów QR.

Czy IronBarcode obsługuje dekodowanie kodów kreskowych w czasie rzeczywistym?

Tak, IronBarcode obsługuje dekodowanie kodów kreskowych w czasie rzeczywistym. Przetwarza klatki wideo na żywo z kamery internetowej, aby natychmiast dekodować kody kreskowe i kody QR.

Czy kod źródłowy do budowy skanera kodów kreskowych z użyciem kamery internetowej jest dostępny?

Tak, zapewniony jest pełny kod źródłowy do budowy opartego na konsoli skanera kodów kreskowych z użyciem kamery internetowej w C#. To pomaga programistom zrozumieć i efektywnie wdrożyć rozwiązanie.

Jakie rodzaje kodów kreskowych można dekodować za pomocą IronBarcode z kamerą internetową?

IronBarcode może dekodować różne rodzaje kodów kreskowych, w tym kody QR, UPC, EAN i Code 128, między innymi, z użyciem kamery internetowej w C#.

Czy potrzebuję zaawansowanych umiejętności programistycznych, aby stworzyć skaner kodów kreskowych z użyciem IronBarcode?

Nie, nie potrzebujesz zaawansowanych umiejętności programistycznych, aby stworzyć skaner kodów kreskowych z użyciem IronBarcode. Proces obejmuje kilka linijek kodu, dzięki czemu jest dostępny dla programistów o wszystkich poziomach zaawansowania.

Jordi Bardia
Inżynier oprogramowania
Jordi jest najbardziej biegły w Pythonie, C# i C++. Kiedy nie wykorzystuje swoich umiejętności w Iron Software, programuje gry. Dzieląc odpowiedzialność za testowanie produktów, rozwój produktów i badania, Jordi wnosi ogromną wartość do ciągłej poprawy produktów. Różnorodne doświadczenia ...
Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie