跳過到頁腳內容
使用IRONBARCODE

如何在.NET中構建條碼讀取器SDK?

IronBarcode允許.NET開發者通過簡單的程式碼將條碼閱讀功能添加到他們的應用程式中。 它支援多種格式,包括1D和2D條碼、各種影像來源,並在生產環境中提供基於機器學習的高準確度檢測。

條碼掃描對於許多應用程式是至關重要的,從庫存管理到零售和物流。 通過將條碼閱讀整合到您的.NET應用程式中,您可以簡化資料捕獲、自動化工作流程,並提高效率。 在評估條碼閱讀解決方案時,請考慮支援的格式、處理速度和整合複雜性等因素。 IronBarcode程式庫提供完整的跨平台相容性和卓越的容錯功能。

IronBarcode是一個有效的.NET程式庫,可以簡化條碼的處理。 使用此工具,您可以從影像中讀取條碼PDF文件,以及使用C# QR碼生成器生成QR碼。 本文將向您展示如何將條碼掃描整合到您的.NET應用程式中,重點在於API或網頁應用程式整合,以暴露條碼掃描功能。 此程式庫支援多種條碼格式,包括1D和2D條碼,具有先進的生成能力樣式選項

IronBarcode整合的最佳使用案例是什麼?

IronBarcode在以下情境中表現出色:

如何在.NET中建立條碼閱讀SDK?

若要建立一個可以在您的應用程式中曝光為服務的條碼閱讀器,您需將IronBarcode整合到REST API或Web App中。架構選擇取決於您的處理需求:對偶爾掃描進行單影像處理、對文件工作流程進行批量處理、或對連續掃描應用進行流處理。 以下是使用ASP.NET Core的範例,考慮了適當的執行緒安全性。 該庫的讀取功能包括先進的影像創建過濾器,以達到最佳準確度。

  1. 使用NuGet套件在C#中安裝.NET庫以讀取條碼
  2. 使用適當的錯誤處理創建可重用的條碼掃描類別
  3. 開發從不同來源讀取條碼的方法
  4. 使用改進的設置將條碼影像讀取整合到您的應用程式中
  5. 使用閱讀速度選項進行測試和性能提升

開始之前我需要什麼?

如果您還沒有,請下載IronBarcode到您的專案中。 確保您擁有適當的授權金鑰以便於您預期的用途。 請注意,通過公共API暴露IronBarcode的功能或將其作為獨立服務轉售需要其他授權(SDK、OEM或SaaS)。 在繼續之前,請確保您理解授權選項。 對於開發環境,您可以開始免費試用並在投產時應用您的授權金鑰。 查看變更記錄以獲取最新的更新和里程碑

為了獲得最佳性能,請考慮您的部署環境。 IronBarcode支援跨平台相容性,包括WindowsLinuxmacOSDocker,以及如AzureAWS Lambda這樣的雲平台。 移動開發者可以通過Blazor整合使用AndroidiOS的支持。 對於.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
            });
        }
    }
}
$vbLabelText   $csharpLabel

此改進的BarcodeScanner類使用選項快取進行性能優化,異步處理以提高可擴展性,以及影像過濾器以提高準確性。 實施遵循SOLID準則並提供生產就緒的錯誤處理。 欲獲得更多功能,考慮使用System.Drawing整合以流的形式匯出。 您還可以創建條碼影像,具有自定義的條碼樣式QR碼樣式

我應該使用哪些方法來讀取不同的條碼來源?

每種方法都針對特定的使用案例和處理要求進行了改進:

  • ReadBarcodeFromImage(string imagePath): 從圖像檔案讀取條碼。
  • ReadBarcodeFromStream(Stream inputStream): 從輸入流讀取條碼(例如,文件上傳或記憶體流)。
  • ReadBarcodeFromPdf(string filePath): 從PDF文件中讀取條碼。

對於高量場景,考慮使用裁剪區域來提高處理速度最多5倍,當條碼位置可預測時。 您還可以創建條碼影像以多種格式儲存條碼。 該程式庫支援從System.Drawing物件中讀取,並且可以匯出條碼為HTMLPDF文件

如何經由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; }
}
$vbLabelText   $csharpLabel

API在Swagger UI中如何顯示?

Swagger UI顯示BarcoderScannerSDK API,包含兩個POST端點,用於從影像和PDF中讀取條碼,具有檔上傳界面和請求配置選項

API的回應是什麼樣的?

API文檔顯示成功POST請求到條碼閱讀端點並返回'Hello World!',狀態為200 OK

此API公開POST端點,您可以上傳條碼影像,API會返回條碼數據。 實施包括正確的驗證、錯誤處理和生產使用的日誌記錄。 針對移動應用程式,考慮添加針對較小影像尺寸和更快回應時間改進的端點。 您還可以從數據創建條碼或將其匯出為HTMLPDF。 對於高對比度需求,生成1-BPP條碼影像。## 我可以添加那些進階功能?

為了進一步改進您的SDK,請考慮使用IronBarcode的完整API參考實施這些生產就緒功能。 探索功能總覽,查看示範以獲得實用的實施:

如何支持多種條碼類型?

IronBarcode支持同時讀取多個條碼。 您可以將SDK配置為一次接受多個條碼,並進行特定格式過濾。 該程式庫支持書寫Unicode條碼,包括中文和阿拉伯文字符。 對於特殊化的應用程式,請探索Code 39閱讀創建QR碼與自定義樣式:

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;
    }
}
$vbLabelText   $csharpLabel

我應該考慮哪些其他改善?

對於生產部署,考慮實施信心門檻以減少誤報並確保資料準確性。 基於機器學習的檢測可針對您的特定使用案例進行微調。 創建部署包時,遵循MSI安裝指南並解決任何缺失的DLL問題。 對於AWS部署,要注意可能的運行時間問題。 考慮創建條碼,使用各種輸出數據格式,並探索條碼閱讀教程

我應該注意哪些授權考量?

如前所述,IronBarcode SDK旨在整合到您的內部應用程式中,通過API曝光需要額外的授權。 在將IronBarcode作為服務(如公共API)的組成部分暴露之前,您必須取得必要的授權(SDK、OEM或SaaS)。 對於企業部署,考慮可用的授權擴展,以增加座位或提升支持。 檢視升級選項以進行部署擴展。

請勿作為獨立SDK轉售IronBarcode 或公開面向API出口其,未確保您的授權涵蓋此用法。 對於網頁應用程式,您可能需要在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 類,並定義使用 ReadBarcodeFromImageReadBarcodeFromStream 等方法讀取條碼的 API 端點。

使用 .NET 條碼庫可以讀取哪些條碼類型?

如 IronBarcode 的 .NET 條碼庫可以讀取各種條碼類型,包括 QR 碼,Code 128,UPC,和 EAN。您可以通過設置檢測參數來配置庫同時檢測多種條碼類型。

如何在 .NET 中處理讀取條碼時的錯誤?

可以通過在您的條碼掃描方法中實施強大的錯誤處理來處理條碼閱讀中的錯誤,使用 IronBarcode。確保捕捉異常並提供有意義的反饋或重試機制,提升條碼閱讀過程的可靠性。

使用 .NET 條碼庫建構公共 API 的許可要求是什麼?

在公共 API 中使用 IronBarcode 時,必須確保適當的許可權。這包括獲取 SDK、OEM 或 SaaS 許可,因為將庫的功能作為獨立服務或公共 API 曝光需要額外的許可。

我可以使用 .NET 庫批量處理多個條碼掃描嗎?

可以,您可以使用 IronBarcode 批量處理多個條碼掃描。該庫允許您在一個操作中讀取多個條碼,這在有效處理大量圖像或文件時特別有用。

是否有 .NET 條碼庫的試用版本?

有的,IronBarcode 提供免費試用版,讓您能夠探索其在 .NET 應用程式中生成、閱讀和編輯條碼的能力。這個試用版可以幫助您在做購買決定前評估該庫。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担產品测测试,產品開發和研究的责任時,Jordi 為持续的產品改進增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我