跳至頁尾內容
使用IRONBARCODE

using C# 和網路攝影機建立條碼掃描器

使用C#的網路攝影機條碼掃描器消除了需要實體條碼掃描器的需求,將任何連接的攝影機轉變為功能強大的條碼閱讀器。 在這篇文章中,我們將引導您如何建立一個基於控制台的網路攝影機條碼掃描器,該掃描器能夠捕捉即時影片幀並即時解碼條碼和QR碼,這一切僅需幾行程式碼。

無論您是正在開發庫存系統原型、構建簽到機,還是對條碼掃描是如何工作感到好奇,本指南提供了可以立即運行的源程式碼。

現在開始使用IronBarcode。
green arrow pointer

網路攝影機能否取代專用條碼掃描器?

絕對可以。 任何標準的網路攝影機或連接到Windows、macOS或Linux機器的USB影片捕捉裝置,在搭配合適的軟體時,可以作為條碼掃描器使用。 該過程是通過攝像頭捕捉影片幀,將每個幀轉換成位圖圖像,然後將該圖像傳遞給條碼閱讀器庫進行解碼。

傳統的條碼掃描設置涉及到工具,如Dynamsoft Barcode Reader SDK或DirectShow.NET,通常需要您手動配置過濾圖、設置捕捉圖並搭建幀回調管道才能從相機提取幀。 IronBarcode大大簡化了這一過程,無需構建複雜的影片流基礎架構。 您只需提供圖像資料,BarcodeReader類即可處理其餘部分,支持從標準條碼到QR碼的一切,僅需單個讀取方法。

如何設置攝像頭並安裝依賴項?

要將影片幀從網路攝影機引入到.NET控制台應用程式中,需要一個攝像頭存取程式庫。 OpenCvSharp4是一個輕量級、跨平台的.NET包裝Opencv,使這一過程變得簡單明瞭。 與IronBarcode結合,它為您提供了一切所需,以建立實時條碼掃描器,而不需與低層級影片捕捉裝置枚舉或幀率配置作鬥爭。

通過NuGet安裝這兩個套件:

dotnet add package OpenCvSharp4.Windows, OpenCvSharp4.Extensions, BarCode

安裝完這三個套件後,您的專案將通過OpenCvSharp獲取攝影機存取權限,並通過IronBarcode進行條碼解碼。 無需配置額外的系統依賴項或外部SDK,只需安裝並開始使用。

如何捕捉影片幀並即時閱讀條碼資料?

以下程式碼範例建立了一個基於Visual Studio的控制台條碼掃描器,它開啟您的預設網路攝影機,連續捕捉幀並掃描每個幀以查找條碼。 當偵測到條碼時,資料會寫入控制台,並將幀保存為快照。

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

使用網路攝影機在C#中建立條碼掃描器:圖像1-使用我們的條碼掃描器在C#中

此程式碼使用頂層語句來保持清晰。 VideoCapture物件開啟第一個連接的攝像頭源並開始迴圈拉取幀。每個幀都從OpenCvSharp Mat轉換為Bitmap,然後包裝在AnyBitmap中,這是IronBarcode的BarcodeReader.Read方法所接受的跨平台圖像格式。

BarcodeReaderOptions物件控制掃描行為。 將Speed設置為ReadingSpeed.Faster可優化即時影片,以便獲取快速幀響應。 將ExpectBarcodeTypes屬性設置為BarcodeEncoding.All,這意味著掃描器將檢測到所有支持的格式,從Code 128和EAN-13到Data Matrix和QR碼。 如果您的用例僅涉及特定格式,縮小範圍將提高掃描性能。 欲了解更多配置選項,請查看BarcodeReaderOptions參考文件

foreach迴圈在返回集合中的每個BarcodeResult中迭代。 Value屬性包含解碼的條碼資料,而BarcodeType標識格式。 該方法返回BarcodeResults集合,使您在需要時更容易處理多個條碼

如何為不同的使用案例微調條碼閱讀器?

現實世界的條碼掃描通常涉及不完美條件、光線不足、傾斜角度或損壞的標籤。 IronBarcode的閱讀選項可讓您根據工作需要平衡速度與精準度。

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

多種條碼讀取輸出:以QR碼為例

使用網路攝影機在C#中建立條碼掃描器:圖像2-使用我們的條碼掃描器讀取QR碼

將Speed切換為ReadingSpeed.Detailed告訴解碼器應用更徹底的圖像分析,這是處理噪音或傾斜輸入資料的理想選擇。 啟用AutoRotate允許IronBarcode自動校正圖像中的旋轉條碼,這是當使用者以奇怪的角度在攝像頭前拿著物品時的常見場景。 這是IronBarcode作為QR碼庫及條碼閱讀器真正出眾的地方:其內建的圖像預處理可處理這些挑戰,不需要您連接外部圖像校正濾波器。

您也可以使用同一個BarcodeReader API從保存的圖像文件、PDF和多幀TIFF中掃描條碼,這使得它在網路攝影機使用案例之外也非常靈活。 如果您正在建立一個基於網路的掃描器,IronBarcode Blazor整合指南涵蓋了如何使用JavaScript互通通過瀏覽器進行網路攝影機掃描。

這種方法為何比其他方法簡單?

許多C#中的網路攝影機條碼掃描器教程依賴於多程式庫組合,通常是使用ZXing.NET進行解碼,搭配AForge.NETDirectShow.NET進行攝影機存取。 這種方法需要建立一個影片捕捉過濾圖,手動配置幀回調以從影片流中提取幀,並通過低層級Windows API處理裝置枚舉。Dynamsoft Barcode Reader SDK遵循類似的模式,需要DirectShow.NET支撐來存取攝像頭。

IronBarcode則切除這種複雜性。 條碼掃描邏輯完全存在於BarcodeReader.Read中,其接受Bitmap、byte陣列、文件路徑或Stream。 無需建立捕獲圖,無需對框架捕獲進行物件發送者和EventArgs e事件接線,只需交給它圖像資料即可獲取條碼資訊。 這意味著需要編寫的程式碼減少,需維護的依賴項減少,更多的時間可用於您程式中真正重要的功能。

對於在.NET Core、.NET Framework或.NET 8+上進行開發的團隊,IronBarcode在Windows、macOS、Linux、Docker、Azure和AWS上提供了一致的跨平台支持。 探索完整的功能集或者瀏覽其他程式碼範例以了解其他可能性。

準備好建立您自己的條碼掃描器了嗎?

當擁有合適的工具時,在C#中將網路攝影機轉變為條碼掃描器僅需最少的程式碼。 IronBarcode處理從標準條碼到QR碼的解碼重任,而OpenCvSharp則乾淨地管理攝影機存取。 一起,它們創造了一個易於構建、易於擴展並適合生產的掃描器。

開始免費試用以在您自己的專案中嘗試,或者當您準備好部署時探索授權選項

常見問題

如何在C#中使用網路攝影機建立條碼掃描器?

您可以在C#中使用IronBarcode和網路攝影機建立條碼掃描器。這涉及從網路攝影機擷取影片框架並即時解碼條碼和QR碼,僅需極少的程式碼。

使用網路攝影機進行條碼掃描有什麼好處?

使用網路攝影機進行條碼掃描省去對專用硬體的需求,讓任何連接的攝影機都可成為強大的條碼讀取器。這對於各種應用來說既經濟又多功能。

是否可以在C#中使用網路攝影機解碼QR碼?

是的,透過IronBarcode,您可以在C#中使用網路攝影機解碼QR碼。這個程式庫能擷取即時影片框架並流暢地處理以提取QR碼資料。

哪些應用程式能夠從C#中使用網路攝影機條碼掃描器中受益?

零售、庫存管理和物流等應用程式可以從C#中的網路攝影機條碼掃描器中受益。它為條碼和QR碼掃描提供了一種靈活且具成本效益的解決方案。

IronBarcode是否支援即時條碼解碼?

是的,IronBarcode支援即時條碼解碼。它處理來自網路攝影機的即時影片框架以立即解碼條碼和QR碼。

是否提供建構網路攝影機條碼掃描器的源程式碼?

是的,提供了於C#中建構基於控制台的網路攝影機條碼掃描器的完整源程式碼。這有助於開發者高效地理解和實現該解決方案。

使用IronBarcode與網路攝影機可以解碼哪些型別的條碼?

IronBarcode可以解碼多種型別的條碼,包括QR碼、UPC、EAN和Code 128等,使用網路攝影機在C#中進行解碼。

我需要具備先進的程式設計技能才能使用IronBarcode建構條碼掃描器嗎?

不,您不需要具備先進的程式設計技能即可使用IronBarcode建構條碼掃描器。這個過程僅涉及幾行程式碼,使其對於各種技能水平的開發者都是可行的。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話