IRONSOFTWAREHOME
影片

從Dynamsoft Barcode Reader遷移到IronBarcode

Curtis Chau
Curtis Chau
Updated: 2026年8月1日

大多數從Dynamsoft Barcode Reader遷移到IronBarcode的開發人員屬於兩類之一:那些因Dynamsoft的聲譽而選擇它,卻發現相機中心的API不適合文件處理使用案例的人,以及那些執行在氣隙或Docker環境中造成生產事故的授權伺服器依賴性的人。

如果您是第一類,遷移將移除外部PDF渲染庫、每頁渲染迴圈以及錯誤程式碼授權模式。 如果您是第二類,遷移將移除InitLicense網路調用、離線授權內容包及刷新周期,以及來自您的Docker或VPC配置的出站網路政策。 無論哪種方式,程式碼庫在此遷移後會變得更短。

這份指南誠實地告訴您會失去什麼:如果您的應用程式處理即時相機畫面,Dynamsoft的Capture Vision管線適合那種工作負荷,而IronBarcode不是正確的替代品。 這份遷移指南適用於伺服器端文件處理、文件工作流程以及授權伺服器存取存在問題的環境。

步驟1:更換NuGet套件

dotnet remove package Dynamsoft.DotNet.BarcodeReader.Bundle
dotnet add package BarCode
SHELL

如果您的專案中也特別為Dynamsoft新增了PDF渲染庫(PdfiumViewer是最常見的),那也可以移除:

# Remove if added only for Dynamsoft PDF support
dotnet remove package PdfiumViewer
dotnet remove package PdfiumViewer.Native.x86_64.v8-xfa
SHELL

步驟2:替換授權初始化

這是最直接簡化的地方。 Dynamsoft模式需要在每次啟動時進行錯誤程式碼檢查和異常處理:

之前—Dynamsoft:

using Dynamsoft.License;
using Dynamsoft.Core;

// Must run before any barcode operations
int errorCode = LicenseManager.InitLicense("YOUR-DYNAMSOFT-KEY", out string errorMsg);
if (errorCode != (int)EnumErrorCode.EC_OK)
    throw new InvalidOperationException($"License validation failed [{errorCode}]: {errorMsg}");

之後 — IronBarcode:

// NuGet: dotnet add package BarCode
using IronBarCode;

// Local validation — no network call, no error code
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";

在ASP.NET Core應用程式中,將此新增到builder.Build()

IronBarCode.License.LicenseKey = Environment.GetEnvironmentVariable("IRONBARCODE_KEY")
    ?? "YOUR-LICENSE-KEY";

在Docker或Kubernetes環境中,將IRONBARCODE_KEY環境變數設置在您的部署清單中。無需出站網路規則。

步驟3:替換命名空間導入

在所有源文件中查找和替換:

grep -r "using Dynamsoft\." --include="*.cs" .
SHELL

替換每次出現:

// Before
using Dynamsoft.CVR;
using Dynamsoft.DBR;
using Dynamsoft.License;
using Dynamsoft.Core;

// After
using IronBarCode;

程式碼遷移範例

基本文件閱讀

最基本的操作——從圖像文件讀取條碼。

之前—Dynamsoft:

using Dynamsoft.CVR;
using Dynamsoft.DBR;

public string ReadBarcodeFromFile(CaptureVisionRouter router, string imagePath)
{
    CapturedResult result = router.Capture(imagePath, PresetTemplate.PT_READ_BARCODES);
    BarcodeResultItem[] items = result.GetDecodedBarcodesResult()?.GetItems();
    if (items == null || items.Length == 0)
        return null;

    return items[0].GetText();
}

之後 — IronBarcode:

// NuGet: dotnet add package BarCode
using IronBarCode;

public string ReadBarcodeFromFile(string imagePath)
{
    var results = BarcodeReader.Read(imagePath);
    return results?.FirstOrDefault()?.Value;
}

路由器實例已消失。 BarcodeReader.Read是靜態的。 .Value。 對results的空檢查使用LINQ更簡潔。

讀取多個條碼

之前—Dynamsoft:

using Dynamsoft.CVR;
using Dynamsoft.DBR;

public List<string> ReadAllBarcodes(CaptureVisionRouter router, string imagePath)
{
    SimplifiedCaptureVisionSettings settings = router.GetSimplifiedSettings(
        PresetTemplate.PT_READ_BARCODES);
    settings.BarcodeSettings.ExpectedBarcodesCount = 0; // 0 = find all
    router.UpdateSettings(PresetTemplate.PT_READ_BARCODES, settings);

    CapturedResult result = router.Capture(imagePath, PresetTemplate.PT_READ_BARCODES);
    BarcodeResultItem[] items = result.GetDecodedBarcodesResult()?.GetItems();
    var values = new List<string>();

    if (items != null)
    {
        foreach (var item in items)
            values.Add(item.GetText());
    }

    return values;
}

之後 — IronBarcode:

using IronBarCode;

public List<string> ReadAllBarcodes(string imagePath)
{
    var options = new BarcodeReaderOptions
    {
        ExpectMultipleBarcodes = true,
        MaxParallelThreads = 4
    };

    return BarcodeReader.Read(imagePath, options)
        .Select(r => r.Value)
        .ToList();
}

從字節讀取(記憶體內圖像)

之前—Dynamsoft:

using Dynamsoft.CVR;
using Dynamsoft.Core;
using Dynamsoft.DBR;

// Requires width, height, stride, and pixel format — low-level buffer API
public string ReadFromBuffer(CaptureVisionRouter router, byte[] rawPixels, int width, int height)
{
    var imageData = new ImageData
    {
        Bytes = rawPixels,
        Width = width,
        Height = height,
        Stride = width * 3, // assuming 24bpp RGB
        Format = EnumImagePixelFormat.IPF_RGB_888
    };

    CapturedResult result = router.Capture(imageData, PresetTemplate.PT_READ_BARCODES);
    return result.GetDecodedBarcodesResult()?.GetItems()?.FirstOrDefault()?.GetText();
}

之後 — IronBarcode:

using IronBarCode;

// Pass PNG/JPEG/BMP bytes directly — no pixel format or stride calculation
public string ReadFromImageBytes(byte[] imageBytes)
{
    return BarcodeReader.Read(imageBytes)?.FirstOrDefault()?.Value;
}

如果您的應用程式以前將圖像字節轉換為Dynamsoft的原始像素緩衝區,您可以直接將原始編碼圖像字節(PNG、JPEG、BMP)傳遞給IronBarcode,而無需先解碼為原始像素。

PDF條碼閱讀——移除渲染迴圈

這通常是遷移中最大的程式碼減少。 移除整個PdfiumViewer渲染迴圈,並用一次調用替換它。

之前—Dynamsoft與PdfiumViewer:

// Requires: Dynamsoft.DotNet.BarcodeReader.Bundle + PdfiumViewer + PdfiumViewer.Native.*
using Dynamsoft.CVR;
using Dynamsoft.DBR;
using PdfiumViewer;
using System.Drawing.Imaging;

public List<string> ReadBarcodesFromPdf(CaptureVisionRouter router, string pdfPath)
{
    var allBarcodes = new List<string>();

    using (var pdfDoc = PdfDocument.Load(pdfPath))
    {
        for (int page = 0; page < pdfDoc.PageCount; page++)
        {
            using var image = pdfDoc.Render(page, 300, 300, true);
            using var ms = new MemoryStream();
            image.Save(ms, ImageFormat.Png);

            CapturedResult result = router.Capture(ms.ToArray(),
                PresetTemplate.PT_READ_BARCODES);
            var items = result.GetDecodedBarcodesResult()?.GetItems();
            if (items != null)
            {
                foreach (var item in items)
                    allBarcodes.Add(item.GetText());
            }
        }
    }

    return allBarcodes;
}

之後 — IronBarcode:

using IronBarCode;

public List<string> ReadBarcodesFromPdf(string pdfPath)
{
    return BarcodeReader.Read(pdfPath)
        .Select(r => r.Value)
        .ToList();
}

頁面迴圈、PdfDocument、300 DPI渲染步驟、MemoryStream和每頁Capture調用都消失。 IronBarcode在內部處理PDF頁面。

如果您需要閱讀具有選項的PDF(對於密集或困難的條碼):

using IronBarCode;

public List<string> ReadBarcodesFromPdfAccurate(string pdfPath)
{
    var options = new BarcodeReaderOptions
    {
        Speed = ReadingSpeed.Balanced,
        ExpectMultipleBarcodes = true
    };

    return BarcodeReader.Read(pdfPath, options)
        .Select(r => r.Value)
        .ToList();
}

離線/氣隙部署

如果您目前的程式碼包括離線授權模式,請完全移除它:

之前—Dynamsoft離線授權:

using Dynamsoft.License;
using Dynamsoft.Core;

// Dynamsoft offline: fetch license bundle on a connected machine, persist it,
// then replay it on the offline machine via InitLicenseFromLicenseContent.
int errorCode = LicenseManager.InitLicenseFromLicenseContent(
    licenseContent,
    out string errorMsg);

if (errorCode != (int)EnumErrorCode.EC_OK)
    throw new InvalidOperationException($"Offline license failed: {errorMsg}");

之後 — IronBarcode:

// Remove all of the above. Replace with:
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";

沒有授權內容包需獲取和刷新。 沒有連接機器啟動步驟。密鑰在本地驗證。

Docker配置

如果您之前有網路出口規則或代理配置以允許出站HTTPS到Dynamsoft的授權端點:

# Before: Docker or Kubernetes egress policy
# Required: Allow outbound HTTPS to Dynamsoft licence endpoints

# After: Remove that egress rule.
# IronBarcode does not require outbound network access for license validation.

# Set license via environment variable
env:
  - name: IRONBARCODE_KEY
    valueFrom:
      secretKeyRef:
        name: ironbarcode-license
        key: key
Text

實例管理清理

Dynamsoft使用基於CaptureVisionRouter的實例API。 如果您的程式碼在服務類、字段初始化器或DI註冊中建立路由器實例,這些都會消失:

之前—Dynamsoft實例管理:

using Dynamsoft.CVR;
using Dynamsoft.DBR;
using Dynamsoft.License;
using Dynamsoft.Core;

public class BarcodeService : IDisposable
{
    private readonly CaptureVisionRouter _router;

    public BarcodeService()
    {
        int errorCode = LicenseManager.InitLicense("KEY", out string errorMsg);
        if (errorCode != (int)EnumErrorCode.EC_OK)
            throw new InvalidOperationException(errorMsg);

        _router = new CaptureVisionRouter();

        var settings = _router.GetSimplifiedSettings(PresetTemplate.PT_READ_BARCODES);
        settings.BarcodeSettings.ExpectedBarcodesCount = 0;
        _router.UpdateSettings(PresetTemplate.PT_READ_BARCODES, settings);
    }

    public string[] ReadFile(string path)
    {
        CapturedResult result = _router.Capture(path, PresetTemplate.PT_READ_BARCODES);
        var items = result.GetDecodedBarcodesResult()?.GetItems();
        return items?.Select(i => i.GetText()).ToArray() ?? Array.Empty<string>();
    }

    public void Dispose()
    {
        _router?.Dispose();
    }
}

之後—IronBarcode靜態API:

// NuGet: dotnet add package BarCode
using IronBarCode;

public class BarcodeService
{
    // No constructor initialization — license set once at app startup
    // No Dispose — no instance to clean up

    public string[] ReadFile(string path)
    {
        var options = new BarcodeReaderOptions { ExpectMultipleBarcodes = true };
        return BarcodeReader.Read(path, options)
            .Select(r => r.Value)
            .ToArray();
    }
}

該類損失了構造函式,其_router字段。 如果此服務在DI中註冊為單例或範圍服務來管理路由器生命周期,該註冊可以簡化或服務可以成為一組靜態方法。

閱讀速度與超時映射

Dynamsoft使用一個以毫秒為單位的Timeout,優化為相機幀率。 IronBarcode使用ReadingSpeed枚舉:

Dynamsoft設置IronBarcode相當
settings.Timeout = 100(相機管線)Speed = ReadingSpeed.Faster
低超時(優先考慮速度)Speed = ReadingSpeed.Balanced
高超時(優先考慮準確性)Speed = ReadingSpeed.Detailed
最大準確性,無時間壓力Speed = ReadingSpeed.ExtremeDetail

對於大多數文件處理工作流來說,處理量比低於100ms的響應時間更重要,ReadingSpeed.Balanced是正確的預設值:

var options = new BarcodeReaderOptions
{
    Speed = ReadingSpeed.Balanced,
    ExpectMultipleBarcodes = true,
    MaxParallelThreads = 4
};

常見遷移問題

BarcodeResultItem.GetText() vs result.Value

存取器從一個方法改為一個屬性:

// Before
string value = item.GetText();

// After
string value = result.Value;

BarcodeResultItem.GetFormatString() vs result.Format

Dynamsoft通過GetFormatString()以字串形式返回格式。 IronBarcode在BarcodeEncoding枚舉公開:

// Before
if (item.GetFormatString() == "QR_CODE")
    Console.WriteLine("Found QR code");

// After
if (result.Format == BarcodeEncoding.QRCode)
    Console.WriteLine("Found QR code");

// For logging without enum comparison — .ToString() works on both
Console.WriteLine($"Format: {result.Format}");

空結果與空集合

Dynamsoft的null。 IronBarcode返回一個空集合。 更新空檢查:

// Before: null check required
CapturedResult result = router.Capture(path, PresetTemplate.PT_READ_BARCODES);
var items = result.GetDecodedBarcodesResult()?.GetItems();
if (items != null && items.Length > 0)
    Process(items[0].GetText());

// After: null-safe but also correct to check Count
var results = BarcodeReader.Read(path);
if (results.Any())
    Process(results.First().Value);

SimplifiedCaptureVisionSettings to BarcodeReaderOptions

GetSimplifiedSettings / Read

// Before
var settings = router.GetSimplifiedSettings(PresetTemplate.PT_READ_BARCODES);
settings.BarcodeSettings.ExpectedBarcodesCount = 0;
settings.Timeout = 500;
router.UpdateSettings(PresetTemplate.PT_READ_BARCODES, settings);
var result = router.Capture(path, PresetTemplate.PT_READ_BARCODES);

// After
var options = new BarcodeReaderOptions
{
    Speed = ReadingSpeed.Balanced,
    ExpectMultipleBarcodes = true
};
var results = BarcodeReader.Read(path, options);

遷移檢查清單

運行這些搜尋以找到所有需要更新的Dynamsoft參考:

grep -r "using Dynamsoft\." --include="*.cs" .
grep -r "LicenseManager.InitLicense\|EnumErrorCode\|EC_OK" --include="*.cs" .
grep -r "new CaptureVisionRouter\|router\.Capture\|PresetTemplate" --include="*.cs" .
grep -r "BarcodeResultItem\|GetDecodedBarcodesResult\|GetFormatString" --include="*.cs" .
grep -r "GetSimplifiedSettings\|UpdateSettings\|SimplifiedCaptureVisionSettings" --include="*.cs" .
grep -r "router\.Dispose\|InitLicenseFromLicenseContent" --include="*.cs" .
SHELL

處理每一個匹配:

  • using Dynamsoft.*using IronBarCode
  • LicenseManager.InitLicense(key, out errorMsg) + 錯誤檢查 → IronBarCode.License.LicenseKey = "key"
  • new CaptureVisionRouter() → 移除(靜態API,無實例)
  • router.Capture(path, PresetTemplate.PT_READ_BARCODES)BarcodeReader.Read(path)
  • router.Capture(imageData, ...)(原始像素緩衝區) → BarcodeReader.Read(imageBytes)
  • 每頁PDF渲染迴圈 + router.Capture(pageBytes, ...)BarcodeReader.Read(pdfPath)
  • BarcodeResultItem.GetText()result.Value
  • BarcodeResultItem.GetFormatString()result.Format
  • GetSimplifiedSettings(...) + UpdateSettings(...)new BarcodeReaderOptions { ... }
  • router.Dispose() → 移除
  • LicenseManager.InitLicenseFromLicenseContent(...) → 完全移除
  • 如果只是為支持Dynamsoft PDF處理而新增了PdfiumViewer NuGet套件,請將其移除
  • 移除Dynamsoft授權端點的Docker/Kubernetes網路出口規則
  • 在部署配置中設置IRONBARCODE_KEY環境變數
Curtis Chau
技術作家

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

...
閱讀更多

相關文章

Key in blue circle

立即免費取得 30 天試用金鑰

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費即時演示
Booking Badge

全球數百萬工程師信賴

Iron Software的客戶標誌
獲取您的無義務諮詢
完成下方表單或發送電子郵件至sales@ironsoftware.com
您的詳細資訊將始終保密。
全球數百萬工程師信賴
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立