如何在C#.NET中使用IronBarcode生成條碼圖片
從Dynamsoft Barcode Reader遷移到IronBarcode
大多數從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
dotnet remove package Dynamsoft.DotNet.BarcodeReader.Bundle
dotnet add package BarCode
如果您的專案中也特別為Dynamsoft新增了PDF渲染庫(PdfiumViewer是最常見的),那也可以移除:
# Remove if added only for Dynamsoft PDF support
dotnet remove package PdfiumViewer
dotnet remove package PdfiumViewer.Native.x86_64.v8-xfa
# Remove if added only for Dynamsoft PDF support
dotnet remove package PdfiumViewer
dotnet remove package PdfiumViewer.Native.x86_64.v8-xfa
步驟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}");
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}");
Imports Dynamsoft.License
Imports Dynamsoft.Core
' Must run before any barcode operations
Dim errorCode As Integer = LicenseManager.InitLicense("YOUR-DYNAMSOFT-KEY", errorMsg)
If errorCode <> CType(EnumErrorCode.EC_OK, Integer) Then
Throw New InvalidOperationException($"License validation failed [{errorCode}]: {errorMsg}")
End If
之後 — IronBarcode:
// NuGet: dotnet add package BarCode
using IronBarCode;
// Local validation — no network call, no error code
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
// NuGet: dotnet add package BarCode
using IronBarCode;
// Local validation — no network call, no error code
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
Imports 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";
IronBarCode.License.LicenseKey = Environment.GetEnvironmentVariable("IRONBARCODE_KEY")
?? "YOUR-LICENSE-KEY";
Imports IronBarCode
IronBarCode.License.LicenseKey = If(Environment.GetEnvironmentVariable("IRONBARCODE_KEY"), "YOUR-LICENSE-KEY")
在Docker或Kubernetes環境中,將IRONBARCODE_KEY環境變數設置在您的部署清單中。無需出站網路規則。
步驟3:替換命名空間導入
在所有源文件中查找和替換:
grep -r "using Dynamsoft\." --include="*.cs" .
grep -r "using Dynamsoft\." --include="*.cs" .
替換每次出現:
// Before
using Dynamsoft.CVR;
using Dynamsoft.DBR;
using Dynamsoft.License;
using Dynamsoft.Core;
// After
using IronBarCode;
// Before
using Dynamsoft.CVR;
using Dynamsoft.DBR;
using Dynamsoft.License;
using Dynamsoft.Core;
// After
using IronBarCode;
Imports 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();
}
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();
}
Imports Dynamsoft.CVR
Imports Dynamsoft.DBR
Public Function ReadBarcodeFromFile(router As CaptureVisionRouter, imagePath As String) As String
Dim result As CapturedResult = router.Capture(imagePath, PresetTemplate.PT_READ_BARCODES)
Dim items As BarcodeResultItem() = result.GetDecodedBarcodesResult()?.GetItems()
If items Is Nothing OrElse items.Length = 0 Then
Return Nothing
End If
Return items(0).GetText()
End Function
之後 — IronBarcode:
// NuGet: dotnet add package BarCode
using IronBarCode;
public string ReadBarcodeFromFile(string imagePath)
{
var results = BarcodeReader.Read(imagePath);
return results?.FirstOrDefault()?.Value;
}
// NuGet: dotnet add package BarCode
using IronBarCode;
public string ReadBarcodeFromFile(string imagePath)
{
var results = BarcodeReader.Read(imagePath);
return results?.FirstOrDefault()?.Value;
}
Imports IronBarCode
Public Function ReadBarcodeFromFile(imagePath As String) As String
Dim results = BarcodeReader.Read(imagePath)
Return results?.FirstOrDefault()?.Value
End Function
路由器實例已消失。 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;
}
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;
}
Imports Dynamsoft.CVR
Imports Dynamsoft.DBR
Public Function ReadAllBarcodes(router As CaptureVisionRouter, imagePath As String) As List(Of String)
Dim settings As SimplifiedCaptureVisionSettings = router.GetSimplifiedSettings(PresetTemplate.PT_READ_BARCODES)
settings.BarcodeSettings.ExpectedBarcodesCount = 0 ' 0 = find all
router.UpdateSettings(PresetTemplate.PT_READ_BARCODES, settings)
Dim result As CapturedResult = router.Capture(imagePath, PresetTemplate.PT_READ_BARCODES)
Dim items As BarcodeResultItem() = result.GetDecodedBarcodesResult()?.GetItems()
Dim values As New List(Of String)()
If items IsNot Nothing Then
For Each item In items
values.Add(item.GetText())
Next
End If
Return values
End Function
之後 — 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();
}
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();
}
Imports IronBarCode
Public Function ReadAllBarcodes(imagePath As String) As List(Of String)
Dim options As New BarcodeReaderOptions With {
.ExpectMultipleBarcodes = True,
.MaxParallelThreads = 4
}
Return BarcodeReader.Read(imagePath, options) _
.Select(Function(r) r.Value) _
.ToList()
End Function
從字節讀取(記憶體內圖像)
之前—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();
}
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();
}
Imports Dynamsoft.CVR
Imports Dynamsoft.Core
Imports Dynamsoft.DBR
' Requires width, height, stride, and pixel format — low-level buffer API
Public Function ReadFromBuffer(router As CaptureVisionRouter, rawPixels As Byte(), width As Integer, height As Integer) As String
Dim imageData As New ImageData With {
.Bytes = rawPixels,
.Width = width,
.Height = height,
.Stride = width * 3, ' assuming 24bpp RGB
.Format = EnumImagePixelFormat.IPF_RGB_888
}
Dim result As CapturedResult = router.Capture(imageData, PresetTemplate.PT_READ_BARCODES)
Return result.GetDecodedBarcodesResult()?.GetItems()?.FirstOrDefault()?.GetText()
End Function
之後 — 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;
}
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;
}
Imports IronBarCode
Public Function ReadFromImageBytes(imageBytes As Byte()) As String
Return BarcodeReader.Read(imageBytes)?.FirstOrDefault()?.Value
End Function
如果您的應用程式以前將圖像字節轉換為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;
}
// 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;
}
Imports Dynamsoft.CVR
Imports Dynamsoft.DBR
Imports PdfiumViewer
Imports System.Drawing.Imaging
Public Function ReadBarcodesFromPdf(router As CaptureVisionRouter, pdfPath As String) As List(Of String)
Dim allBarcodes As New List(Of String)()
Using pdfDoc As PdfDocument = PdfDocument.Load(pdfPath)
For page As Integer = 0 To pdfDoc.PageCount - 1
Using image = pdfDoc.Render(page, 300, 300, True)
Using ms As New MemoryStream()
image.Save(ms, ImageFormat.Png)
Dim result As CapturedResult = router.Capture(ms.ToArray(), PresetTemplate.PT_READ_BARCODES)
Dim items = result.GetDecodedBarcodesResult()?.GetItems()
If items IsNot Nothing Then
For Each item In items
allBarcodes.Add(item.GetText())
Next
End If
End Using
End Using
Next
End Using
Return allBarcodes
End Function
之後 — IronBarcode:
using IronBarCode;
public List<string> ReadBarcodesFromPdf(string pdfPath)
{
return BarcodeReader.Read(pdfPath)
.Select(r => r.Value)
.ToList();
}
using IronBarCode;
public List<string> ReadBarcodesFromPdf(string pdfPath)
{
return BarcodeReader.Read(pdfPath)
.Select(r => r.Value)
.ToList();
}
Imports IronBarCode
Public Function ReadBarcodesFromPdf(pdfPath As String) As List(Of String)
Return BarcodeReader.Read(pdfPath) _
.Select(Function(r) r.Value) _
.ToList()
End Function
頁面迴圈、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();
}
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();
}
Imports IronBarCode
Public Function ReadBarcodesFromPdfAccurate(pdfPath As String) As List(Of String)
Dim options As New BarcodeReaderOptions With {
.Speed = ReadingSpeed.Balanced,
.ExpectMultipleBarcodes = True
}
Return BarcodeReader.Read(pdfPath, options) _
.Select(Function(r) r.Value) _
.ToList()
End Function
離線/氣隙部署
如果您目前的程式碼包括離線授權模式,請完全移除它:
之前—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}");
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}");
Imports Dynamsoft.License
Imports Dynamsoft.Core
' Dynamsoft offline: fetch license bundle on a connected machine, persist it,
' then replay it on the offline machine via InitLicenseFromLicenseContent.
Dim errorMsg As String
Dim errorCode As Integer = LicenseManager.InitLicenseFromLicenseContent(licenseContent, errorMsg)
If errorCode <> CType(EnumErrorCode.EC_OK, Integer) Then
Throw New InvalidOperationException($"Offline license failed: {errorMsg}")
End If
之後 — IronBarcode:
// Remove all of the above. Replace with:
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
// Remove all of the above. Replace with:
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
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
# 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
實例管理清理
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();
}
}
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();
}
}
Imports Dynamsoft.CVR
Imports Dynamsoft.DBR
Imports Dynamsoft.License
Imports Dynamsoft.Core
Public Class BarcodeService
Implements IDisposable
Private ReadOnly _router As CaptureVisionRouter
Public Sub New()
Dim errorCode As Integer = LicenseManager.InitLicense("KEY", errorMsg:=Nothing)
If errorCode <> CType(EnumErrorCode.EC_OK, Integer) Then
Throw New InvalidOperationException(errorMsg)
End If
_router = New CaptureVisionRouter()
Dim settings = _router.GetSimplifiedSettings(PresetTemplate.PT_READ_BARCODES)
settings.BarcodeSettings.ExpectedBarcodesCount = 0
_router.UpdateSettings(PresetTemplate.PT_READ_BARCODES, settings)
End Sub
Public Function ReadFile(path As String) As String()
Dim result As CapturedResult = _router.Capture(path, PresetTemplate.PT_READ_BARCODES)
Dim items = result.GetDecodedBarcodesResult()?.GetItems()
Return If(items?.Select(Function(i) i.GetText()).ToArray(), Array.Empty(Of String)())
End Function
Public Sub Dispose() Implements IDisposable.Dispose
_router?.Dispose()
End Sub
End Class
之後—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();
}
}
// 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();
}
}
Imports IronBarCode
Public Class BarcodeService
' No constructor initialization — license set once at app startup
' No Dispose — no instance to clean up
Public Function ReadFile(path As String) As String()
Dim options As New BarcodeReaderOptions With {.ExpectMultipleBarcodes = True}
Return BarcodeReader.Read(path, options) _
.Select(Function(r) r.Value) _
.ToArray()
End Function
End Class
該類損失了構造函式,其_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
};
var options = new BarcodeReaderOptions
{
Speed = ReadingSpeed.Balanced,
ExpectMultipleBarcodes = true,
MaxParallelThreads = 4
};
Dim options As New BarcodeReaderOptions With {
.Speed = ReadingSpeed.Balanced,
.ExpectMultipleBarcodes = True,
.MaxParallelThreads = 4
}
常見遷移問題
BarcodeResultItem.GetText() vs result.Value
存取器從一個方法改為一個屬性:
// Before
string value = item.GetText();
// After
string value = result.Value;
// Before
string value = item.GetText();
// After
string value = result.Value;
' Before
Dim value As String = item.GetText()
' After
Dim value As String = 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}");
// 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}");
' Before
If item.GetFormatString() = "QR_CODE" Then
Console.WriteLine("Found QR code")
End If
' After
If result.Format = BarcodeEncoding.QRCode Then
Console.WriteLine("Found QR code")
End If
' 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);
// 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);
Imports System.Linq
' Before: null check required
Dim result As CapturedResult = router.Capture(path, PresetTemplate.PT_READ_BARCODES)
Dim items = result.GetDecodedBarcodesResult()?.GetItems()
If items IsNot Nothing AndAlso items.Length > 0 Then
Process(items(0).GetText())
End If
' After: null-safe but also correct to check Count
Dim results = BarcodeReader.Read(path)
If results.Any() Then
Process(results.First().Value)
End If
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);
// 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);
' Before
Dim settings = router.GetSimplifiedSettings(PresetTemplate.PT_READ_BARCODES)
settings.BarcodeSettings.ExpectedBarcodesCount = 0
settings.Timeout = 500
router.UpdateSettings(PresetTemplate.PT_READ_BARCODES, settings)
Dim result = router.Capture(path, PresetTemplate.PT_READ_BARCODES)
' After
Dim options As New BarcodeReaderOptions With {
.Speed = ReadingSpeed.Balanced,
.ExpectMultipleBarcodes = True
}
Dim 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" .
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" .
處理每一個匹配:
using Dynamsoft.*→using IronBarCodeLicenseManager.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.ValueBarcodeResultItem.GetFormatString()→result.FormatGetSimplifiedSettings(...)+UpdateSettings(...)→new BarcodeReaderOptions { ... }router.Dispose()→ 移除LicenseManager.InitLicenseFromLicenseContent(...)→ 完全移除- 如果只是為支持Dynamsoft PDF處理而新增了PdfiumViewer NuGet套件,請將其移除
- 移除Dynamsoft授權端點的Docker/Kubernetes網路出口規則
- 在部署配置中設置
IRONBARCODE_KEY環境變數
常見問題
我為什麼要從Dynamsoft Barcode Reader遷移到IronBarcode?
常見的理由包括簡化授權(去除SDK +運行時鑰匙的複雜性)、消除吞吐量限制、獲得原生PDF支持、改善Docker/CI/CD部署,並減少生產程式碼中的API樣板。
我如何使用IronBarcode替換Dynamsoft API調用?
用IronBarCode.License.LicenseKey = "key"替換實例建立和授權樣板。用BarcodeReader.Read(path)替換讀取呼叫,用BarcodeWriter.CreateBarcode(data, encoding)替換寫入呼叫。靜態方法不需要實例管理。
從Dynamsoft Barcode Reader遷移到IronBarcode需要更改多少程式碼?
大多數遷移會導致較少的程式碼行。授權樣板、實例構造函式和顯式格式配置被移除。核心讀/寫操作映射為較短的IronBarcode等價物,且結果物件更清晰。
遷移期間需要同時安裝Dynamsoft Barcode Reader和IronBarcode嗎?
不需要。大多數遷移是直接替換而不是並行操作。一次遷移一個服務類,替換NuGet引用,並更新實例化和API呼叫模式後再移動到下一個類。
IronBarcode的NuGet包名稱是什麼?
包名是'IronBarCode'(大寫B和C)。可以用'Install-Package IronBarCode'或'dotnet add package IronBarCode'安裝。程式碼中的using指令是'using IronBarCode;'。
與Dynamsoft Barcode Reader相比,IronBarcode如何簡化Docker部署?
IronBarcode是沒有外部SDK文件或掛載許可配置的NuGet封裝。在Docker中,設置IRONBARCODE_LICENSE_KEY環境變數,包在啟動時處理許可驗證。
IronBarcode在從Dynamsoft遷移後能自動檢測所有條碼格式嗎?
是的。IronBarcode自動檢測所有支持的格式的符號學。不需要顯式的BarcodeTypes枚舉。如果格式已經知道並且性能很重要,BarcodeReaderOptions允許限制搜索空間作為優化。
IronBarcode是否可以不使用單獨的庫讀取PDF中的條碼?
可以。BarcodeReader.Read("document.pdf")原生處理PDF文件。結果包括每個條碼發現的頁碼、格式、值和置信度。不需要外部PDF渲染步驟。
IronBarcode如何處理並行條碼處理?
IronBarcode的靜態方法是無狀態且執行緒安全的。直接使用Parallel.ForEach遍歷文件列表,不需要每個執行緒的實例管理。BarcodeReaderOptions.MaxParallelThreads控制內部執行緒預算。
從Dynamsoft Barcode Reader遷移到IronBarcode時哪些結果屬性會改變?
常見的重命名:BarcodeValue變為Value,BarcodeType變為Format。IronBarcode結果還新增了Confidence和PageNumber。整個解決方案的搜索和替換可處理現有結果處理程式碼中的重新命名。
我如何在CI/CD管道中設置IronBarcode授權?
將IRONBARCODE_LICENSE_KEY作為管道機密儲存,在應用程式啟動程式碼中分配IronBarCode.License.LicenseKey。一個機密涵蓋所有環境,包括開發、測試、分期和生產。
IronBarcode是否支持生成帶有自定義樣式的QR碼?
支持。QRCodeWriter.CreateQrCode()支持通過ChangeBarCodeColor()自定義顏色,通過AddBrandLogo()嵌入logo,可配置錯誤校正級別,以及包括PNG、JPG、PDF和流在內的多種輸出格式。

