如何使用OCR在C#中讀取條碼和QR碼

如何使用IronOCR在C#中讀取條碼和QR碼

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

IronOCR通過在配置中設定ReadBarCodes = true來讀取C#中的條碼和QR碼。 此單一設定可自動從PDF和圖像中提取條碼值,與常規文字識別一起,支持超過20種條碼格式,包括QR碼、Code 128和Data Matrix。

快速入門:即時從PDF中讀取條碼

通過一個設定啟用條碼檢測,並使用IronOCR掃描PDF。 下面的程式碼顯示如何開啟條碼讀取、處理PDF並檢索解碼值。

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/IronOcr

    PM > Install-Package IronOcr
  2. 複製並運行這段程式碼片段。

    var result = new IronOcr.IronTesseract() { Configuration = new IronOcr.TesseractConfiguration { ReadBarCodes = true } }.Read(new IronOcr.OcrPdfInput("document.pdf"));
    foreach(var bc in result.Barcodes) Console.WriteLine(bc.Value);
  3. 部署以在您的實時環境中測試

    今天就開始在您的專案中使用IronOCR,透過免費試用

    arrow pointer


如何從PDF文件中讀取條碼?

建立一個IronTesseract物件以執行讀取操作。 將ReadBarCodes屬性設置為true以啟用條碼檢測。 使用OcrPdfInput構造函式導入PDF文件。 使用Read方法對導入的PDF執行OCR。

以下是一個使用該PDF文件的範例:

:path=/static-assets/ocr/content-code-examples/how-to/barcodes-read-barcodes.cs
using IronOcr;
using System;

// Instantiate IronTesseract
IronTesseract ocrTesseract = new IronTesseract();

// Enable barcode reading
ocrTesseract.Configuration.ReadBarCodes = true;

// Add PDF
using var imageInput = new OcrPdfInput("pdfWithBarcodes.pdf");

// Perform OCR
OcrResult ocrResult = ocrTesseract.Read(imageInput);

// Output detected barcodes and text values
Console.WriteLine("Extracted text:");
Console.WriteLine(ocrResult.Text);
Console.WriteLine("Extracted barcodes:");
foreach (var barcode in ocrResult.Barcodes)
{
    Console.WriteLine(barcode.Value);
}
Imports IronOcr
Imports System

' Instantiate IronTesseract
Private ocrTesseract As New IronTesseract()

' Enable barcode reading
ocrTesseract.Configuration.ReadBarCodes = True

' Add PDF
Dim imageInput = New OcrPdfInput("pdfWithBarcodes.pdf")

' Perform OCR
Dim ocrResult As OcrResult = ocrTesseract.Read(imageInput)

' Output detected barcodes and text values
Console.WriteLine("Extracted text:")
Console.WriteLine(ocrResult.Text)
Console.WriteLine("Extracted barcodes:")
For Each barcode In ocrResult.Barcodes
	Console.WriteLine(barcode.Value)
Next barcode
$vbLabelText   $csharpLabel
IronOCR除錯輸出顯示從PDF中提取的文字和三個條碼(A、B、C),具有商業檔案。

多個條碼值顯示在條碼下方,並包含在提取的文字中。

為什麼IronOCR會提取文字和條碼值?

IronOCR的雙重提取提供了全面的文件分析。 在處理同時包含文字和條碼的文件時,此程式庫會執行標準OCR文字提取,同時解碼條碼符號。 此一體化方法消除了多次處理傳遞或單獨程式庫的需求。

文字提取捕獲人類可讀元素,而條碼檢測識別並解碼機器可讀資料。 這有益於如發票、運送標籤或庫存報告等檔案,其中條碼值與印刷文字相對應。 Barcodes集合存取條碼資料。

支持哪些條碼格式?

IronOCR支持超過20種條碼格式:

1D條碼:

  • Code 128、Code 39、Code 93
  • EAN-13、EAN-8
  • UPC-A、UPC-E
  • Codabar
  • ITF(Interleaved 2 of 5)
  • MSI
  • Plessey

2D條碼:

  • QR Code
  • Data Matrix
  • PDF417
  • Aztec Code
  • MaxiCode

對於像讀取MICR支票或處理身份文件等專門應用,IronOCR的條碼功能補充了其文字提取功能。

何時應該使用OCR來讀取條碼而不是專用的條碼程式庫?

選擇IronOCR的綜合條碼讀取適用於:

  1. 混合內容處理:檔案包含文字和條碼(運送標籤、發票或掃描文件
  2. 單一程式庫偏好:您希望最小化依賴並使用一個解決方案
  3. PDF處理:您已經在使用IronOCR進行PDF OCR文字提取
  4. 複雜文件佈局:文件中的條碼嵌入在文字區域或表格

在以下情況使用專用條碼程式庫:

  • 處理大量僅含條碼的圖像
  • 需要實時條碼掃描(< 50ms響應時間)
  • 與損壞或低質量條碼需專門算法的
  • 實施帶有相機優化的移動條碼掃描

如何從文件中讀取QR碼?

像條碼讀取一樣,將ReadBarCodes屬性設置為true。 除了文件路徑外,其他程式碼無需更改。 使用這個帶有QR碼的PDF文件:

:path=/static-assets/ocr/content-code-examples/how-to/barcodes-read-qr-codes.cs
using IronOcr;
using System;

// Instantiate IronTesseract
IronTesseract ocrTesseract = new IronTesseract();

// Enable barcode reading
ocrTesseract.Configuration.ReadBarCodes = true;

// Add PDF
using var imageInput = new OcrPdfInput("pdfWithQrCodes.pdf");

// Perform OCR
OcrResult ocrResult = ocrTesseract.Read(imageInput);

// Output detected barcodes and text values
Console.WriteLine("Extracted text:");
Console.WriteLine(ocrResult.Text);
Console.WriteLine("Extracted barcodes:");
foreach (var barcode in ocrResult.Barcodes)
{
    Console.WriteLine(barcode.Value);
}
Imports IronOcr
Imports System

' Instantiate IronTesseract
Private ocrTesseract As New IronTesseract()

' Enable barcode reading
ocrTesseract.Configuration.ReadBarCodes = True

' Add PDF
Dim imageInput = New OcrPdfInput("pdfWithQrCodes.pdf")

' Perform OCR
Dim ocrResult As OcrResult = ocrTesseract.Read(imageInput)

' Output detected barcodes and text values
Console.WriteLine("Extracted text:")
Console.WriteLine(ocrResult.Text)
Console.WriteLine("Extracted barcodes:")
For Each barcode In ocrResult.Barcodes
	Console.WriteLine(barcode.Value)
Next barcode
$vbLabelText   $csharpLabel
IronOCR在Visual Studio中輸出展示從文件中成功提取的文字和解碼的QR碼A、B和C

為什麼相同的配置適用於條碼和QR碼?

IronOCR的綜合條碼檢測引擎將所有可機讀程式碼視為相等。 ReadBarCodes配置激活了一個綜合符號檢測器,該檢測器能夠識別1D(線性條碼)和2D(QR碼、Data Matrix)格式,而無需格式特定的設定。 此設計簡化了實施並減少配置複雜性。

檢測算法自動執行:

  • 基於模式識別確定符號型別
  • 應用適當的解碼算法
  • 處理方向和尺寸的變化
  • 返回一致格式的結果,不論條碼型別

這種方法反映了計算機視覺模型的工作方式—訓練多個格式以提供通用的檢測能力。

使用OCR讀取QR碼時有哪些常見問題?

處理QR碼時的常見挑戰包括:

  1. 解析度問題:PDF中的QR碼可能被降低到最小模塊大小以下。使用DPI設置確保足夠的解析度(建議至少300 DPI)。

  2. 圖像質量:掃描的QR碼通常會受到模糊、噪聲或變形的影響。 應用圖像校正篩選器以提高清晰度:
// Apply filters to improve QR code readability
ocrTesseract.Configuration.ReadBarCodes = true;
var input = new OcrImageInput("qr-code-scan.jpg");
input.DeNoise();
input.Sharpen();
input.EnhanceResolution();

var result = ocrTesseract.Read(input);
// Apply filters to improve QR code readability
ocrTesseract.Configuration.ReadBarCodes = true;
var input = new OcrImageInput("qr-code-scan.jpg");
input.DeNoise();
input.Sharpen();
input.EnhanceResolution();

var result = ocrTesseract.Read(input);
' Apply filters to improve QR code readability
ocrTesseract.Configuration.ReadBarCodes = True
Dim input As New OcrImageInput("qr-code-scan.jpg")
input.DeNoise()
input.Sharpen()
input.EnhanceResolution()

Dim result = ocrTesseract.Read(input)
$vbLabelText   $csharpLabel
  1. 方向問題:角度不正的QR碼可能無法正確解碼。 啟用頁面旋轉檢測以處理未對齊的文件。

  2. 混合內容干擾:疊加在QR碼上的文字或圖形可能會阻止檢測。 若有需要,使用裁剪區域來隔離QR碼所在區域。

如何提高QR碼識別的準確性?

使用以下技術優化QR碼識別:

  1. 預處理圖像:使用篩選精靈來確定最佳的增強設置:
:path=/static-assets/ocr/content-code-examples/how-to/barcodes-5.cs
// Enhanced QR code reading with preprocessing
var ocrTesseract = new IronTesseract();
ocrTesseract.Configuration.ReadBarCodes = true;

// Configure for better QR detection
var input = new OcrImageInput("document-with-qr.pdf");
input.TargetDPI = 300; // Ensure sufficient resolution
input.Binarize(); // Convert to black and white
input.DeNoise(); // Remove image artifacts

var result = ocrTesseract.Read(input);
Imports IronOcr

' Enhanced QR code reading with preprocessing
Dim ocrTesseract As New IronTesseract()
ocrTesseract.Configuration.ReadBarCodes = True

' Configure for better QR detection
Dim input As New OcrImageInput("document-with-qr.pdf")
input.TargetDPI = 300 ' Ensure sufficient resolution
input.Binarize() ' Convert to black and white
input.DeNoise() ' Remove image artifacts

Dim result = ocrTesseract.Read(input)
$vbLabelText   $csharpLabel
  1. 處理多頁文件:處理跨多頁有QR碼的多頁文件
// Process multi-page documents efficiently
using var pdfInput = new OcrPdfInput("multi-page-qr-document.pdf");
pdfInput.TargetDPI = 300;

var results = ocrTesseract.Read(pdfInput);
foreach (var page in results.Pages)
{
    Console.WriteLine($"Page {page.PageNumber}:");
    foreach (var barcode in page.Barcodes)
    {
        Console.WriteLine($"  QR Code: {barcode.Value}");
        Console.WriteLine($"  Location: X={barcode.X}, Y={barcode.Y}");
    }
}
// Process multi-page documents efficiently
using var pdfInput = new OcrPdfInput("multi-page-qr-document.pdf");
pdfInput.TargetDPI = 300;

var results = ocrTesseract.Read(pdfInput);
foreach (var page in results.Pages)
{
    Console.WriteLine($"Page {page.PageNumber}:");
    foreach (var barcode in page.Barcodes)
    {
        Console.WriteLine($"  QR Code: {barcode.Value}");
        Console.WriteLine($"  Location: X={barcode.X}, Y={barcode.Y}");
    }
}
Imports System

' Process multi-page documents efficiently
Using pdfInput As New OcrPdfInput("multi-page-qr-document.pdf")
    pdfInput.TargetDPI = 300

    Dim results = ocrTesseract.Read(pdfInput)
    For Each page In results.Pages
        Console.WriteLine($"Page {page.PageNumber}:")
        For Each barcode In page.Barcodes
            Console.WriteLine($"  QR Code: {barcode.Value}")
            Console.WriteLine($"  Location: X={barcode.X}, Y={barcode.Y}")
        Next
    Next
End Using
$vbLabelText   $csharpLabel
  1. 異步處理:為提高多文件處理的性能,使用異步方法
// Asynchronous QR code reading
var result = await ocrTesseract.ReadAsync(imageInput);
// Asynchronous QR code reading
var result = await ocrTesseract.ReadAsync(imageInput);
' Asynchronous QR code reading
Dim result = Await ocrTesseract.ReadAsync(imageInput)
$vbLabelText   $csharpLabel
  1. 除錯識別問題:啟用結果高亮顯示以可視化IronOCR檢測到的內容:
result.SaveAsHighlightedImage("qr-detection-debug.png");
result.SaveAsHighlightedImage("qr-detection-debug.png");
result.SaveAsHighlightedImage("qr-detection-debug.png")
$vbLabelText   $csharpLabel

大規模條碼處理的性能優化

在處理成千上萬張帶有條碼和QR碼的文件時,實施這些優化策略:

  1. 多執行緒處理:利用多執行緒處理以同時處理多份文件:
:path=/static-assets/ocr/content-code-examples/how-to/barcodes-9.cs
// Process multiple documents in parallel
var documents = new[] { "doc1.pdf", "doc2.pdf", "doc3.pdf" };
var results = documents.AsParallel().Select(doc =>
{
    var tesseract = new IronTesseract();
    tesseract.Configuration.ReadBarCodes = true;
    return tesseract.Read(new OcrPdfInput(doc));
}).ToList();
Imports IronTesseract

' Process multiple documents in parallel
Dim documents = {"doc1.pdf", "doc2.pdf", "doc3.pdf"}
Dim results = documents.AsParallel().Select(Function(doc)
    Dim tesseract = New IronTesseract()
    tesseract.Configuration.ReadBarCodes = True
    Return tesseract.Read(New OcrPdfInput(doc))
End Function).ToList()
$vbLabelText   $csharpLabel
  1. 記憶體管理:為長時間運行的操作使用中止標記
// Implement cancellation for large batch processing
using var cts = new CancellationTokenSource();
ocrTesseract.Configuration.CancellationToken = cts.Token;

// Cancel if processing takes too long
cts.CancelAfter(TimeSpan.FromMinutes(5));
// Implement cancellation for large batch processing
using var cts = new CancellationTokenSource();
ocrTesseract.Configuration.CancellationToken = cts.Token;

// Cancel if processing takes too long
cts.CancelAfter(TimeSpan.FromMinutes(5));
' Implement cancellation for large batch processing
Using cts As New CancellationTokenSource()
    ocrTesseract.Configuration.CancellationToken = cts.Token

    ' Cancel if processing takes too long
    cts.CancelAfter(TimeSpan.FromMinutes(5))
End Using
$vbLabelText   $csharpLabel
  1. 結果導出:將結果儲存為可搜尋的PDF以保持文字和條碼資料:
// Export results with embedded barcode values
result.SaveAsSearchablePdf("output-with-barcodes.pdf");
// Export results with embedded barcode values
result.SaveAsSearchablePdf("output-with-barcodes.pdf");
' Export results with embedded barcode values
result.SaveAsSearchablePdf("output-with-barcodes.pdf")
$vbLabelText   $csharpLabel

與業務應用的整合

IronOCR的條碼功能可與現有的.NET應用無縫整合。 常見的整合場景包括:

  • 庫存管理:從運送清單中提取產品程式碼
  • 文件存檔:根據內嵌條碼識別符索引掃描文件
  • 發票處理:將條碼SKU與財務文件中的行項目匹配
  • 醫療記錄:處理病人腕帶條碼與醫療表單

對於高批量處理條碼和QR碼的生產應用,考慮實施進度跟踪來監控處理狀態,並基於實際指標優化性能。

常見問題

如何在我的C#應用程式中啟用條碼讀取?

透過IronOCR,在TesseractConfiguration中設置ReadBarCodes = true以啟用條碼讀取。這一個設定激活了從PDF和影像中自動提取條碼值的功能,並支持超過20種條碼格式的文字識別。

我能夠從同一文件中讀取文字和條碼嗎?

可以,IronOCR執行雙重提取—它通過標準OCR捕獲人類可讀文字,同時解碼機器可讀條碼。OcrResult類將這些輸出分開,文字可通過Text屬性存取,條碼資料通過Barcodes集合存取。

可以檢測到哪些條碼格式?

IronOCR支持超過20種條碼格式,包括一維條碼(Code 128, Code 39, Code 93, EAN-13, EAN-8, UPC-A, UPC-E, Codabar, ITF, MSI, Plessey)和二維條碼(QR碼, Data Matrix, 等)。

如何從PDF文件中提取條碼?

建立一個IronTesseract物件,設置ReadBarCodes為true,使用OcrPdfInput建構式匯入PDF,然後使用Read方法。IronOCR將執行OCR並提取所有檢測到的條碼值,這些值可通過result.Barcodes集合存取。

我需要單獨的程式庫來進行文字OCR和條碼讀取嗎?

不需要,IronOCR的統一方法消除了多次處理過程或單獨程式庫的需求。它在執行標準OCR文字提取的同時,解碼條碼符號,用一次操作完成。

IronOCR支援多種語言嗎?

IronOCR支援多種語言,使其成為全球需要不同語言文字識別的應用程式的多功能工具。

IronOCR能整合到現有的應用程式中嗎?

IronOCR被設計成可以輕鬆地整合到現有應用程式中,使用C#允許開發人員以最小的努力為其軟體新增OCR功能。

使用IronOCR進行文件管理的好處是什麼?

使用IronOCR進行文件管理通過將掃描的文件轉換為可搜索和可編輯的文字來簡化工作流程,減少手動資料輸入的需求並提高文件的可存取性。

IronOCR如何提高資料精確性?

IronOCR通過其先進的識別算法和影像校正功能提高資料精確性,確保文字提取過程既可靠又精確。

IronOCR有免費試用版嗎?

有的,Iron Software提供IronOCR的免費試用版,允許使用者在做出購買決定前測試其功能和能力。

Curtis Chau
技術作家

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

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

準備開始了嗎?
Nuget 下載 6,136,090 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在滾動?

想要快速證明? PM > Install-Package IronOcr
執行範例 觀看您的圖像轉變為可搜尋文字。