如何在.NET中建立條碼閱讀器SDK?
IronBarcode 允許 .NET 開發人員以最少的程式碼向其應用程式添加條碼讀取功能。 它支援多種格式,包括一維和二維條碼、各種影像來源,並利用基於機器學習的檢測技術,為生產環境提供高精度。
條碼掃描對於許多應用至關重要,從庫存管理到零售和物流。 透過將條碼讀取功能整合到 .NET 應用程式中,您可以簡化資料收集、自動化工作流程並提高效率。 在評估條碼閱讀器解決方案時,請考慮支援的格式、處理速度和整合複雜性等因素。 IronBarcode 庫提供完全的跨平台相容性和卓越的容錯功能。
IronBarcode 是一個高效率的 .NET 函式庫,可以簡化條碼的使用。 借助此工具,您可以讀取影像、串流和PDF 檔案中的條碼,也可以使用C# QR 碼產生器產生 QR 碼。 本文將向您展示如何將條碼掃描整合到您的 .NET 應用程式中,重點介紹如何建立 API 或 Web 應用程式整合來公開條碼掃描功能。 該庫支援各種條碼格式,包括一維和二維條碼,並具有高級生成功能和樣式選項。
IronBarcode整合的最佳應用場景有哪些?
IronBarcode 在以下情況下表現出色:
*庫存管理系統*– 支援多條碼讀取和多頁 TIFF/GIF,實現產品追蹤自動化 物流應用– 使用高速讀取和可自訂輸出格式處理運輸條碼 零售POS系統– 使用Code 39和一維條碼產生驗證交易 文件處理– 使用自訂閱讀器設定從PDF 發票中提取數據 醫療保健應用– 使用二維格式讀取患者 ID 並進行錯誤糾正 生產品質控制**– 運行具有可配置條碼邊距的批量處理
如何在.NET中建立條碼讀取器SDK?
若要建立可作為服務在應用程式中提供的條碼閱讀器,請將 IronBarcode 整合到 REST API 或 Web 應用程式中。架構選擇取決於您的處理需求:單張影像處理適用於偶爾掃描,批次處理適用於文件工作流程,流處理適用於連續掃描應用程式。 以下是一個使用 ASP.NET Core 並充分考慮線程安全的範例。 該圖書館的閱讀功能包括先進的圖像創建過濾器,以實現最佳精度。
- 使用NuGet 套件安裝用於在 C# 中讀取條碼的 .NET 程式庫
- 建立一個可重複使用的條碼掃描類,並具備完善的錯誤處理機制。
- 發展從不同來源讀取條碼的方法
- 使用改進設定將條碼影像讀取功能整合到您的應用程式中
- 透過閱讀速度選項測試和改進效能
開始之前我需要準備什麼?
如果您還沒有下載 IronBarcode,請立即下載到您的專案中。 請確保您擁有適用於您預期用途的正確許可證金鑰。 請注意,透過公共 API 公開 IronBarcode 的功能或將其轉售為獨立服務需要額外的許可(SDK、OEM 或 SaaS)。 請務必在繼續操作前了解許可選項。 對於開發環境,您可以先使用免費試用版,然後在準備好投入生產環境時套用您的許可證金鑰。 查看變更日誌以取得最新更新和里程碑資訊。
為了獲得最佳效能,請考慮您的部署環境。 IronBarcode 支援跨平台相容性,包括Windows 、 Linux 、 macOS 、 Docker以及Azure和AWS Lambda等雲端平台。 行動開發者可以透過Blazor 整合獲得對Android和iOS 的支援。 對於 .NET MAUI 應用程序,請按照條碼掃描器閱讀器教學進行操作。
如何建立條碼掃描器類別?
在設定好 IronBarcode 並將其安裝到專案中之後,您可以建立一個可重複使用的條碼掃描器類,該類別整合了 IronBarcode 的功能並將其公開為 API 端點。 此實現方案包括效能最佳化和影像校正,以應對具有挑戰性的場景,並進行方向校正。 如果條碼位置可預測,可以考慮實施作物區域劃分以加快處理速度:
using IronBarCode;
using System.IO;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace BarcodeIntegration
{
public class BarcodeScanner
{
private static readonly ConcurrentDictionary<string, BarcodeReaderOptions> _optionsCache = new();
static BarcodeScanner()
{
// Set the license key
IronBarCode.License.LicenseKey = "Your-License-Key";
}
// Method to read a barcode from an image file with performance optimization
public string ReadBarcodeFromImage(string imagePath, BarcodeReadingSpeed speed = BarcodeReadingSpeed.Balanced)
{
try
{
var options = GetCachedOptions(speed);
// Try to read the barcode from the given image path
var barcode = BarcodeReader.Read(imagePath, options);
return barcode?.ToString() ?? "No Barcode Found"; // Return the barcode string or indicate no barcode was found
}
catch (Exception ex)
{
// Return an error message if an exception occurs
return $"Error reading barcode: {ex.Message}";
}
}
// Method to read a barcode from a stream (e.g., file upload or memory stream)
public async Task<string> ReadBarcodeFromStreamAsync(Stream inputStream)
{
try
{
var options = GetCachedOptions(BarcodeReadingSpeed.Detailed);
// Enable image correction for better accuracy
options.ImageFilters = new[] {
new SharpenFilter(),
new ContrastFilter()
};
// Try to read the barcode from the given stream
var barcode = await Task.Run(() => BarcodeReader.Read(inputStream, options));
return barcode?.ToString() ?? "No barcode found";
}
catch (Exception ex)
{
return $"Error reading barcode: {ex.Message}";
}
}
// Method to read a barcode from a PDF file with batch processing support
public async Task<List<string>> ReadBarcodesFromPdfAsync(string filePath)
{
try
{
var options = new BarcodeReaderOptions
{
ExpectMultipleBarcodes = true,
Speed = BarcodeReadingSpeed.Detailed
};
// Try to read barcodes from the given PDF file path
var barcodes = await Task.Run(() => BarcodeReader.ReadPdf(filePath, options));
return barcodes.Select(b => b.ToString()).ToList();
}
catch (Exception ex)
{
return new List<string> { $"Error reading barcode: {ex.Message}" };
}
}
// Cache reader options for performance
private BarcodeReaderOptions GetCachedOptions(BarcodeReadingSpeed speed)
{
return _optionsCache.GetOrAdd(speed.ToString(), _ => new BarcodeReaderOptions
{
Speed = speed,
AutoRotate = true,
RemoveFalsePositive = true
});
}
}
}using IronBarCode;
using System.IO;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace BarcodeIntegration
{
public class BarcodeScanner
{
private static readonly ConcurrentDictionary<string, BarcodeReaderOptions> _optionsCache = new();
static BarcodeScanner()
{
// Set the license key
IronBarCode.License.LicenseKey = "Your-License-Key";
}
// Method to read a barcode from an image file with performance optimization
public string ReadBarcodeFromImage(string imagePath, BarcodeReadingSpeed speed = BarcodeReadingSpeed.Balanced)
{
try
{
var options = GetCachedOptions(speed);
// Try to read the barcode from the given image path
var barcode = BarcodeReader.Read(imagePath, options);
return barcode?.ToString() ?? "No Barcode Found"; // Return the barcode string or indicate no barcode was found
}
catch (Exception ex)
{
// Return an error message if an exception occurs
return $"Error reading barcode: {ex.Message}";
}
}
// Method to read a barcode from a stream (e.g., file upload or memory stream)
public async Task<string> ReadBarcodeFromStreamAsync(Stream inputStream)
{
try
{
var options = GetCachedOptions(BarcodeReadingSpeed.Detailed);
// Enable image correction for better accuracy
options.ImageFilters = new[] {
new SharpenFilter(),
new ContrastFilter()
};
// Try to read the barcode from the given stream
var barcode = await Task.Run(() => BarcodeReader.Read(inputStream, options));
return barcode?.ToString() ?? "No barcode found";
}
catch (Exception ex)
{
return $"Error reading barcode: {ex.Message}";
}
}
// Method to read a barcode from a PDF file with batch processing support
public async Task<List<string>> ReadBarcodesFromPdfAsync(string filePath)
{
try
{
var options = new BarcodeReaderOptions
{
ExpectMultipleBarcodes = true,
Speed = BarcodeReadingSpeed.Detailed
};
// Try to read barcodes from the given PDF file path
var barcodes = await Task.Run(() => BarcodeReader.ReadPdf(filePath, options));
return barcodes.Select(b => b.ToString()).ToList();
}
catch (Exception ex)
{
return new List<string> { $"Error reading barcode: {ex.Message}" };
}
}
// Cache reader options for performance
private BarcodeReaderOptions GetCachedOptions(BarcodeReadingSpeed speed)
{
return _optionsCache.GetOrAdd(speed.ToString(), _ => new BarcodeReaderOptions
{
Speed = speed,
AutoRotate = true,
RemoveFalsePositive = true
});
}
}
}改進後的BarcodeScanner類別透過選項快取、 非同步處理(以提高可擴展性)和影像過濾器(以提高準確性)進行了效能優化。 此實作遵循 SOLID 原則,並提供可用於生產環境的錯誤處理。 如需更多功能,請考慮使用System.Drawing 整合或匯出為串流。 您也可以建立具有自訂條碼樣式和二維碼樣式的條碼圖像。
讀取不同來源的條碼應該使用哪些方法?
每種方法都針對特定用例和處理要求進行了改進:
ReadBarcodeFromImage(string imagePath):從映像檔讀取條碼。ReadBarcodeFromStream(Stream inputStream):從輸入流(例如,檔案上傳或記憶體流)讀取條碼。ReadBarcodeFromPdf(string filePath):從 PDF 檔案中讀取條碼。
對於大批量生產場景,如果條碼位置可預測,可以考慮使用作物區域來提高處理速度,最高可達 5 倍。 您也可以建立條碼圖像或以各種格式儲存條碼。 該程式庫支援從 System.Drawing 物件讀取數據,並可將條碼匯出為 HTML或PDF 文件。
如何透過 REST API 公開條碼讀取功能?
若要允許外部應用程式使用您的條碼掃描功能,請使用 ASP.NET Core 將其公開為 REST API。 此實現方案包括適當的錯誤處理、驗證以及對多種輸入格式的支援。 您也可以使用C# 條碼影像產生器產生條碼,或探索條碼快速入門範例。 處理 PDF 文件時,可考慮在現有 PDF 文件上新增條碼以進行文件追蹤:
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Microsoft.AspNetCore.Http;
using BarcodeIntegration;
[ApiController]
[Route("api/barcode")]
public class BarcodeController : ControllerBase
{
private readonly BarcodeScanner _barcodeScanner;
private readonly ILogger<BarcodeController> _logger;
public BarcodeController(ILogger<BarcodeController> logger)
{
_barcodeScanner = new BarcodeScanner();
_logger = logger;
}
// POST endpoint to read barcode from an uploaded image
[HttpPost("read-from-image")]
public async Task<IActionResult> ReadFromImage(IFormFile file)
{
if (file == null || file.Length == 0)
return BadRequest(new { Error = "No file uploaded" });
// Validate file type
var allowedTypes = new[] { "image/jpeg", "image/png", "image/gif", "image/bmp", "image/tiff" };
if (!allowedTypes.Contains(file.ContentType.ToLower()))
return BadRequest(new { Error = "Unsupported file type" });
try
{
using var stream = file.OpenReadStream();
var result = await _barcodeScanner.ReadBarcodeFromStreamAsync(stream);
_logger.LogInformation($"Barcode read successfully from {file.FileName}");
return Ok(new { Barcode = result, FileName = file.FileName });
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing barcode");
return StatusCode(500, new { Error = "Internal server error" });
}
}
// POST endpoint for batch processing
[HttpPost("read-batch")]
public async Task<IActionResult> ReadBatch(List<IFormFile> files)
{
var results = new List<object>();
foreach (var file in files)
{
using var stream = file.OpenReadStream();
var result = await _barcodeScanner.ReadBarcodeFromStreamAsync(stream);
results.Add(new { FileName = file.FileName, Barcode = result });
}
return Ok(new { Results = results, Count = results.Count });
}
// POST endpoint to generate barcode from data
[HttpPost("generate")]
public IActionResult GenerateBarcode([FromBody] BarcodeGenerationRequest request)
{
try
{
// Create barcode with specified data and format
var barcode = BarcodeWriter.CreateBarcode(request.Data, request.Format ?? BarcodeWriterEncoding.Code128);
// Apply custom styling if requested
if (request.Width.HasValue && request.Height.HasValue)
barcode.ResizeTo(request.Width.Value, request.Height.Value);
if (!string.IsNullOrEmpty(request.ForegroundColor))
barcode.ChangeBarCodeColor(System.Drawing.ColorTranslator.FromHtml(request.ForegroundColor));
// Return as base64 encoded image
using var ms = barcode.ToStream();
var bytes = ms.ToArray();
return Ok(new {
Image = Convert.ToBase64String(bytes),
Format = request.Format?.ToString() ?? "Code128",
Data = request.Data
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Error generating barcode");
return BadRequest(new { Error = "Failed to generate barcode" });
}
}
}
public class BarcodeGenerationRequest
{
public string Data { get; set; }
public BarcodeWriterEncoding? Format { get; set; }
public int? Width { get; set; }
public int? Height { get; set; }
public string ForegroundColor { get; set; }
}using Microsoft.AspNetCore.Mvc;
using System.IO;
using Microsoft.AspNetCore.Http;
using BarcodeIntegration;
[ApiController]
[Route("api/barcode")]
public class BarcodeController : ControllerBase
{
private readonly BarcodeScanner _barcodeScanner;
private readonly ILogger<BarcodeController> _logger;
public BarcodeController(ILogger<BarcodeController> logger)
{
_barcodeScanner = new BarcodeScanner();
_logger = logger;
}
// POST endpoint to read barcode from an uploaded image
[HttpPost("read-from-image")]
public async Task<IActionResult> ReadFromImage(IFormFile file)
{
if (file == null || file.Length == 0)
return BadRequest(new { Error = "No file uploaded" });
// Validate file type
var allowedTypes = new[] { "image/jpeg", "image/png", "image/gif", "image/bmp", "image/tiff" };
if (!allowedTypes.Contains(file.ContentType.ToLower()))
return BadRequest(new { Error = "Unsupported file type" });
try
{
using var stream = file.OpenReadStream();
var result = await _barcodeScanner.ReadBarcodeFromStreamAsync(stream);
_logger.LogInformation($"Barcode read successfully from {file.FileName}");
return Ok(new { Barcode = result, FileName = file.FileName });
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing barcode");
return StatusCode(500, new { Error = "Internal server error" });
}
}
// POST endpoint for batch processing
[HttpPost("read-batch")]
public async Task<IActionResult> ReadBatch(List<IFormFile> files)
{
var results = new List<object>();
foreach (var file in files)
{
using var stream = file.OpenReadStream();
var result = await _barcodeScanner.ReadBarcodeFromStreamAsync(stream);
results.Add(new { FileName = file.FileName, Barcode = result });
}
return Ok(new { Results = results, Count = results.Count });
}
// POST endpoint to generate barcode from data
[HttpPost("generate")]
public IActionResult GenerateBarcode([FromBody] BarcodeGenerationRequest request)
{
try
{
// Create barcode with specified data and format
var barcode = BarcodeWriter.CreateBarcode(request.Data, request.Format ?? BarcodeWriterEncoding.Code128);
// Apply custom styling if requested
if (request.Width.HasValue && request.Height.HasValue)
barcode.ResizeTo(request.Width.Value, request.Height.Value);
if (!string.IsNullOrEmpty(request.ForegroundColor))
barcode.ChangeBarCodeColor(System.Drawing.ColorTranslator.FromHtml(request.ForegroundColor));
// Return as base64 encoded image
using var ms = barcode.ToStream();
var bytes = ms.ToArray();
return Ok(new {
Image = Convert.ToBase64String(bytes),
Format = request.Format?.ToString() ?? "Code128",
Data = request.Data
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Error generating barcode");
return BadRequest(new { Error = "Failed to generate barcode" });
}
}
}
public class BarcodeGenerationRequest
{
public string Data { get; set; }
public BarcodeWriterEncoding? Format { get; set; }
public int? Width { get; set; }
public int? Height { get; set; }
public string ForegroundColor { get; set; }
}在 Swagger UI 中,API 的顯示效果如何?
Swagger UI 展示了 BarcoderScannerSDK API,它包含兩個 POST 端點,分別用於從影像和 PDF 讀取條碼,並提供檔案上傳介面和請求設定選項。
API響應是什麼樣的?
API 文件顯示,成功傳送至條碼讀取端點 POST 請求,傳回"Hello World!"以及 200 OK 回應狀態。
此 API 公開 POST 端點,您可以在其中上傳條碼映像,API 將傳回條碼資料。 此實作方案包括適當的驗證、錯誤處理和日誌記錄,以滿足生產環境的需求。 對於行動應用程序,可以考慮添加針對更小圖像尺寸和更快響應時間進行改進的端點。 您也可以從資料建立條碼,或將其匯出為HTML或PDF 。 對於高對比度要求,產生1-BPP 條碼影像。 ## 我可以新增哪些進階功能?
為了進一步改進您的 SDK,請考慮使用 IronBarcode 的完整API 參考來實現這些可用於生產環境的功能。 瀏覽功能概述並查看演示以了解實際應用:
如何支援多種條碼類型?
IronBarcode支援同時讀取多個條碼。 您可以設定 SDK,使其能夠一次接受多個條碼,並進行特定的格式篩選。 該程式庫支援編寫包含中文和阿拉伯字元的Unicode條碼。 對於特殊應用,可以探索Code 39 讀取功能並建立具有自訂樣式的二維碼:
public async Task<List<BarcodeResult>> ReadMultipleBarcodesAsync(string imagePath, BarcodeEncoding[] expectedTypes = null)
{
try
{
var options = new BarcodeReaderOptions()
{
ExpectMultipleBarcodes = true,
ExpectBarcodeTypes = expectedTypes ?? BarcodeEncoding.All,
Speed = BarcodeReadingSpeed.Detailed,
MaxParallelThreads = Environment.ProcessorCount,
Multithreaded = true
};
// Apply confidence threshold for machine learning accuracy
options.Confidence = Confidence.High;
var results = await Task.Run(() => BarcodeReader.Read(imagePath, options));
return results.Select(barcode => new BarcodeResult
{
Value = barcode.ToString(),
Format = barcode.BarcodeType.ToString(),
Confidence = barcode.Confidence,
Position = barcode.Rect
}).ToList();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error reading multiple barcodes");
throw;
}
}public async Task<List<BarcodeResult>> ReadMultipleBarcodesAsync(string imagePath, BarcodeEncoding[] expectedTypes = null)
{
try
{
var options = new BarcodeReaderOptions()
{
ExpectMultipleBarcodes = true,
ExpectBarcodeTypes = expectedTypes ?? BarcodeEncoding.All,
Speed = BarcodeReadingSpeed.Detailed,
MaxParallelThreads = Environment.ProcessorCount,
Multithreaded = true
};
// Apply confidence threshold for machine learning accuracy
options.Confidence = Confidence.High;
var results = await Task.Run(() => BarcodeReader.Read(imagePath, options));
return results.Select(barcode => new BarcodeResult
{
Value = barcode.ToString(),
Format = barcode.BarcodeType.ToString(),
Confidence = barcode.Confidence,
Position = barcode.Rect
}).ToList();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error reading multiple barcodes");
throw;
}
}我還應該考慮哪些其他改進措施?
*錯誤處理:*實現完整的錯誤處理,包括MSI 條碼識別 批次處理:建立用於非同步批次處理1-BPP 條碼影像的方法 效能監控:新增讀取速度配置指標 快取:對頻繁掃描的條碼實施結果緩存 影像預處理:**使用方向校正和對比度濾波器 *格式特定最佳化:配置GS1-128和新格式的設置
對於生產環境部署,可以考慮實施置信度閾值,以減少誤報並確保資料準確性。 基於機器學習的檢測方法可以根據您的特定使用情境進行微調。 建立部署包時,請按照MSI 安裝程式指南進行操作,並解決任何缺少的 DLL 問題。 對於 AWS 部署,請注意潛在的執行時間問題。 考慮建立具有各種輸出資料格式的條碼,並探索條碼讀取教學。
我應該注意哪些許可方面的注意事項?
如前所述,IronBarcode SDK 旨在整合到您的內部應用程式中,透過 API 公開它需要額外的許可。 在將 IronBarcode 作為服務的一部分(例如公共 API)公開之前,您必須獲得必要的許可(SDK、OEM 或 SaaS)。 對於企業部署,請考慮使用可用的授權擴充來增加席位或改善支援。 查看升級選項,以擴展您的部署規模。
未經許可,請勿將 IronBarcode 以獨立 SDK 轉售,或透過面向公眾的 API 公開,除非您已確保您的許可涵蓋此用途。 對於 Web 應用程序,您可能需要在 web.config 中配置許可證金鑰才能正確啟動。 隨時了解安全 CVE 更新,並遵循運行時複製例外的最佳實踐。 對於技術問題,請考慮提交工程請求。 查看有關編寫 Unicode 條碼的資源,並探索讀取條碼教學。
我今天為什麼要嘗試 IronBarcode?
體驗IronBarcode的全新功能。 試試我們的免費試用版,體驗適用於 .NET 應用程式的流暢條碼產生、讀取和編輯功能。 IronBarcode 擁有先進的功能、卓越的性能和用戶友好的介面,是滿足您所有條碼需求的終極解決方案。 請瀏覽我們的完整文件、查看程式碼範例並觀看即時演示,以了解其全部功能。 查看有關讀取條碼的教程,並了解MicroQR 和 rMQR支援。 了解適用於不同部署場景的NuGet 套件選項。 您也可以查閱IronBarcode 文檔,以了解有關我們完整條碼解決方案的更多資訊。 立即開始免費試用,提升您的專案品質。
常見問題解答
如何將條碼閱讀器整合到 .NET 應用程式中?
您可以使用 IronBarcode 庫將條碼閱讀器整合到 .NET 應用程式中。首先,安裝 IronBarcode,然後建立一個用於條碼掃描的類,並實現從圖像、流和 PDF 中讀取條碼的方法。最後,測試並優化您的配置。
如何將條碼讀取功能作為 REST API 公開?
若要將條碼讀取功能作為 REST API 公開,請使用 ASP.NET Core 建立一個 Web 應用程式。整合 IronBarcode 庫,開發一個 BarcodeScanner 類,並定義使用ReadBarcodeFromImage和ReadBarcodeFromStream等方法讀取條碼的 API 端點。
使用 .NET 條碼庫可以讀取哪些類型的條碼?
像 IronBarcode 這樣的 .NET 條碼庫可以讀取多種條碼類型,包括二維碼、Code 128、UPC 和 EAN。您可以透過設定偵測參數來配置該庫,使其同時偵測多種條碼類型。
如何在.NET中處理讀取條碼時出現的錯誤?
使用 IronBarcode,您可以透過在條碼掃描方法中實現強大的錯誤處理機制來應對條碼讀取錯誤。確保捕獲異常並提供有效的回饋或重試機制,以提高條碼讀取過程的可靠性。
在公共 API 中使用 .NET 條碼庫有哪些授權需求?
在公共 API 中使用 IronBarcode 時,必須確保適當的許可。這包括取得 SDK、OEM 或 SaaS 許可,因為將程式庫的功能作為獨立服務或公共 API 公開需要額外的權限。
我可以使用 .NET 函式庫批次處理多個條碼掃描嗎?
是的,您可以使用 IronBarcode 批次處理多個條碼掃描。該程式庫允許您在一次操作中讀取多個條碼,這對於高效處理大量影像或文件尤其有用。
是否有適用於 .NET 條碼庫的試用版?
是的,IronBarcode 提供免費試用版,讓您可以體驗其在 .NET 應用程式中產生、讀取和編輯條碼的功能。此試用版可以幫助您在購買前評估該庫。






