如何在 C# 中讀取條碼

C# 條碼掃描器:在 .NET 應用程式中讀取條碼和二維碼

This article was translated from English: Does it need improvement?
Translated
View the article in English

需要在 .NET 應用程式中快速掃描條碼或二維碼嗎? 無論您是處理完美的數位影像還是具有挑戰性的真實世界照片,IronBarcode 都能讓條碼讀取變得簡單可靠。 本指南將透過您可以立即使用的實際範例,向您展示如何在 C# 中實現條碼掃描。

快速入門:立即從檔案中讀取條碼

這個簡單的範例向您展示了IronBarcode入門是多麼容易。 只需一行程式碼,即可從圖像檔案中讀取條碼——無需複雜的設定。

Nuget Icon立即開始使用 NuGet 建立 PDF 檔案:

  1. 使用 NuGet 套件管理器安裝 IronBarcode

    PM > Install-Package BarCode

  2. 複製並運行這段程式碼。

    var results = IronBarCode.BarcodeReader.Read("path/to/barcode.png");
  3. 部署到您的生產環境進行測試

    立即開始在您的專案中使用 IronBarcode,免費試用!
    arrow pointer

如何在我的.NET專案中安裝IronBarcode?

IronBarcode 可以透過 NuGet 套件管理器輕鬆安裝,也可以直接下載 DLL 檔案進行安裝。 建議使用 NuGet 安裝,因為它能夠自動管理依賴項和更新。

Install-Package BarCode

安裝完成後,在 C# 檔案中加入using IronBarCode;即可存取條碼掃描功能。 有關不同開發環境下的詳細安裝說明,請查看我們的安裝指南

如何使用 C# 讀取我的第一個條碼?

使用 IronBarcode 讀取條碼只需要一行程式碼。 此庫可自動偵測條碼格式並擷取所有編碼資料。

Code128 barcode ready for scanning - contains text 'https://ironsoftware.com/csharp/barcode/' IronBarcode 可以立即讀取的標準 Code128 條碼
using IronBarCode;
using System;

// Read barcodes from the image file - supports PNG, JPG, BMP, GIF, and more
BarcodeResults results = BarcodeReader.Read("GetStarted.png");

// Check if any barcodes were detected
if (results != null && results.Count > 0)
{
    // Process each barcode found in the image
    foreach (BarcodeResult result in results)
    {
        // Extract the text value from the barcode
        Console.WriteLine("Barcode detected! Value: " + result.Text);

        // Additional properties available:
        // result.BarcodeType - The format (Code128, QR, etc.)
        // result.BinaryValue - Raw binary data if applicable
        // result.Confidence - Detection confidence score
    }
}
else
{
    Console.WriteLine("No barcodes detected in the image.");
}
using IronBarCode;
using System;

// Read barcodes from the image file - supports PNG, JPG, BMP, GIF, and more
BarcodeResults results = BarcodeReader.Read("GetStarted.png");

// Check if any barcodes were detected
if (results != null && results.Count > 0)
{
    // Process each barcode found in the image
    foreach (BarcodeResult result in results)
    {
        // Extract the text value from the barcode
        Console.WriteLine("Barcode detected! Value: " + result.Text);

        // Additional properties available:
        // result.BarcodeType - The format (Code128, QR, etc.)
        // result.BinaryValue - Raw binary data if applicable
        // result.Confidence - Detection confidence score
    }
}
else
{
    Console.WriteLine("No barcodes detected in the image.");
}
$vbLabelText   $csharpLabel

BarcodeReader.Read方法傳回一個BarcodeResults集合,其中包含所有偵測到的條碼。 每個BarcodeResult都提供對條碼的文字值、格式類型、位置座標和二進位資料的存取。 這種方法可以與常見的條碼格式無縫配合,包括 Code128、Code39、QR 碼和 Data Matrix 碼。

哪些方法可以幫助讀取難以辨識或損壞的條碼?

現實世界中的條碼掃描經常會遇到影像不完美的情況——角度傾斜、光線不足或部分損壞。 IronBarcode 的進階選項可以有效應對這些挑戰。

using IronBarCode;

// Configure advanced reading options for difficult barcodes
BarcodeReaderOptions options = new BarcodeReaderOptions
{
    // Speed settings: Faster, Balanced, Detailed, ExtremeDetail
    // ExtremeDetail performs deep analysis for challenging images
    Speed = ReadingSpeed.ExtremeDetail,

    // Specify expected formats to improve performance
    // Use bitwise OR (|) to combine multiple formats
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,

    // Maximum number of barcodes to find (0 = unlimited)
    MaxParallelThreads = 4,

    // Crop region for faster processing of specific areas
    CropArea = null // Or specify a Rectangle
};

// Apply options when reading
BarcodeResults results = BarcodeReader.Read("TryHarderQR.png", options);

// Process detected barcodes
foreach (var barcode in results)
{
    Console.WriteLine($"Format: {barcode.BarcodeType}, Value: {barcode.Text}");
}
using IronBarCode;

// Configure advanced reading options for difficult barcodes
BarcodeReaderOptions options = new BarcodeReaderOptions
{
    // Speed settings: Faster, Balanced, Detailed, ExtremeDetail
    // ExtremeDetail performs deep analysis for challenging images
    Speed = ReadingSpeed.ExtremeDetail,

    // Specify expected formats to improve performance
    // Use bitwise OR (|) to combine multiple formats
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,

    // Maximum number of barcodes to find (0 = unlimited)
    MaxParallelThreads = 4,

    // Crop region for faster processing of specific areas
    CropArea = null // Or specify a Rectangle
};

// Apply options when reading
BarcodeResults results = BarcodeReader.Read("TryHarderQR.png", options);

// Process detected barcodes
foreach (var barcode in results)
{
    Console.WriteLine($"Format: {barcode.BarcodeType}, Value: {barcode.Text}");
}
$vbLabelText   $csharpLabel
QR code rotated 45 degrees demonstrating IronBarcode's rotation handling IronBarcode 使用進階選項成功讀取了旋轉後的二維碼

ExpectBarcodeTypes屬性透過將搜尋限制在特定格式內,顯著提高了效能。 為了最大限度地提高處理問題影像的精確度,請將影像濾波器與自動旋轉功能結合使用:

using IronBarCode;

BarcodeReaderOptions options = new BarcodeReaderOptions
{
    // Apply image processing filters to enhance readability
    ImageFilters = new ImageFilterCollection
    {
        new AdaptiveThresholdFilter(9, 0.01f), // Handles varying lighting
        new ContrastFilter(2.0f),               // Increases contrast
        new SharpenFilter()                     // Reduces blur
    },

    // Automatically rotate to find barcodes at any angle
    AutoRotate = true,

    // Use multiple CPU cores for faster processing
    Multithreaded = true
};

BarcodeResults results = BarcodeReader.Read("TryHarderQR.png", options);

foreach (var result in results)
{
    Console.WriteLine($"Detected {result.BarcodeType}: {result.Text}");
    Console.WriteLine($"Confidence: {result.Confidence}%");
    Console.WriteLine($"Position: X={result.X}, Y={result.Y}");
}
using IronBarCode;

BarcodeReaderOptions options = new BarcodeReaderOptions
{
    // Apply image processing filters to enhance readability
    ImageFilters = new ImageFilterCollection
    {
        new AdaptiveThresholdFilter(9, 0.01f), // Handles varying lighting
        new ContrastFilter(2.0f),               // Increases contrast
        new SharpenFilter()                     // Reduces blur
    },

    // Automatically rotate to find barcodes at any angle
    AutoRotate = true,

    // Use multiple CPU cores for faster processing
    Multithreaded = true
};

BarcodeResults results = BarcodeReader.Read("TryHarderQR.png", options);

foreach (var result in results)
{
    Console.WriteLine($"Detected {result.BarcodeType}: {result.Text}");
    Console.WriteLine($"Confidence: {result.Confidence}%");
    Console.WriteLine($"Position: X={result.X}, Y={result.Y}");
}
$vbLabelText   $csharpLabel

IronBarcode 的這些進階功能使其成為掃描照片、監視器或行動裝置拍攝的影像中條碼的理想選擇,尤其適用於影像品質差異很大的情況。

如何掃描PDF文件中的多個條碼?

PDF條碼掃描對於處理發票、出貨標籤和庫存文件至關重要。 IronBarcode 可以有效率地讀取每一頁上的所有條碼。

從PDF檔中讀取條碼

using System;
using IronBarCode;

try
{
    // Scan all pages of a PDF for barcodes
    BarcodeResults results = BarcodeReader.ReadPdf("MultipleBarcodes.pdf");

    if (results != null && results.Count > 0)
    {
        foreach (var barcode in results)
        {
            // Access barcode data and metadata
            string value = barcode.Text;
            int pageNumber = barcode.PageNumber;
            BarcodeEncoding format = barcode.BarcodeType;
            byte[] binaryData = barcode.BinaryValue;

            // Extract barcode image if needed
            System.Drawing.Bitmap barcodeImage = barcode.BarcodeImage;

            Console.WriteLine($"Found {format} on page {pageNumber}: {value}");
        }
    }
    else
    {
        Console.WriteLine("No barcodes found in the PDF.");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Error reading PDF: {ex.Message}");
}
using System;
using IronBarCode;

try
{
    // Scan all pages of a PDF for barcodes
    BarcodeResults results = BarcodeReader.ReadPdf("MultipleBarcodes.pdf");

    if (results != null && results.Count > 0)
    {
        foreach (var barcode in results)
        {
            // Access barcode data and metadata
            string value = barcode.Text;
            int pageNumber = barcode.PageNumber;
            BarcodeEncoding format = barcode.BarcodeType;
            byte[] binaryData = barcode.BinaryValue;

            // Extract barcode image if needed
            System.Drawing.Bitmap barcodeImage = barcode.BarcodeImage;

            Console.WriteLine($"Found {format} on page {pageNumber}: {value}");
        }
    }
    else
    {
        Console.WriteLine("No barcodes found in the PDF.");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Error reading PDF: {ex.Message}");
}
$vbLabelText   $csharpLabel

在顯示控制台輸出的 PDF 頁面中偵測到多個條碼 控制台輸出顯示在不同的 PDF 頁面中發現了多個條碼

對於特定頁面範圍或進階 PDF 處理,請使用BarcodeReaderOptions

// Read only specific pages to improve performance
BarcodeReaderOptions pdfOptions = new BarcodeReaderOptions
{
    // Scan pages 1-5 only
    PageNumbers = new[] { 1, 2, 3, 4, 5 },

    // PDF-specific settings
    PdfDpi = 300, // Higher DPI for better accuracy
    ReadBehindVectorGraphics = true
};

BarcodeResults results = BarcodeReader.ReadPdf("document.pdf", pdfOptions);
// Read only specific pages to improve performance
BarcodeReaderOptions pdfOptions = new BarcodeReaderOptions
{
    // Scan pages 1-5 only
    PageNumbers = new[] { 1, 2, 3, 4, 5 },

    // PDF-specific settings
    PdfDpi = 300, // Higher DPI for better accuracy
    ReadBehindVectorGraphics = true
};

BarcodeResults results = BarcodeReader.ReadPdf("document.pdf", pdfOptions);
$vbLabelText   $csharpLabel

如何處理多幀TIFF影像?

多幀 TIFF 檔案(常見於文件掃描和傳真係統)與 PDF 文件一樣,都得到了全面的支援。

包含多個跨幀條碼的多幀 TIFF 文件 一個多幀 TIFF 文件,不同幀上帶有條碼。

using IronBarCode;

// TIFF files are processed similarly to regular images
// Each frame is scanned automatically
BarcodeResults multiFrameResults = BarcodeReader.Read("Multiframe.tiff");

foreach (var result in multiFrameResults)
{
    // Access frame-specific information
    int frameNumber = result.PageNumber; // Frame number in TIFF
    string barcodeValue = result.Text;

    Console.WriteLine($"Frame {frameNumber}: {barcodeValue}");

    // Save individual barcode images if needed
    result.BarcodeImage?.Save($"barcode_frame_{frameNumber}.png");
}
using IronBarCode;

// TIFF files are processed similarly to regular images
// Each frame is scanned automatically
BarcodeResults multiFrameResults = BarcodeReader.Read("Multiframe.tiff");

foreach (var result in multiFrameResults)
{
    // Access frame-specific information
    int frameNumber = result.PageNumber; // Frame number in TIFF
    string barcodeValue = result.Text;

    Console.WriteLine($"Frame {frameNumber}: {barcodeValue}");

    // Save individual barcode images if needed
    result.BarcodeImage?.Save($"barcode_frame_{frameNumber}.png");
}
$vbLabelText   $csharpLabel

BarcodeReaderOptions也適用於 TIFF 處理,包括影像濾鏡和旋轉設定。 有關 TIFF 處理場景的詳細說明,請參閱我們的影像處理教學

我能否利用多執行緒加快處理速度?

並行處理能大幅提升多文件處理效率。 IronBarcode 會自動利用可用的 CPU 核心,以達到最佳效能。

using IronBarCode;

// List of documents to process - mix of formats supported
var documentBatch = new[] 
{ 
    "invoice1.pdf", 
    "shipping_label.png", 
    "inventory_sheet.tiff",
    "product_catalog.pdf"
};

// Configure for batch processing
BarcodeReaderOptions batchOptions = new BarcodeReaderOptions
{
    // Enable parallel processing across documents
    Multithreaded = true,

    // Limit threads if needed (0 = use all cores)
    MaxParallelThreads = Environment.ProcessorCount,

    // Apply consistent settings to all documents
    Speed = ReadingSpeed.Balanced,
    ExpectBarcodeTypes = BarcodeEncoding.All
};

// Process all documents in parallel
BarcodeResults batchResults = BarcodeReader.Read(documentBatch, batchOptions);

// Group results by source document
var resultsByDocument = batchResults.GroupBy(r => r.Filename);

foreach (var docGroup in resultsByDocument)
{
    Console.WriteLine($"\nDocument: {docGroup.Key}");
    foreach (var barcode in docGroup)
    {
        Console.WriteLine($"  - {barcode.BarcodeType}: {barcode.Text}");
    }
}
using IronBarCode;

// List of documents to process - mix of formats supported
var documentBatch = new[] 
{ 
    "invoice1.pdf", 
    "shipping_label.png", 
    "inventory_sheet.tiff",
    "product_catalog.pdf"
};

// Configure for batch processing
BarcodeReaderOptions batchOptions = new BarcodeReaderOptions
{
    // Enable parallel processing across documents
    Multithreaded = true,

    // Limit threads if needed (0 = use all cores)
    MaxParallelThreads = Environment.ProcessorCount,

    // Apply consistent settings to all documents
    Speed = ReadingSpeed.Balanced,
    ExpectBarcodeTypes = BarcodeEncoding.All
};

// Process all documents in parallel
BarcodeResults batchResults = BarcodeReader.Read(documentBatch, batchOptions);

// Group results by source document
var resultsByDocument = batchResults.GroupBy(r => r.Filename);

foreach (var docGroup in resultsByDocument)
{
    Console.WriteLine($"\nDocument: {docGroup.Key}");
    foreach (var barcode in docGroup)
    {
        Console.WriteLine($"  - {barcode.BarcodeType}: {barcode.Text}");
    }
}
$vbLabelText   $csharpLabel

這種平行方法可以同時處理文檔,在多核心系統上可將總掃描時間縮短高達 75%。 對於企業級條碼處理,請查閱我們的效能最佳化指南

概括

IronBarcode 將複雜的條碼掃描轉換為簡單的 C# 程式碼。 無論您是建立庫存系統、文件處理器還是行動應用程序,該庫都能處理從完美的數位條碼到具有挑戰性的現實世界採集的一切。

主要功能涵蓋:

  • 從影像中讀取單行條碼
  • 針對損壞或旋轉條碼的進階選項
  • 全面掃描 PDF 和 TIFF 文檔
  • 高效能多執行緒批次處理
    支援所有主流條碼格式

延伸閱讀

利用以下資源擴展您的條碼處理能力:

條碼產生教學課程- 建立自訂條碼

原始碼下載

請自行執行以下範例:

-教程 GitHub 倉庫

準備好在您的應用程式中實現條碼掃描了嗎? 立即開始免費試用,並將專業的條碼讀取功能加入您的.NET專案。

!{--01001100010010010100001001010010010000010101001001011001010 111110100011101000101010101010001011111010100110101010001000001 010100100101010001000101010001000101111101010111010010010101010 001001000010111110101000001010101000010010000101111101010000010 1001001001111010001000101010101000011010101010001011111010101000101001001001001010101010001010010010010010100001010101010101 010101011000010101000100010101001110010001000101010001000101111101000010010011000100111110100010010011000100111100

常見問題解答

如何在.NET專案中安裝條碼讀取庫?

您可以透過 NuGet 套件管理器使用指令dotnet add package BarCode安裝 IronBarcode 函式庫,也可以透過 Visual Studio 的 NuGet 介面安裝。此外,您也可以下載 DLL 檔案進行手動安裝。

如何使用 C# 從影像中讀取條碼?

使用 IronBarcode 的BarcodeReader.Read方法,只需一行程式碼: var results = BarcodeReader.Read('image.png');此方法偵測並讀取影像中存在的所有條碼格式。

是否可以偵測單一影像或文件中的多個條碼?

是的,IronBarcode 可以自動偵測和讀取影像、PDF 或多幀 TIFF 中的多個條碼,並將每個條碼的值、類型和位置傳回BarcodeResults集合中。

如何使用 C# 讀取 PDF 檔案中的條碼?

使用 IronBarcode 的BarcodeReader.ReadPdf方法掃描 PDF 文件的所有頁面: var results = BarcodeReader.ReadPdf('document.pdf');每個結果都包含找到條碼的頁碼。

如果條碼圖像模糊或旋轉,我該怎麼辦?

配置BarcodeReaderOptions以處理複雜影像,方法是將AutoRotate = true ,並套用SharpenFilterAdaptiveThresholdFilter等影像濾鏡。使用Speed = ExtremeDetail可獲得更高的精確度。

.NET 應用程式支援哪些條碼格式?

IronBarcode 支援所有主流條碼格式,例如 QR 碼、Code 128、Code 39、EAN-13、UPC-A、Data Matrix、PDF417 等。使用BarcodeEncoding.All可以掃描任何支援的格式。

如何提高 C# 應用程式中的條碼掃描效能?

透過使用ExpectBarcodeTypes指定預期條碼類型、啟用多執行緒處理以及選擇合適的Speed設定來提高效能。對於批次任務,請使用帶有檔案路徑的BarcodeReader.Read方法。

處理條碼讀取錯誤的建議方法是什麼?

將條碼讀取操作封裝在 try-catch 程式碼區塊中,並驗證結果是否為空。 IronBarcode 提供詳細的錯誤資訊和一個置信度屬性,用於指示檢測的可靠性。

條碼掃描後,我可以擷取條碼影像嗎?

是的,IronBarcode 的BarcodeResult包含一個BarcodeImage屬性,其中包含偵測到的條碼的 Bitmap,可以單獨儲存或處理。

如何讀取PDF文件中特定頁面的條碼?

BarcodeReaderOptions中設定PageNumbers屬性以指定頁碼: options.PageNumbers = new[] {1, 2, 3};這樣可以只掃描指定的頁碼,從而優化效能。

.NET 中的條碼掃描相容於哪些影像格式?

IronBarcode支援掃描PNG、JPEG、BMP、GIF、TIFF(包括多幀)和PDF等格式的影像。您可以從檔案路徑、流或位元組數組載入圖像。

如何在C#中存取掃描條碼中的二進位資料?

利用BarcodeResultBinaryValue屬性來取得原始二進位數據,這對於包含非文字資料(例如壓縮資訊或二進位協定)的條碼尤其有用。

Jacob Mellor,Team Iron 首席技術官
首席技術長

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。

準備好開始了嗎?
Nuget 下載 2,035,202 | 版本: 2025.12 剛剛發布