Skip to footer content
USING IRONBARCODE

Develop a RESTful Barcode Scanner API with IronBarcode and ASP.NET Core

Create a RESTful barcode scanner API using IronBarcode and ASP.NET Core to manage barcodes from images, PDFs, and damaged scans without hardware, ensuring reliable performance across Windows, Linux, and macOS.

IronBarcode enables professional barcode scanning through RESTful APIs in ASP.NET Core, processing images, PDFs, and damaged scans without hardware dependencies while supporting cross-platform deployment with built-in security and compliance features.

The Enterprise Barcode Challenge

Imagine being the Enterprise Architect at a Fortune 500 logistics company. Your warehouse teams struggle with damaged shipping labels, your finance department needs to process thousands of invoiced PDFs with embedded barcodes, and your IT security team demands a solution that meets SOC2 compliance without introducing hardware dependencies across your global infrastructure.

This scenario led one of our enterprise clients to discover IronBarcode's REST API capabilities. What began as a simple requirement to read barcodes evolved into a complete scanning solution that now processes over 2 million barcodes monthly across their organization.

Traditionally, this would have required expensive hardware scanners at each location, complex driver management, and significant security reviews. Instead, they built a centralized RESTful API that any department could securely access, whether scanning damaged warehouse labels or extracting invoice data from supplier PDFs.

This tutorial guides you through building that same professional barcode scanner API. You'll learn how to create secure endpoints that handle real-world challenges like torn labels, skewed images, and multi-page documents. More importantly, you'll see how to implement this with the security, scalability, and vendor stability that enterprise environments demand.

Building a Reliable C# Scanner API

Creating an enterprise barcode scanner API requires addressing several critical concerns upfront. Security teams need assurance about data handling. Compliance officers require audit trails. Operations teams demand reliability across different platforms. IronBarcode's complete documentation addresses each of these concerns systematically.

The beauty of a RESTful approach lies in its simplicity and security. By centralizing barcode processing behind secure API endpoints, you maintain complete control over data flow. No client devices need direct access to your barcode processing logic. This architecture naturally supports your zero-trust security model while enabling smooth integration with existing enterprise systems.

Let's start with the foundation. IronBarcode's reading features support every major barcode format your enterprise might encounter. From traditional Code 39 barcodes used in manufacturing to modern QR codes in marketing campaigns, the library handles them all. The supported barcode formats guide provides a complete reference for planning your implementation.

What makes this particularly valuable for enterprise scenarios is the library's fault tolerance capabilities. Real-world barcodes aren't perfect. They get damaged, printed poorly, or scanned at angles. IronBarcode's advanced image processing handles these challenges automatically, reducing support tickets and improving operational efficiency.

Installing and Setting Up IronBarcode

Enterprise deployments require careful consideration of dependencies and licensing. IronBarcode simplifies this with straightforward NuGet installation and transparent licensing. Here's how to get started in your ASP.NET Core project:

Install-Package IronBarCode
Install-Package IronBarCode
SHELL

For enterprise environments with specific platform requirements, consult the advanced NuGet installation guide. This covers scenarios like targeting specific .NET versions or optimizing for particular platforms.

Once installed, verify your setup with a simple test. This code demonstrates the library's ability to read barcodes with minimal configuration:

using IronBarCode;

// Verify installation with a basic barcode read
public class InstallationTest
{
    public static void VerifySetup()
    {
        try
        {
            // Test with a sample barcode image
            var result = BarcodeReader.Read("test-barcode.png");

            if (result.Any())
            {
                Console.WriteLine($"Success! Detected: {result.First().Value}");
                Console.WriteLine($"Format: {result.First().BarcodeType}");
                Console.WriteLine($"Confidence: {result.First().Confidence}%");
            }
            else
            {
                Console.WriteLine("No barcode detected in test image");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Setup issue: {ex.Message}");
        }
    }
}
using IronBarCode;

// Verify installation with a basic barcode read
public class InstallationTest
{
    public static void VerifySetup()
    {
        try
        {
            // Test with a sample barcode image
            var result = BarcodeReader.Read("test-barcode.png");

            if (result.Any())
            {
                Console.WriteLine($"Success! Detected: {result.First().Value}");
                Console.WriteLine($"Format: {result.First().BarcodeType}");
                Console.WriteLine($"Confidence: {result.First().Confidence}%");
            }
            else
            {
                Console.WriteLine("No barcode detected in test image");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Setup issue: {ex.Message}");
        }
    }
}
$vbLabelText   $csharpLabel

This verification step is crucial for enterprise deployments. It confirms that the library is properly installed, licensed, and can access necessary system resources. The confidence score output helps establish baseline expectations for your specific barcode types.

For production deployments, review the licensing documentation carefully. Enterprise licenses support unlimited deployments within your organization, crucial for scaling across multiple data centers. The license key configuration guide explains various activation methods, including environment variables and configuration files that align with your DevOps practices.

Platform Compatibility for Enterprises

Your enterprise likely runs a heterogeneous environment. Development happens on Windows, staging runs on Linux containers, and some teams might use macOS. IronBarcode's cross-platform compatibility ensures consistent behavior across all these platforms.

For containerized deployments, the Docker setup guide provides specific instructions for Linux containers. This includes handling dependencies and optimizing image size for efficient cloud deployment. If you're deploying to Azure or AWS Lambda, platform-specific guides ensure optimal performance in these environments.

The library even supports mobile scenarios through .NET MAUI integration, enabling you to extend your barcode scanning capabilities to iOS and Android devices when field workers need mobile scanning capabilities.

Building a Complete Scanner API Controller

Let's build a production-ready scanner API that addresses real enterprise needs. This implementation includes proper error handling, security considerations, and performance optimizations:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using IronBarCode;
using System.Drawing;
using System.ComponentModel.DataAnnotations;

namespace BarcodeScannerAPI.Controllers
{
    [ApiController]
    [Route("api/v1/[controller]")]
    [Authorize] // Require authentication for all endpoints
    public class ScannerController : ControllerBase
    {
        private readonly ILogger<ScannerController> _logger;
        private readonly IConfiguration _configuration;

        public ScannerController(ILogger<ScannerController> logger, IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
        }

        // Enhanced result model with audit fields
        public class ScanResult
        {
            public bool Success { get; set; }
            public List<BarcodeData> Barcodes { get; set; } = new List<BarcodeData>();
            public string RequestId { get; set; } = Guid.NewGuid().ToString();
            public DateTime ProcessedAt { get; set; } = DateTime.UtcNow;
            public long ProcessingTimeMs { get; set; }
            public string ErrorMessage { get; set; }
            public Dictionary<string, object> Metadata { get; set; } = new Dictionary<string, object>();
        }

        public class BarcodeData
        {
            public string Value { get; set; }
            public string Format { get; set; }
            public double Confidence { get; set; }
            public Rectangle Location { get; set; }
            public int PageNumber { get; set; } // For PDF processing
        }

        // Input validation model
        public class ScanRequest
        {
            [Required]
            public IFormFile File { get; set; }

            [Range(1, 10)]
            public int MaxBarcodes { get; set; } = 5;

            public string[] ExpectedFormats { get; set; }

            public bool EnableImageCorrection { get; set; } = true;
        }

        [HttpPost("scan")]
        [RequestSizeLimit(52428800)] // 50MB limit
        public async Task<ActionResult<ScanResult>> ScanDocument([FromForm] ScanRequest request)
        {
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            var result = new ScanResult();

            try
            {
                // Validate file type for security
                var allowedExtensions = new[] { ".pdf", ".png", ".jpg", ".jpeg", ".gif", ".tiff", ".bmp" };
                var fileExtension = Path.GetExtension(request.File.FileName).ToLowerInvariant();

                if (!allowedExtensions.Contains(fileExtension))
                {
                    _logger.LogWarning($"Rejected file type: {fileExtension}");
                    return BadRequest(new ScanResult
                    {
                        Success = false,
                        ErrorMessage = "Unsupported file type. Allowed: PDF, PNG, JPG, GIF, TIFF, BMP"
                    });
                }

                // Process the file
                using var stream = new MemoryStream();
                await request.File.CopyToAsync(stream);
                var fileBytes = stream.ToArray();

                // Log for audit trail
                _logger.LogInformation($"Processing {request.File.FileName} ({fileBytes.Length} bytes) - RequestId: {result.RequestId}");

                // Configure scanner based on requirements
                var options = ConfigureOptions(request);

                // Handle different file types
                BarcodeResults scanResults;
                if (fileExtension == ".pdf")
                {
                    var pdfOptions = new PdfBarcodeReaderOptions
                    {
                        Scale = 3,
                        DPI = 300,
                        MaxThreads = 4
                    };
                    scanResults = BarcodeReader.ReadPdf(fileBytes, pdfOptions);
                }
                else
                {
                    scanResults = BarcodeReader.Read(fileBytes, options);
                }

                // Process results
                if (scanResults.Any())
                {
                    result.Success = true;
                    foreach (var barcode in scanResults.Take(request.MaxBarcodes))
                    {
                        result.Barcodes.Add(new BarcodeData
                        {
                            Value = barcode.Value,
                            Format = barcode.BarcodeType.ToString(),
                            Confidence = barcode.Confidence,
                            Location = barcode.Bounds,
                            PageNumber = barcode.PageNumber
                        });
                    }

                    result.Metadata["TotalFound"] = scanResults.Count();
                    result.Metadata["FileSize"] = fileBytes.Length;
                    result.Metadata["FileName"] = request.File.FileName;

                    _logger.LogInformation($"Successfully scanned {scanResults.Count()} barcodes - RequestId: {result.RequestId}");
                }
                else
                {
                    result.Success = false;
                    result.ErrorMessage = "No barcodes detected in the document";
                    _logger.LogWarning($"No barcodes found - RequestId: {result.RequestId}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Scanning error - RequestId: {result.RequestId}");
                result.Success = false;
                result.ErrorMessage = "An error occurred during processing";

                // Don't expose internal errors to clients
                if (_configuration.GetValue<bool>("DetailedErrors"))
                {
                    result.Metadata["Exception"] = ex.Message;
                }
            }
            finally
            {
                stopwatch.Stop();
                result.ProcessingTimeMs = stopwatch.ElapsedMilliseconds;
            }

            return result;
        }

        private BarcodeReaderOptions ConfigureOptions(ScanRequest request)
        {
            var options = new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.Balanced,
                ExpectMultipleBarcodes = request.MaxBarcodes > 1,
                RemoveFalsePositive = true,
                Multithreaded = true,
                MaxParallelThreads = Environment.ProcessorCount
            };

            // Apply format filtering if specified
            if (request.ExpectedFormats?.Any() == true)
            {
                var formats = BarcodeEncoding.None;
                foreach (var format in request.ExpectedFormats)
                {
                    if (Enum.TryParse<BarcodeEncoding>(format, true, out var encoding))
                    {
                        formats |= encoding;
                    }
                }
                options.ExpectBarcodeTypes = formats;
            }

            // Enable image correction for damaged barcodes
            if (request.EnableImageCorrection)
            {
                options.ImageFilters = new ImageFilterCollection
                {
                    new SharpenFilter(2),
                    new ContrastFilter(1.5f),
                    new BrightnessFilter(1.1f)
                };
                options.AutoRotate = true;
            }

            return options;
        }

        // Batch processing endpoint for high-volume scenarios
        [HttpPost("scan-batch")]
        [RequestSizeLimit(524288000)] // 500MB for batch operations
        public async Task<ActionResult<List<ScanResult>>> ScanBatch(List<IFormFile> files)
        {
            if (files == null || !files.Any())
            {
                return BadRequest("No files provided");
            }

            if (files.Count > 50)
            {
                return BadRequest("Maximum 50 files per batch");
            }

            var tasks = files.Select(file => ProcessFileAsync(file));
            var results = await Task.WhenAll(tasks);

            _logger.LogInformation($"Batch processed {files.Count} files, {results.Count(r => r.Success)} successful");

            return Ok(results);
        }

        private async Task<ScanResult> ProcessFileAsync(IFormFile file)
        {
            // Reuse the scanning logic
            var request = new ScanRequest 
            { 
                File = file,
                EnableImageCorrection = true 
            };
            var actionResult = await ScanDocument(request);

            if (actionResult.Result is OkObjectResult okResult)
            {
                return okResult.Value as ScanResult;
            }
            else if (actionResult.Result is BadRequestObjectResult badResult)
            {
                return badResult.Value as ScanResult;
            }

            return new ScanResult 
            { 
                Success = false, 
                ErrorMessage = "Processing failed" 
            };
        }
    }
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using IronBarCode;
using System.Drawing;
using System.ComponentModel.DataAnnotations;

namespace BarcodeScannerAPI.Controllers
{
    [ApiController]
    [Route("api/v1/[controller]")]
    [Authorize] // Require authentication for all endpoints
    public class ScannerController : ControllerBase
    {
        private readonly ILogger<ScannerController> _logger;
        private readonly IConfiguration _configuration;

        public ScannerController(ILogger<ScannerController> logger, IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
        }

        // Enhanced result model with audit fields
        public class ScanResult
        {
            public bool Success { get; set; }
            public List<BarcodeData> Barcodes { get; set; } = new List<BarcodeData>();
            public string RequestId { get; set; } = Guid.NewGuid().ToString();
            public DateTime ProcessedAt { get; set; } = DateTime.UtcNow;
            public long ProcessingTimeMs { get; set; }
            public string ErrorMessage { get; set; }
            public Dictionary<string, object> Metadata { get; set; } = new Dictionary<string, object>();
        }

        public class BarcodeData
        {
            public string Value { get; set; }
            public string Format { get; set; }
            public double Confidence { get; set; }
            public Rectangle Location { get; set; }
            public int PageNumber { get; set; } // For PDF processing
        }

        // Input validation model
        public class ScanRequest
        {
            [Required]
            public IFormFile File { get; set; }

            [Range(1, 10)]
            public int MaxBarcodes { get; set; } = 5;

            public string[] ExpectedFormats { get; set; }

            public bool EnableImageCorrection { get; set; } = true;
        }

        [HttpPost("scan")]
        [RequestSizeLimit(52428800)] // 50MB limit
        public async Task<ActionResult<ScanResult>> ScanDocument([FromForm] ScanRequest request)
        {
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            var result = new ScanResult();

            try
            {
                // Validate file type for security
                var allowedExtensions = new[] { ".pdf", ".png", ".jpg", ".jpeg", ".gif", ".tiff", ".bmp" };
                var fileExtension = Path.GetExtension(request.File.FileName).ToLowerInvariant();

                if (!allowedExtensions.Contains(fileExtension))
                {
                    _logger.LogWarning($"Rejected file type: {fileExtension}");
                    return BadRequest(new ScanResult
                    {
                        Success = false,
                        ErrorMessage = "Unsupported file type. Allowed: PDF, PNG, JPG, GIF, TIFF, BMP"
                    });
                }

                // Process the file
                using var stream = new MemoryStream();
                await request.File.CopyToAsync(stream);
                var fileBytes = stream.ToArray();

                // Log for audit trail
                _logger.LogInformation($"Processing {request.File.FileName} ({fileBytes.Length} bytes) - RequestId: {result.RequestId}");

                // Configure scanner based on requirements
                var options = ConfigureOptions(request);

                // Handle different file types
                BarcodeResults scanResults;
                if (fileExtension == ".pdf")
                {
                    var pdfOptions = new PdfBarcodeReaderOptions
                    {
                        Scale = 3,
                        DPI = 300,
                        MaxThreads = 4
                    };
                    scanResults = BarcodeReader.ReadPdf(fileBytes, pdfOptions);
                }
                else
                {
                    scanResults = BarcodeReader.Read(fileBytes, options);
                }

                // Process results
                if (scanResults.Any())
                {
                    result.Success = true;
                    foreach (var barcode in scanResults.Take(request.MaxBarcodes))
                    {
                        result.Barcodes.Add(new BarcodeData
                        {
                            Value = barcode.Value,
                            Format = barcode.BarcodeType.ToString(),
                            Confidence = barcode.Confidence,
                            Location = barcode.Bounds,
                            PageNumber = barcode.PageNumber
                        });
                    }

                    result.Metadata["TotalFound"] = scanResults.Count();
                    result.Metadata["FileSize"] = fileBytes.Length;
                    result.Metadata["FileName"] = request.File.FileName;

                    _logger.LogInformation($"Successfully scanned {scanResults.Count()} barcodes - RequestId: {result.RequestId}");
                }
                else
                {
                    result.Success = false;
                    result.ErrorMessage = "No barcodes detected in the document";
                    _logger.LogWarning($"No barcodes found - RequestId: {result.RequestId}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Scanning error - RequestId: {result.RequestId}");
                result.Success = false;
                result.ErrorMessage = "An error occurred during processing";

                // Don't expose internal errors to clients
                if (_configuration.GetValue<bool>("DetailedErrors"))
                {
                    result.Metadata["Exception"] = ex.Message;
                }
            }
            finally
            {
                stopwatch.Stop();
                result.ProcessingTimeMs = stopwatch.ElapsedMilliseconds;
            }

            return result;
        }

        private BarcodeReaderOptions ConfigureOptions(ScanRequest request)
        {
            var options = new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.Balanced,
                ExpectMultipleBarcodes = request.MaxBarcodes > 1,
                RemoveFalsePositive = true,
                Multithreaded = true,
                MaxParallelThreads = Environment.ProcessorCount
            };

            // Apply format filtering if specified
            if (request.ExpectedFormats?.Any() == true)
            {
                var formats = BarcodeEncoding.None;
                foreach (var format in request.ExpectedFormats)
                {
                    if (Enum.TryParse<BarcodeEncoding>(format, true, out var encoding))
                    {
                        formats |= encoding;
                    }
                }
                options.ExpectBarcodeTypes = formats;
            }

            // Enable image correction for damaged barcodes
            if (request.EnableImageCorrection)
            {
                options.ImageFilters = new ImageFilterCollection
                {
                    new SharpenFilter(2),
                    new ContrastFilter(1.5f),
                    new BrightnessFilter(1.1f)
                };
                options.AutoRotate = true;
            }

            return options;
        }

        // Batch processing endpoint for high-volume scenarios
        [HttpPost("scan-batch")]
        [RequestSizeLimit(524288000)] // 500MB for batch operations
        public async Task<ActionResult<List<ScanResult>>> ScanBatch(List<IFormFile> files)
        {
            if (files == null || !files.Any())
            {
                return BadRequest("No files provided");
            }

            if (files.Count > 50)
            {
                return BadRequest("Maximum 50 files per batch");
            }

            var tasks = files.Select(file => ProcessFileAsync(file));
            var results = await Task.WhenAll(tasks);

            _logger.LogInformation($"Batch processed {files.Count} files, {results.Count(r => r.Success)} successful");

            return Ok(results);
        }

        private async Task<ScanResult> ProcessFileAsync(IFormFile file)
        {
            // Reuse the scanning logic
            var request = new ScanRequest 
            { 
                File = file,
                EnableImageCorrection = true 
            };
            var actionResult = await ScanDocument(request);

            if (actionResult.Result is OkObjectResult okResult)
            {
                return okResult.Value as ScanResult;
            }
            else if (actionResult.Result is BadRequestObjectResult badResult)
            {
                return badResult.Value as ScanResult;
            }

            return new ScanResult 
            { 
                Success = false, 
                ErrorMessage = "Processing failed" 
            };
        }
    }
}
$vbLabelText   $csharpLabel

This professional implementation includes several critical features that production deployments require. Authentication ensures only authorized users can access the scanning service. Request size limits prevent denial-of-service attacks. Complete logging provides the audit trail that compliance teams need.

The structured response model returns not just barcode values, but confidence scores and location data. This metadata proves invaluable for quality assurance processes. When a supplier's barcode scans with low confidence, your system can flag it for manual review.

Professional Error Handling

Notice how the controller never exposes internal exception details to clients? This follows security best practices by preventing information leakage. The detailed logging captures everything needed for debugging while keeping error responses generic.

The RequestId field enables end-to-end tracing across your distributed systems. When a warehouse worker reports a scanning issue, your support team can quickly locate the exact request in your centralized logging system. This dramatically reduces mean time to resolution (MTTR) for production issues.

Performance monitoring through ProcessingTimeMs helps identify bottlenecks. If certain barcode types consistently take longer to process, you can adjust your reading speed settings accordingly. The reading speeds example demonstrates how different settings impact performance.

Handling Different Input Sources

Enterprise systems rarely standardize on a single format. Your scanner API needs to handle everything from high-resolution warehouse cameras to low-quality PDF scans from decades-old fax machines. Here's how to build that flexibility:

// Extended controller with multiple input handlers
[ApiController]
[Route("api/v1/[controller]")]
[Authorize]
public class AdvancedScannerController : ControllerBase
{
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly ILogger<AdvancedScannerController> _logger;

    public AdvancedScannerController(
        IHttpClientFactory httpClientFactory, 
        ILogger<AdvancedScannerController> logger)
    {
        _httpClientFactory = httpClientFactory;
        _logger = logger;
    }

    // Handle Base64 input (common in web applications)
    [HttpPost("scan-base64")]
    public ActionResult<ScanResult> ScanBase64([FromBody] Base64Request request)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        try
        {
            // Validate Base64 format
            var base64Data = request.ImageData;
            if (base64Data.Contains(","))
            {
                // Handle data URL format: "data:image/png;base64,..."
                base64Data = base64Data.Substring(base64Data.IndexOf(",") + 1);
            }

            var imageBytes = Convert.FromBase64String(base64Data);

            // Implement size validation
            if (imageBytes.Length > 10 * 1024 * 1024) // 10MB limit
            {
                return BadRequest(new ScanResult
                {
                    Success = false,
                    ErrorMessage = "Image size exceeds 10MB limit"
                });
            }

            // Configure for web-uploaded images (often lower quality)
            var options = new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.Detailed,
                ImageFilters = new ImageFilterCollection
                {
                    new SharpenFilter(3),
                    new ContrastFilter(2),
                    new DeNoise()
                },
                TryInvertColor = true, // Handle inverted barcodes
                AutoRotate = true
            };

            var results = BarcodeReader.Read(imageBytes, options);
            return ProcessResults(results, "base64", request.FileName);
        }
        catch (FormatException)
        {
            return BadRequest(new ScanResult
            {
                Success = false,
                ErrorMessage = "Invalid Base64 format"
            });
        }
    }

    // Handle URL input (for cloud storage integration)
    [HttpPost("scan-url")]
    public async Task<ActionResult<ScanResult>> ScanFromUrl([FromBody] UrlScanRequest request)
    {
        if (!Uri.TryCreate(request.Url, UriKind.Absolute, out var uri))
        {
            return BadRequest(new ScanResult
            {
                Success = false,
                ErrorMessage = "Invalid URL format"
            });
        }

        // Validate URL domain (security measure)
        var allowedDomains = _configuration.GetSection("AllowedDomains").Get<string[]>() 
            ?? new[] { "blob.core.windows.net", "s3.amazonaws.com" };

        if (!allowedDomains.Any(domain => uri.Host.EndsWith(domain)))
        {
            _logger.LogWarning($"Rejected URL from unauthorized domain: {uri.Host}");
            return BadRequest(new ScanResult
            {
                Success = false,
                ErrorMessage = "URL domain not authorized"
            });
        }

        try
        {
            using var httpClient = _httpClientFactory.CreateClient("BarcodeScanner");
            httpClient.Timeout = TimeSpan.FromSeconds(30);

            // Add headers to avoid being blocked
            httpClient.DefaultRequestHeaders.Add("User-Agent", "BarcodeScannerAPI/2.0");

            var response = await httpClient.GetAsync(uri);
            response.EnsureSuccessStatusCode();

            // Check content type
            var contentType = response.Content.Headers.ContentType?.MediaType;
            if (!IsValidContentType(contentType))
            {
                return BadRequest(new ScanResult
                {
                    Success = false,
                    ErrorMessage = $"Unsupported content type: {contentType}"
                });
            }

            var imageBytes = await response.Content.ReadAsByteArrayAsync();

            // Use async processing for better scalability
            var results = await BarcodeReader.ReadAsync(imageBytes);
            return ProcessResults(results, "url", uri.ToString());
        }
        catch (HttpRequestException ex)
        {
            _logger.LogError(ex, $"Failed to download from URL: {uri}");
            return BadRequest(new ScanResult
            {
                Success = false,
                ErrorMessage = "Failed to download image from URL"
            });
        }
        catch (TaskCanceledException)
        {
            return BadRequest(new ScanResult
            {
                Success = false,
                ErrorMessage = "Download timeout - file too large or slow connection"
            });
        }
    }

    // Handle multi-page PDFs with page-specific processing
    [HttpPost("scan-pdf-advanced")]
    public async Task<ActionResult<PdfScanResult>> ScanPdfAdvanced([FromForm] PdfScanRequest request)
    {
        using var stream = new MemoryStream();
        await request.File.CopyToAsync(stream);

        var pdfOptions = new PdfBarcodeReaderOptions
        {
            Scale = request.Scale ?? 3,
            DPI = request.DPI ?? 300,
            PageNumbers = request.PageNumbers,
            Password = request.Password,
            MaxThreads = Math.Min(request.MaxThreads ?? 4, Environment.ProcessorCount)
        };

        // For large PDFs, process in chunks
        if (stream.Length > 50 * 1024 * 1024) // 50MB
        {
            _logger.LogInformation($"Large PDF detected ({stream.Length / 1024 / 1024}MB), using chunked processing");
            pdfOptions.MaxThreads = 2; // Reduce memory pressure
        }

        var results = BarcodeReader.ReadPdf(stream.ToArray(), pdfOptions);

        // Group results by page
        var pageResults = results.GroupBy(r => r.PageNumber)
            .OrderBy(g => g.Key)
            .Select(g => new PageBarcodeResult
            {
                PageNumber = g.Key,
                BarcodeCount = g.Count(),
                Barcodes = g.Select(b => new BarcodeData
                {
                    Value = b.Value,
                    Format = b.BarcodeType.ToString(),
                    Confidence = b.Confidence,
                    Location = b.Bounds
                }).ToList()
            }).ToList();

        return Ok(new PdfScanResult
        {
            Success = true,
            TotalPages = pageResults.Count,
            TotalBarcodes = results.Count(),
            PageResults = pageResults,
            RequestId = Guid.NewGuid().ToString()
        });
    }

    // Handle damaged or low-quality barcodes
    [HttpPost("scan-damaged")]
    public async Task<ActionResult<ScanResult>> ScanDamagedBarcode([FromForm] IFormFile file)
    {
        using var stream = new MemoryStream();
        await file.CopyToAsync(stream);

        // Aggressive image correction for damaged barcodes
        var options = new BarcodeReaderOptions
        {
            Speed = ReadingSpeed.ExtremeDetail,
            ImageFilters = new ImageFilterCollection
            {
                new SharpenFilter(4),
                new ContrastFilter(3),
                new BrightnessFilter(1.5f),
                new BinaryThresholdFilter(128),
                new DeNoise(3)
            },
            TryInvertColor = true,
            AutoRotate = true,
            UseCode39ExtendedMode = true,
            RemoveFalsePositive = false, // Accept lower confidence
            Confidence = ConfidenceLevel.Low
        };

        var results = BarcodeReader.Read(stream.ToArray(), options);

        // If still no results, try with different threshold
        if (!results.Any())
        {
            options.ImageFilters = new ImageFilterCollection
            {
                new AdaptiveThresholdFilter(9),
                new MedianFilter(3),
                new Dilate(1)
            };

            results = BarcodeReader.Read(stream.ToArray(), options);
        }

        return ProcessResults(results, "damaged", file.FileName);
    }

    private bool IsValidContentType(string contentType)
    {
        var validTypes = new[]
        {
            "image/jpeg", "image/jpg", "image/png", "image/gif",
            "image/tiff", "image/bmp", "application/pdf"
        };
        return validTypes.Contains(contentType?.ToLower());
    }

    private ActionResult<ScanResult> ProcessResults(BarcodeResults results, string source, string identifier)
    {
        var scanResult = new ScanResult
        {
            Metadata = new Dictionary<string, object>
            {
                ["Source"] = source,
                ["Identifier"] = identifier,
                ["ProcessedAt"] = DateTime.UtcNow
            }
        };

        if (results.Any())
        {
            scanResult.Success = true;
            scanResult.Barcodes = results.Select(r => new BarcodeData
            {
                Value = r.Value,
                Format = r.BarcodeType.ToString(),
                Confidence = r.Confidence,
                Location = r.Bounds
            }).ToList();

            // Log low confidence results for quality monitoring
            var lowConfidence = results.Where(r => r.Confidence < 70).ToList();
            if (lowConfidence.Any())
            {
                _logger.LogWarning($"Low confidence barcodes detected: {lowConfidence.Count} of {results.Count()} from {identifier}");
            }
        }
        else
        {
            scanResult.Success = false;
            scanResult.ErrorMessage = "No barcodes detected";
        }

        return Ok(scanResult);
    }
}

// Request models
public class Base64Request
{
    [Required]
    public string ImageData { get; set; }
    public string FileName { get; set; }
}

public class UrlScanRequest
{
    [Required]
    [Url]
    public string Url { get; set; }
}

public class PdfScanRequest
{
    [Required]
    public IFormFile File { get; set; }
    public int? Scale { get; set; }
    public int? DPI { get; set; }
    public int[] PageNumbers { get; set; }
    public string Password { get; set; }
    public int? MaxThreads { get; set; }
}

// Response models
public class PdfScanResult : ScanResult
{
    public int TotalPages { get; set; }
    public int TotalBarcodes { get; set; }
    public List<PageBarcodeResult> PageResults { get; set; }
}

public class PageBarcodeResult
{
    public int PageNumber { get; set; }
    public int BarcodeCount { get; set; }
    public List<BarcodeData> Barcodes { get; set; }
}
// Extended controller with multiple input handlers
[ApiController]
[Route("api/v1/[controller]")]
[Authorize]
public class AdvancedScannerController : ControllerBase
{
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly ILogger<AdvancedScannerController> _logger;

    public AdvancedScannerController(
        IHttpClientFactory httpClientFactory, 
        ILogger<AdvancedScannerController> logger)
    {
        _httpClientFactory = httpClientFactory;
        _logger = logger;
    }

    // Handle Base64 input (common in web applications)
    [HttpPost("scan-base64")]
    public ActionResult<ScanResult> ScanBase64([FromBody] Base64Request request)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        try
        {
            // Validate Base64 format
            var base64Data = request.ImageData;
            if (base64Data.Contains(","))
            {
                // Handle data URL format: "data:image/png;base64,..."
                base64Data = base64Data.Substring(base64Data.IndexOf(",") + 1);
            }

            var imageBytes = Convert.FromBase64String(base64Data);

            // Implement size validation
            if (imageBytes.Length > 10 * 1024 * 1024) // 10MB limit
            {
                return BadRequest(new ScanResult
                {
                    Success = false,
                    ErrorMessage = "Image size exceeds 10MB limit"
                });
            }

            // Configure for web-uploaded images (often lower quality)
            var options = new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.Detailed,
                ImageFilters = new ImageFilterCollection
                {
                    new SharpenFilter(3),
                    new ContrastFilter(2),
                    new DeNoise()
                },
                TryInvertColor = true, // Handle inverted barcodes
                AutoRotate = true
            };

            var results = BarcodeReader.Read(imageBytes, options);
            return ProcessResults(results, "base64", request.FileName);
        }
        catch (FormatException)
        {
            return BadRequest(new ScanResult
            {
                Success = false,
                ErrorMessage = "Invalid Base64 format"
            });
        }
    }

    // Handle URL input (for cloud storage integration)
    [HttpPost("scan-url")]
    public async Task<ActionResult<ScanResult>> ScanFromUrl([FromBody] UrlScanRequest request)
    {
        if (!Uri.TryCreate(request.Url, UriKind.Absolute, out var uri))
        {
            return BadRequest(new ScanResult
            {
                Success = false,
                ErrorMessage = "Invalid URL format"
            });
        }

        // Validate URL domain (security measure)
        var allowedDomains = _configuration.GetSection("AllowedDomains").Get<string[]>() 
            ?? new[] { "blob.core.windows.net", "s3.amazonaws.com" };

        if (!allowedDomains.Any(domain => uri.Host.EndsWith(domain)))
        {
            _logger.LogWarning($"Rejected URL from unauthorized domain: {uri.Host}");
            return BadRequest(new ScanResult
            {
                Success = false,
                ErrorMessage = "URL domain not authorized"
            });
        }

        try
        {
            using var httpClient = _httpClientFactory.CreateClient("BarcodeScanner");
            httpClient.Timeout = TimeSpan.FromSeconds(30);

            // Add headers to avoid being blocked
            httpClient.DefaultRequestHeaders.Add("User-Agent", "BarcodeScannerAPI/2.0");

            var response = await httpClient.GetAsync(uri);
            response.EnsureSuccessStatusCode();

            // Check content type
            var contentType = response.Content.Headers.ContentType?.MediaType;
            if (!IsValidContentType(contentType))
            {
                return BadRequest(new ScanResult
                {
                    Success = false,
                    ErrorMessage = $"Unsupported content type: {contentType}"
                });
            }

            var imageBytes = await response.Content.ReadAsByteArrayAsync();

            // Use async processing for better scalability
            var results = await BarcodeReader.ReadAsync(imageBytes);
            return ProcessResults(results, "url", uri.ToString());
        }
        catch (HttpRequestException ex)
        {
            _logger.LogError(ex, $"Failed to download from URL: {uri}");
            return BadRequest(new ScanResult
            {
                Success = false,
                ErrorMessage = "Failed to download image from URL"
            });
        }
        catch (TaskCanceledException)
        {
            return BadRequest(new ScanResult
            {
                Success = false,
                ErrorMessage = "Download timeout - file too large or slow connection"
            });
        }
    }

    // Handle multi-page PDFs with page-specific processing
    [HttpPost("scan-pdf-advanced")]
    public async Task<ActionResult<PdfScanResult>> ScanPdfAdvanced([FromForm] PdfScanRequest request)
    {
        using var stream = new MemoryStream();
        await request.File.CopyToAsync(stream);

        var pdfOptions = new PdfBarcodeReaderOptions
        {
            Scale = request.Scale ?? 3,
            DPI = request.DPI ?? 300,
            PageNumbers = request.PageNumbers,
            Password = request.Password,
            MaxThreads = Math.Min(request.MaxThreads ?? 4, Environment.ProcessorCount)
        };

        // For large PDFs, process in chunks
        if (stream.Length > 50 * 1024 * 1024) // 50MB
        {
            _logger.LogInformation($"Large PDF detected ({stream.Length / 1024 / 1024}MB), using chunked processing");
            pdfOptions.MaxThreads = 2; // Reduce memory pressure
        }

        var results = BarcodeReader.ReadPdf(stream.ToArray(), pdfOptions);

        // Group results by page
        var pageResults = results.GroupBy(r => r.PageNumber)
            .OrderBy(g => g.Key)
            .Select(g => new PageBarcodeResult
            {
                PageNumber = g.Key,
                BarcodeCount = g.Count(),
                Barcodes = g.Select(b => new BarcodeData
                {
                    Value = b.Value,
                    Format = b.BarcodeType.ToString(),
                    Confidence = b.Confidence,
                    Location = b.Bounds
                }).ToList()
            }).ToList();

        return Ok(new PdfScanResult
        {
            Success = true,
            TotalPages = pageResults.Count,
            TotalBarcodes = results.Count(),
            PageResults = pageResults,
            RequestId = Guid.NewGuid().ToString()
        });
    }

    // Handle damaged or low-quality barcodes
    [HttpPost("scan-damaged")]
    public async Task<ActionResult<ScanResult>> ScanDamagedBarcode([FromForm] IFormFile file)
    {
        using var stream = new MemoryStream();
        await file.CopyToAsync(stream);

        // Aggressive image correction for damaged barcodes
        var options = new BarcodeReaderOptions
        {
            Speed = ReadingSpeed.ExtremeDetail,
            ImageFilters = new ImageFilterCollection
            {
                new SharpenFilter(4),
                new ContrastFilter(3),
                new BrightnessFilter(1.5f),
                new BinaryThresholdFilter(128),
                new DeNoise(3)
            },
            TryInvertColor = true,
            AutoRotate = true,
            UseCode39ExtendedMode = true,
            RemoveFalsePositive = false, // Accept lower confidence
            Confidence = ConfidenceLevel.Low
        };

        var results = BarcodeReader.Read(stream.ToArray(), options);

        // If still no results, try with different threshold
        if (!results.Any())
        {
            options.ImageFilters = new ImageFilterCollection
            {
                new AdaptiveThresholdFilter(9),
                new MedianFilter(3),
                new Dilate(1)
            };

            results = BarcodeReader.Read(stream.ToArray(), options);
        }

        return ProcessResults(results, "damaged", file.FileName);
    }

    private bool IsValidContentType(string contentType)
    {
        var validTypes = new[]
        {
            "image/jpeg", "image/jpg", "image/png", "image/gif",
            "image/tiff", "image/bmp", "application/pdf"
        };
        return validTypes.Contains(contentType?.ToLower());
    }

    private ActionResult<ScanResult> ProcessResults(BarcodeResults results, string source, string identifier)
    {
        var scanResult = new ScanResult
        {
            Metadata = new Dictionary<string, object>
            {
                ["Source"] = source,
                ["Identifier"] = identifier,
                ["ProcessedAt"] = DateTime.UtcNow
            }
        };

        if (results.Any())
        {
            scanResult.Success = true;
            scanResult.Barcodes = results.Select(r => new BarcodeData
            {
                Value = r.Value,
                Format = r.BarcodeType.ToString(),
                Confidence = r.Confidence,
                Location = r.Bounds
            }).ToList();

            // Log low confidence results for quality monitoring
            var lowConfidence = results.Where(r => r.Confidence < 70).ToList();
            if (lowConfidence.Any())
            {
                _logger.LogWarning($"Low confidence barcodes detected: {lowConfidence.Count} of {results.Count()} from {identifier}");
            }
        }
        else
        {
            scanResult.Success = false;
            scanResult.ErrorMessage = "No barcodes detected";
        }

        return Ok(scanResult);
    }
}

// Request models
public class Base64Request
{
    [Required]
    public string ImageData { get; set; }
    public string FileName { get; set; }
}

public class UrlScanRequest
{
    [Required]
    [Url]
    public string Url { get; set; }
}

public class PdfScanRequest
{
    [Required]
    public IFormFile File { get; set; }
    public int? Scale { get; set; }
    public int? DPI { get; set; }
    public int[] PageNumbers { get; set; }
    public string Password { get; set; }
    public int? MaxThreads { get; set; }
}

// Response models
public class PdfScanResult : ScanResult
{
    public int TotalPages { get; set; }
    public int TotalBarcodes { get; set; }
    public List<PageBarcodeResult> PageResults { get; set; }
}

public class PageBarcodeResult
{
    public int PageNumber { get; set; }
    public int BarcodeCount { get; set; }
    public List<BarcodeData> Barcodes { get; set; }
}
$vbLabelText   $csharpLabel

This complete implementation addresses real-world enterprise scenarios. The URL scanning endpoint includes domain validation to prevent server-side request forgery (SSRF) attacks. The Base64 handler strips data URL prefixes, common when receiving images from web applications.

The damaged barcode endpoint demonstrates IronBarcode's image correction capabilities. By applying multiple filters and trying different approaches, it can recover data from severely degraded images. This proves invaluable when dealing with old inventory labels or weather-damaged shipping documents.

Choosing Between PDF and Image Scanning

PDFs present unique challenges and opportunities in enterprise barcode scanning. Many business documents like invoices, shipping manifests, and compliance forms arrive as PDFs with embedded barcodes. The PDF barcode reading capabilities in IronBarcode handle these scenarios elegantly.

Consider a typical enterprise scenario: Your accounts payable department receives thousands of invoices monthly, each containing barcodes for automated processing. Some vendors send high-quality PDFs, others send scanned documents with varying quality.

The advanced PDF scanning endpoint handles both scenarios. For high-quality PDFs, standard settings work perfectly. For scanned documents, increasing the DPI and scale parameters improves detection rates. The page-specific processing enables you to extract barcodes from specific pages, useful when you know invoices always have barcodes on the first page.

The grouped results by page provide valuable context. Your workflow system can route documents based on which pages contain barcodes, automating document classification. This structured approach to multi-page document processing transforms manual processes into efficient automated workflows.

Efficiently Handling Multiple Barcodes

Enterprise documents often contain multiple barcodes serving different purposes. A shipping label might have a tracking barcode, a product barcode, and a destination barcode. Proper handling of multiple barcode scenarios requires thoughtful API design.

The batch processing endpoint demonstrates how to handle high-volume scenarios efficiently. By processing multiple files in parallel, you can dramatically reduce total processing time. The Task.WhenAll pattern ensures optimal resource utilization while maintaining system stability.

For creating barcodes in your applications, IronBarcode offers equally effective capabilities. Whether you need to generate 1D linear barcodes for inventory systems or create 2D matrix codes for mobile applications, the same simple API approach applies.

Improving Performance and Accuracy

Performance optimization in enterprise barcode scanning isn't just about speed—it's about finding the right balance for your specific use case. Let's explore advanced optimization techniques that can transform your scanning performance:

public class OptimizedScannerService
{
    private readonly ILogger<OptimizedScannerService> _logger;
    private readonly IMemoryCache _cache;

    public OptimizedScannerService(ILogger<OptimizedScannerService> logger, IMemoryCache cache)
    {
        _logger = logger;
        _cache = cache;
    }

    // Performance-optimized scanning with caching
    public async Task<ScanResult> ScanWithOptimizationsAsync(byte[] imageData, string cacheKey = null)
    {
        // Check cache for repeat scans
        if (!string.IsNullOrEmpty(cacheKey))
        {
            if (_cache.TryGetValue(cacheKey, out ScanResult cachedResult))
            {
                _logger.LogInformation($"Cache hit for {cacheKey}");
                cachedResult.Metadata["CacheHit"] = true;
                return cachedResult;
            }
        }

        // Determine optimal settings based on image characteristics
        var settings = await DetermineOptimalSettingsAsync(imageData);

        // Apply region-specific scanning if applicable
        if (settings.UseRegionScanning)
        {
            return await ScanWithRegionsAsync(imageData, settings);
        }

        // Standard optimized scanning
        var results = await BarcodeReader.ReadAsync(imageData, settings.Options);
        var scanResult = BuildScanResult(results);

        // Cache successful results
        if (!string.IsNullOrEmpty(cacheKey) && scanResult.Success)
        {
            _cache.Set(cacheKey, scanResult, TimeSpan.FromMinutes(5));
        }

        return scanResult;
    }

    // Intelligent settings determination
    private async Task<ScanSettings> DetermineOptimalSettingsAsync(byte[] imageData)
    {
        var settings = new ScanSettings();

        // Quick analysis of image properties
        using var ms = new MemoryStream(imageData);
        using var image = Image.FromStream(ms);

        var width = image.Width;
        var height = image.Height;
        var aspectRatio = (double)width / height;

        _logger.LogInformation($"Image analysis: {width}x{height}, ratio: {aspectRatio:F2}");

        // High-resolution images can use faster scanning
        if (width > 2000 && height > 2000)
        {
            settings.Options.Speed = ReadingSpeed.Faster;
            settings.Options.ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128;
        }
        // Low-resolution needs more processing
        else if (width < 800 || height < 800)
        {
            settings.Options.Speed = ReadingSpeed.ExtremeDetail;
            settings.Options.ImageFilters = new ImageFilterCollection
            {
                new SharpenFilter(3),
                new ContrastFilter(2)
            };
        }
        else
        {
            settings.Options.Speed = ReadingSpeed.Balanced;
        }

        // Detect if image might contain multiple barcodes based on aspect ratio
        if (aspectRatio > 2 || aspectRatio < 0.5)
        {
            settings.Options.ExpectMultipleBarcodes = true;
            settings.UseRegionScanning = true;
        }

        // Enable rotation correction for potentially skewed images
        settings.Options.AutoRotate = true;

        return settings;
    }

    // Region-based scanning for large images
    private async Task<ScanResult> ScanWithRegionsAsync(byte[] imageData, ScanSettings settings)
    {
        var allResults = new List<BarcodeResult>();
        using var ms = new MemoryStream(imageData);
        using var image = Image.FromStream(ms);

        // Define scanning regions for common document layouts
        var regions = new[]
        {
            new Rectangle(0, 0, image.Width / 2, image.Height / 2), // Top-left
            new Rectangle(image.Width / 2, 0, image.Width / 2, image.Height / 2), // Top-right
            new Rectangle(0, image.Height / 2, image.Width / 2, image.Height / 2), // Bottom-left
            new Rectangle(image.Width / 2, image.Height / 2, image.Width / 2, image.Height / 2), // Bottom-right
            new Rectangle(image.Width / 4, image.Height / 4, image.Width / 2, image.Height / 2) // Center
        };

        var tasks = regions.Select(async region =>
        {
            var regionOptions = new BarcodeReaderOptions
            {
                CropArea = region,
                Speed = ReadingSpeed.Faster,
                ExpectMultipleBarcodes = false
            };

            try
            {
                return await BarcodeReader.ReadAsync(imageData, regionOptions);
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"Region scan failed: {ex.Message}");
                return new BarcodeResult[0];
            }
        });

        var regionResults = await Task.WhenAll(tasks);

        // Combine and deduplicate results
        var uniqueResults = regionResults
            .SelectMany(r => r)
            .GroupBy(r => r.Value)
            .Select(g => g.OrderByDescending(r => r.Confidence).First())
            .ToList();

        return BuildScanResult(uniqueResults);
    }

    // Adaptive quality enhancement
    public async Task<ScanResult> ScanWithAdaptiveEnhancementAsync(byte[] imageData)
    {
        var attempts = new List<Func<Task<BarcodeResults>>>
        {
            // Attempt 1: Fast scan
            async () => await BarcodeReader.ReadAsync(imageData, new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.Faster,
                RemoveFalsePositive = true
            }),

            // Attempt 2: Standard scan with basic filters
            async () => await BarcodeReader.ReadAsync(imageData, new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.Balanced,
                ImageFilters = new ImageFilterCollection
                {
                    new ContrastFilter(1.5f),
                    new SharpenFilter(1)
                },
                TryInvertColor = true
            }),

            // Attempt 3: Detailed scan with aggressive filtering
            async () => await BarcodeReader.ReadAsync(imageData, new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.Detailed,
                ImageFilters = new ImageFilterCollection
                {
                    new AdaptiveThresholdFilter(11),
                    new DeNoise(2),
                    new MedianFilter(3)
                },
                AutoRotate = true,
                Confidence = ConfidenceLevel.Low
            }),

            // Attempt 4: Extreme processing for damaged barcodes
            async () => await BarcodeReader.ReadAsync(imageData, new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.ExtremeDetail,
                ImageFilters = new ImageFilterCollection
                {
                    new BinaryThresholdFilter(100),
                    new Erode(1),
                    new Dilate(2),
                    new SharpenFilter(4)
                },
                RemoveFalsePositive = false,
                UseCode39ExtendedMode = true,
                TryInvertColor = true
            })
        };

        foreach (var (attempt, index) in attempts.Select((a, i) => (a, i)))
        {
            var stopwatch = Stopwatch.StartNew();
            var results = await attempt();
            stopwatch.Stop();

            _logger.LogInformation($"Attempt {index + 1} took {stopwatch.ElapsedMilliseconds}ms, found {results.Count()} barcodes");

            if (results.Any())
            {
                var scanResult = BuildScanResult(results);
                scanResult.Metadata["AttemptNumber"] = index + 1;
                scanResult.Metadata["ProcessingStrategy"] = GetStrategyName(index);
                return scanResult;
            }
        }

        return new ScanResult
        {
            Success = false,
            ErrorMessage = "No barcodes found after all enhancement attempts"
        };
    }

    // Machine learning confidence optimization
    public class MLOptimizedScanner
    {
        private readonly Dictionary<string, double> _formatConfidenceThresholds = new()
        {
            { "QRCode", 85.0 },
            { "Code128", 90.0 },
            { "Code39", 88.0 },
            { "DataMatrix", 87.0 },
            { "EAN13", 92.0 },
            { "PDF417", 86.0 }
        };

        public async Task<ScanResult> ScanWithMLConfidenceAsync(byte[] imageData, string expectedFormat = null)
        {
            var options = new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.Balanced,
                Confidence = ConfidenceLevel.Optional
            };

            // If we know the expected format, improve for it
            if (!string.IsNullOrEmpty(expectedFormat) && 
                Enum.TryParse<BarcodeEncoding>(expectedFormat, out var encoding))
            {
                options.ExpectBarcodeTypes = encoding;
            }

            var results = await BarcodeReader.ReadAsync(imageData, options);

            // Apply ML confidence filtering
            var confidenceThreshold = expectedFormat != null && 
                _formatConfidenceThresholds.ContainsKey(expectedFormat)
                ? _formatConfidenceThresholds[expectedFormat]
                : 80.0;

            var highConfidenceResults = results
                .Where(r => r.Confidence >= confidenceThreshold)
                .ToList();

            if (highConfidenceResults.Any())
            {
                return BuildScanResult(highConfidenceResults);
            }

            // If no high-confidence results, include lower confidence with warnings
            var lowConfidenceResults = results
                .Where(r => r.Confidence < confidenceThreshold)
                .ToList();

            if (lowConfidenceResults.Any())
            {
                var result = BuildScanResult(lowConfidenceResults);
                result.Metadata["Warning"] = "Low confidence results - manual verification recommended";
                result.Metadata["MinConfidence"] = lowConfidenceResults.Min(r => r.Confidence);
                return result;
            }

            return new ScanResult
            {
                Success = false,
                ErrorMessage = "No barcodes met confidence threshold"
            };
        }
    }

    private ScanResult BuildScanResult(IEnumerable<BarcodeResult> results)
    {
        var resultList = results.ToList();
        return new ScanResult
        {
            Success = true,
            Barcodes = resultList.Select(r => new BarcodeData
            {
                Value = r.Value,
                Format = r.BarcodeType.ToString(),
                Confidence = r.Confidence,
                Location = r.Bounds
            }).ToList(),
            Metadata = new Dictionary<string, object>
            {
                ["TotalFound"] = resultList.Count,
                ["AverageConfidence"] = resultList.Average(r => r.Confidence),
                ["Formats"] = resultList.Select(r => r.BarcodeType.ToString()).Distinct().ToArray()
            }
        };
    }

    private string GetStrategyName(int attemptIndex)
    {
        return attemptIndex switch
        {
            0 => "FastScan",
            1 => "StandardEnhanced",
            2 => "DetailedFiltering",
            3 => "ExtremeDamageRecovery",
            _ => "Unknown"
        };
    }
}

// Supporting classes
public class ScanSettings
{
    public BarcodeReaderOptions Options { get; set; } = new BarcodeReaderOptions();
    public bool UseRegionScanning { get; set; }
    public List<Rectangle> CustomRegions { get; set; }
}

// Benchmark service for performance testing
public class BenchmarkService
{
    private readonly ILogger<BenchmarkService> _logger;

    public async Task<BenchmarkResult> BenchmarkSettingsAsync(byte[] testImage, int iterations = 10)
    {
        var results = new Dictionary<string, BenchmarkData>();

        var testConfigurations = new Dictionary<string, BarcodeReaderOptions>
        {
            ["Fastest"] = new() { Speed = ReadingSpeed.Faster },
            ["Balanced"] = new() { Speed = ReadingSpeed.Balanced },
            ["Detailed"] = new() { Speed = ReadingSpeed.Detailed },
            ["Parallel"] = new() { Speed = ReadingSpeed.Balanced, Multithreaded = true, MaxParallelThreads = 4 },
            ["Filtered"] = new() 
            { 
                Speed = ReadingSpeed.Balanced, 
                ImageFilters = new ImageFilterCollection { new SharpenFilter(2), new ContrastFilter(1.5f) } 
            }
        };

        foreach (var config in testConfigurations)
        {
            var times = new List<long>();
            var successCount = 0;

            for (int i = 0; i < iterations; i++)
            {
                var sw = Stopwatch.StartNew();
                var scanResults = await BarcodeReader.ReadAsync(testImage, config.Value);
                sw.Stop();

                times.Add(sw.ElapsedMilliseconds);
                if (scanResults.Any()) successCount++;

                // Small delay between tests
                await Task.Delay(100);
            }

            results[config.Key] = new BenchmarkData
            {
                AverageMs = times.Average(),
                MinMs = times.Min(),
                MaxMs = times.Max(),
                SuccessRate = (double)successCount / iterations * 100
            };
        }

        return new BenchmarkResult { Results = results };
    }
}

public class BenchmarkData
{
    public double AverageMs { get; set; }
    public long MinMs { get; set; }
    public long MaxMs { get; set; }
    public double SuccessRate { get; set; }
}

public class BenchmarkResult
{
    public Dictionary<string, BenchmarkData> Results { get; set; }
}
public class OptimizedScannerService
{
    private readonly ILogger<OptimizedScannerService> _logger;
    private readonly IMemoryCache _cache;

    public OptimizedScannerService(ILogger<OptimizedScannerService> logger, IMemoryCache cache)
    {
        _logger = logger;
        _cache = cache;
    }

    // Performance-optimized scanning with caching
    public async Task<ScanResult> ScanWithOptimizationsAsync(byte[] imageData, string cacheKey = null)
    {
        // Check cache for repeat scans
        if (!string.IsNullOrEmpty(cacheKey))
        {
            if (_cache.TryGetValue(cacheKey, out ScanResult cachedResult))
            {
                _logger.LogInformation($"Cache hit for {cacheKey}");
                cachedResult.Metadata["CacheHit"] = true;
                return cachedResult;
            }
        }

        // Determine optimal settings based on image characteristics
        var settings = await DetermineOptimalSettingsAsync(imageData);

        // Apply region-specific scanning if applicable
        if (settings.UseRegionScanning)
        {
            return await ScanWithRegionsAsync(imageData, settings);
        }

        // Standard optimized scanning
        var results = await BarcodeReader.ReadAsync(imageData, settings.Options);
        var scanResult = BuildScanResult(results);

        // Cache successful results
        if (!string.IsNullOrEmpty(cacheKey) && scanResult.Success)
        {
            _cache.Set(cacheKey, scanResult, TimeSpan.FromMinutes(5));
        }

        return scanResult;
    }

    // Intelligent settings determination
    private async Task<ScanSettings> DetermineOptimalSettingsAsync(byte[] imageData)
    {
        var settings = new ScanSettings();

        // Quick analysis of image properties
        using var ms = new MemoryStream(imageData);
        using var image = Image.FromStream(ms);

        var width = image.Width;
        var height = image.Height;
        var aspectRatio = (double)width / height;

        _logger.LogInformation($"Image analysis: {width}x{height}, ratio: {aspectRatio:F2}");

        // High-resolution images can use faster scanning
        if (width > 2000 && height > 2000)
        {
            settings.Options.Speed = ReadingSpeed.Faster;
            settings.Options.ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128;
        }
        // Low-resolution needs more processing
        else if (width < 800 || height < 800)
        {
            settings.Options.Speed = ReadingSpeed.ExtremeDetail;
            settings.Options.ImageFilters = new ImageFilterCollection
            {
                new SharpenFilter(3),
                new ContrastFilter(2)
            };
        }
        else
        {
            settings.Options.Speed = ReadingSpeed.Balanced;
        }

        // Detect if image might contain multiple barcodes based on aspect ratio
        if (aspectRatio > 2 || aspectRatio < 0.5)
        {
            settings.Options.ExpectMultipleBarcodes = true;
            settings.UseRegionScanning = true;
        }

        // Enable rotation correction for potentially skewed images
        settings.Options.AutoRotate = true;

        return settings;
    }

    // Region-based scanning for large images
    private async Task<ScanResult> ScanWithRegionsAsync(byte[] imageData, ScanSettings settings)
    {
        var allResults = new List<BarcodeResult>();
        using var ms = new MemoryStream(imageData);
        using var image = Image.FromStream(ms);

        // Define scanning regions for common document layouts
        var regions = new[]
        {
            new Rectangle(0, 0, image.Width / 2, image.Height / 2), // Top-left
            new Rectangle(image.Width / 2, 0, image.Width / 2, image.Height / 2), // Top-right
            new Rectangle(0, image.Height / 2, image.Width / 2, image.Height / 2), // Bottom-left
            new Rectangle(image.Width / 2, image.Height / 2, image.Width / 2, image.Height / 2), // Bottom-right
            new Rectangle(image.Width / 4, image.Height / 4, image.Width / 2, image.Height / 2) // Center
        };

        var tasks = regions.Select(async region =>
        {
            var regionOptions = new BarcodeReaderOptions
            {
                CropArea = region,
                Speed = ReadingSpeed.Faster,
                ExpectMultipleBarcodes = false
            };

            try
            {
                return await BarcodeReader.ReadAsync(imageData, regionOptions);
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"Region scan failed: {ex.Message}");
                return new BarcodeResult[0];
            }
        });

        var regionResults = await Task.WhenAll(tasks);

        // Combine and deduplicate results
        var uniqueResults = regionResults
            .SelectMany(r => r)
            .GroupBy(r => r.Value)
            .Select(g => g.OrderByDescending(r => r.Confidence).First())
            .ToList();

        return BuildScanResult(uniqueResults);
    }

    // Adaptive quality enhancement
    public async Task<ScanResult> ScanWithAdaptiveEnhancementAsync(byte[] imageData)
    {
        var attempts = new List<Func<Task<BarcodeResults>>>
        {
            // Attempt 1: Fast scan
            async () => await BarcodeReader.ReadAsync(imageData, new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.Faster,
                RemoveFalsePositive = true
            }),

            // Attempt 2: Standard scan with basic filters
            async () => await BarcodeReader.ReadAsync(imageData, new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.Balanced,
                ImageFilters = new ImageFilterCollection
                {
                    new ContrastFilter(1.5f),
                    new SharpenFilter(1)
                },
                TryInvertColor = true
            }),

            // Attempt 3: Detailed scan with aggressive filtering
            async () => await BarcodeReader.ReadAsync(imageData, new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.Detailed,
                ImageFilters = new ImageFilterCollection
                {
                    new AdaptiveThresholdFilter(11),
                    new DeNoise(2),
                    new MedianFilter(3)
                },
                AutoRotate = true,
                Confidence = ConfidenceLevel.Low
            }),

            // Attempt 4: Extreme processing for damaged barcodes
            async () => await BarcodeReader.ReadAsync(imageData, new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.ExtremeDetail,
                ImageFilters = new ImageFilterCollection
                {
                    new BinaryThresholdFilter(100),
                    new Erode(1),
                    new Dilate(2),
                    new SharpenFilter(4)
                },
                RemoveFalsePositive = false,
                UseCode39ExtendedMode = true,
                TryInvertColor = true
            })
        };

        foreach (var (attempt, index) in attempts.Select((a, i) => (a, i)))
        {
            var stopwatch = Stopwatch.StartNew();
            var results = await attempt();
            stopwatch.Stop();

            _logger.LogInformation($"Attempt {index + 1} took {stopwatch.ElapsedMilliseconds}ms, found {results.Count()} barcodes");

            if (results.Any())
            {
                var scanResult = BuildScanResult(results);
                scanResult.Metadata["AttemptNumber"] = index + 1;
                scanResult.Metadata["ProcessingStrategy"] = GetStrategyName(index);
                return scanResult;
            }
        }

        return new ScanResult
        {
            Success = false,
            ErrorMessage = "No barcodes found after all enhancement attempts"
        };
    }

    // Machine learning confidence optimization
    public class MLOptimizedScanner
    {
        private readonly Dictionary<string, double> _formatConfidenceThresholds = new()
        {
            { "QRCode", 85.0 },
            { "Code128", 90.0 },
            { "Code39", 88.0 },
            { "DataMatrix", 87.0 },
            { "EAN13", 92.0 },
            { "PDF417", 86.0 }
        };

        public async Task<ScanResult> ScanWithMLConfidenceAsync(byte[] imageData, string expectedFormat = null)
        {
            var options = new BarcodeReaderOptions
            {
                Speed = ReadingSpeed.Balanced,
                Confidence = ConfidenceLevel.Optional
            };

            // If we know the expected format, improve for it
            if (!string.IsNullOrEmpty(expectedFormat) && 
                Enum.TryParse<BarcodeEncoding>(expectedFormat, out var encoding))
            {
                options.ExpectBarcodeTypes = encoding;
            }

            var results = await BarcodeReader.ReadAsync(imageData, options);

            // Apply ML confidence filtering
            var confidenceThreshold = expectedFormat != null && 
                _formatConfidenceThresholds.ContainsKey(expectedFormat)
                ? _formatConfidenceThresholds[expectedFormat]
                : 80.0;

            var highConfidenceResults = results
                .Where(r => r.Confidence >= confidenceThreshold)
                .ToList();

            if (highConfidenceResults.Any())
            {
                return BuildScanResult(highConfidenceResults);
            }

            // If no high-confidence results, include lower confidence with warnings
            var lowConfidenceResults = results
                .Where(r => r.Confidence < confidenceThreshold)
                .ToList();

            if (lowConfidenceResults.Any())
            {
                var result = BuildScanResult(lowConfidenceResults);
                result.Metadata["Warning"] = "Low confidence results - manual verification recommended";
                result.Metadata["MinConfidence"] = lowConfidenceResults.Min(r => r.Confidence);
                return result;
            }

            return new ScanResult
            {
                Success = false,
                ErrorMessage = "No barcodes met confidence threshold"
            };
        }
    }

    private ScanResult BuildScanResult(IEnumerable<BarcodeResult> results)
    {
        var resultList = results.ToList();
        return new ScanResult
        {
            Success = true,
            Barcodes = resultList.Select(r => new BarcodeData
            {
                Value = r.Value,
                Format = r.BarcodeType.ToString(),
                Confidence = r.Confidence,
                Location = r.Bounds
            }).ToList(),
            Metadata = new Dictionary<string, object>
            {
                ["TotalFound"] = resultList.Count,
                ["AverageConfidence"] = resultList.Average(r => r.Confidence),
                ["Formats"] = resultList.Select(r => r.BarcodeType.ToString()).Distinct().ToArray()
            }
        };
    }

    private string GetStrategyName(int attemptIndex)
    {
        return attemptIndex switch
        {
            0 => "FastScan",
            1 => "StandardEnhanced",
            2 => "DetailedFiltering",
            3 => "ExtremeDamageRecovery",
            _ => "Unknown"
        };
    }
}

// Supporting classes
public class ScanSettings
{
    public BarcodeReaderOptions Options { get; set; } = new BarcodeReaderOptions();
    public bool UseRegionScanning { get; set; }
    public List<Rectangle> CustomRegions { get; set; }
}

// Benchmark service for performance testing
public class BenchmarkService
{
    private readonly ILogger<BenchmarkService> _logger;

    public async Task<BenchmarkResult> BenchmarkSettingsAsync(byte[] testImage, int iterations = 10)
    {
        var results = new Dictionary<string, BenchmarkData>();

        var testConfigurations = new Dictionary<string, BarcodeReaderOptions>
        {
            ["Fastest"] = new() { Speed = ReadingSpeed.Faster },
            ["Balanced"] = new() { Speed = ReadingSpeed.Balanced },
            ["Detailed"] = new() { Speed = ReadingSpeed.Detailed },
            ["Parallel"] = new() { Speed = ReadingSpeed.Balanced, Multithreaded = true, MaxParallelThreads = 4 },
            ["Filtered"] = new() 
            { 
                Speed = ReadingSpeed.Balanced, 
                ImageFilters = new ImageFilterCollection { new SharpenFilter(2), new ContrastFilter(1.5f) } 
            }
        };

        foreach (var config in testConfigurations)
        {
            var times = new List<long>();
            var successCount = 0;

            for (int i = 0; i < iterations; i++)
            {
                var sw = Stopwatch.StartNew();
                var scanResults = await BarcodeReader.ReadAsync(testImage, config.Value);
                sw.Stop();

                times.Add(sw.ElapsedMilliseconds);
                if (scanResults.Any()) successCount++;

                // Small delay between tests
                await Task.Delay(100);
            }

            results[config.Key] = new BenchmarkData
            {
                AverageMs = times.Average(),
                MinMs = times.Min(),
                MaxMs = times.Max(),
                SuccessRate = (double)successCount / iterations * 100
            };
        }

        return new BenchmarkResult { Results = results };
    }
}

public class BenchmarkData
{
    public double AverageMs { get; set; }
    public long MinMs { get; set; }
    public long MaxMs { get; set; }
    public double SuccessRate { get; set; }
}

public class BenchmarkResult
{
    public Dictionary<string, BenchmarkData> Results { get; set; }
}
$vbLabelText   $csharpLabel

This advanced optimization approach demonstrates several professional techniques. The intelligent settings determination analyzes image properties to select optimal processing parameters automatically. High-resolution images from modern cameras can use faster processing, while low-quality scans receive enhanced filtering.

Region-based scanning proves particularly effective for large format documents. By dividing the image into regions and processing them in parallel, you can achieve significant performance improvements. This technique works especially well for standardized forms where barcode locations are predictable.

Choosing the Right ReadingSpeed Setting

The adaptive enhancement approach tries progressively more aggressive processing techniques until successful. This ensures the fastest possible processing for good-quality barcodes while still handling damaged ones successfully. The confidence threshold feature uses machine learning to validate results, reducing false positives in production environments.

For specific optimization scenarios:

  • High-volume processing: Use ReadingSpeed.Faster with specific barcode type filtering
  • Mixed quality documents: Start with ReadingSpeed.Balanced and implement adaptive enhancement
  • Damaged or old barcodes: Use ReadingSpeed.ExtremeDetail with complete image filters
  • Real-time applications: Implement caching and region-based scanning for consistent performance

The benchmark service helps you make data-driven decisions about configuration. Run benchmarks with your actual barcode samples to find the optimal balance between speed and accuracy for your specific use case.

Impact of Image Filters

Image filters can dramatically improve recognition rates for challenging barcodes. The image correction documentation explains each filter's purpose. However, filters also increase processing time, so use them judiciously.

For enterprise deployments, consider implementing a tiered approach:

  1. Fast scan without filters for initial attempt
  2. Apply basic filters if the first attempt fails
  3. Use aggressive filtering only when necessary
  4. Cache results to avoid reprocessing

This strategy maintains fast average response times while still handling difficult cases successfully. The orientation correction feature proves particularly valuable for mobile-captured images where users might hold devices at various angles.

Creating QR Code Images in C

While scanning is crucial, many enterprise applications also need to generate barcodes. IronBarcode makes creation as straightforward as reading. Here's how to generate QR codes for various enterprise scenarios:

public class BarcodeGenerationService
{
    private readonly ILogger<BarcodeGenerationService> _logger;

    // Generate QR codes for asset tracking
    public byte[] GenerateAssetQRCode(AssetInfo asset)
    {
        // Create JSON payload with asset information
        var assetData = JsonSerializer.Serialize(new
        {
            Id = asset.AssetId,
            Type = asset.AssetType,
            Location = asset.CurrentLocation,
            LastMaintenance = asset.LastMaintenanceDate,
            Url = "___PROTECTED_URL_45___"
        });

        // Generate QR code with high error correction for durability
        var qrCode = QRCodeWriter.CreateQrCode(assetData, 500, QRCodeWriter.QrErrorCorrectionLevel.High);

        // Add company branding
        qrCode.AddAnnotationTextAboveBarcode($"ASSET: {asset.AssetId}");
        qrCode.AddAnnotationTextBelowBarcode(asset.AssetType);
        qrCode.SetMargins(10);

        // Style for printing on asset labels
        qrCode.ChangeBarCodeColor(Color.Black);
        qrCode.ChangeBackgroundColor(Color.White);

        return qrCode.ToStream().ToArray();
    }

    // Generate visitor badges with QR codes
    public GeneratedBarcode CreateVisitorBadgeQR(VisitorInfo visitor)
    {
        // Encode visitor information with expiration
        var visitorData = new
        {
            Name = visitor.Name,
            Company = visitor.Company,
            Host = visitor.HostEmployee,
            ValidFrom = visitor.CheckInTime,
            ValidUntil = visitor.CheckInTime.AddHours(8),
            AccessLevel = visitor.AccessLevel,
            BadgeId = Guid.NewGuid().ToString()
        };

        var qrCode = QRCodeWriter.CreateQrCode(
            JsonSerializer.Serialize(visitorData), 
            400, 
            QRCodeWriter.QrErrorCorrectionLevel.Medium
        );

        // Add company logo for professional appearance
        if (File.Exists("company-logo.png"))
        {
            qrCode.AddLogo("company-logo.png");
        }

        // Style for badge printing
        qrCode.SetMargins(15);
        qrCode.ChangeBarCodeColor(Color.FromArgb(0, 48, 135)); // Company blue

        // Add visible text for security personnel
        qrCode.AddAnnotationTextAboveBarcode($"VISITOR: {visitor.Name}");
        qrCode.AddAnnotationTextBelowBarcode($"Expires: {visitor.CheckInTime.AddHours(8):HH:mm}");

        _logger.LogInformation($"Generated visitor badge for {visitor.Name}, BadgeId: {visitorData.BadgeId}");

        return qrCode;
    }

    // Generate shipping labels with multiple barcodes
    public byte[] GenerateShippingLabel(ShippingInfo shipping)
    {
        // Create a PDF with multiple barcodes
        var pdf = new IronPdf.ChromePdfRenderer();

        // Generate tracking barcode (Code 128 for USPS/UPS compatibility)
        var trackingBarcode = BarcodeWriter.CreateBarcode(
            shipping.TrackingNumber, 
            BarcodeEncoding.Code128
        );
        trackingBarcode.ResizeTo(300, 75);
        trackingBarcode.SetMargins(5);

        // Generate postal code barcode
        var postalBarcode = BarcodeWriter.CreateBarcode(
            shipping.PostalCode,
            BarcodeEncoding.Code128
        );
        postalBarcode.ResizeTo(200, 50);

        // Generate QR code with complete shipping data
        var shippingData = JsonSerializer.Serialize(shipping);
        var qrCode = QRCodeWriter.CreateQrCode(shippingData, 200);

        // Combine into shipping label HTML
        var labelHtml = $@
        <html>
        <body style='font-family: Arial, sans-serif;'>
            <div style='border: 2px solid black; padding: 20px; width: 4in; height: 6in;'>
                <h2>SHIPPING LABEL</h2>
                <hr/>
                <p><strong>From:</strong><br/>{shipping.SenderAddress}</p>
                <p><strong>To:</strong><br/>{shipping.RecipientAddress}</p>
                <hr/>
                <div style='text-align: center;'>
                    <img src='{trackingBarcode.ToDataUrl()}' alt='Tracking barcode'/>
                    <p>Tracking: {shipping.TrackingNumber}</p>
                </div>
                <div style='margin-top: 20px;'>
                    <img src='{postalBarcode.ToDataUrl()}' alt='Postal barcode' style='float: left;'/>
                    <img src='{qrCode.ToDataUrl()}' alt='Shipping QR code' style='float: right; width: 100px;'/>
                </div>
                <div style='clear: both; margin-top: 20px; font-size: 10px;'>
                    <p>Service: {shipping.ServiceType} | Weight: {shipping.Weight}lbs</p>
                </div>
            </div>
        </body>
        </html>";

        return pdf.RenderHtmlAsPdf(labelHtml).BinaryData;
    }

    // Generate secure document QR codes with encryption
    public class SecureDocumentQR
    {
        private readonly byte[] _encryptionKey;

        public SecureDocumentQR(byte[] encryptionKey)
        {
            _encryptionKey = encryptionKey;
        }

        public GeneratedBarcode GenerateSecureDocumentQR(DocumentInfo document)
        {
            // Create document reference with security features
            var documentRef = new
            {
                DocumentId = document.Id,
                Type = document.DocumentType,
                CreatedDate = document.CreatedDate,
                Hash = ComputeDocumentHash(document),
                AccessUrl = "___PROTECTED_URL_46___",
                ValidUntil = DateTime.UtcNow.AddDays(30)
            };

            // Encrypt sensitive data
            var jsonData = JsonSerializer.Serialize(documentRef);
            var encryptedData = EncryptData(jsonData);

            // Generate QR with encrypted payload
            var qrCode = QRCodeWriter.CreateQrCode(
                Convert.ToBase64String(encryptedData),
                500,
                QRCodeWriter.QrErrorCorrectionLevel.High
            );

            // Add visual security indicators
            qrCode.ChangeBarCodeColor(Color.DarkGreen);
            qrCode.AddAnnotationTextAboveBarcode("SECURE DOCUMENT");
            qrCode.AddAnnotationTextBelowBarcode($"Expires: {documentRef.ValidUntil:yyyy-MM-dd}");

            return qrCode;
        }

        private string ComputeDocumentHash(DocumentInfo document)
        {
            using var sha256 = SHA256.Create();
            var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(document.Content ?? document.Id));
            return BitConverter.ToString(hash).Replace("-", "");
        }

        private byte[] EncryptData(string data)
        {
            // Simplified encryption - use proper encryption in production
            using var aes = Aes.Create();
            aes.Key = _encryptionKey;
            aes.GenerateIV();

            using var encryptor = aes.CreateEncryptor();
            var dataBytes = Encoding.UTF8.GetBytes(data);
            var encrypted = encryptor.TransformFinalBlock(dataBytes, 0, dataBytes.Length);

            // Prepend IV for decryption
            return aes.IV.Concat(encrypted).ToArray();
        }
    }

    // Batch generation for high-volume scenarios
    public async Task<List<GeneratedBarcode>> GenerateBatchQRCodesAsync(List<string> data, QRCodeOptions options)
    {
        var tasks = data.Select(item => Task.Run(() =>
        {
            var qr = QRCodeWriter.CreateQrCode(
                item, 
                options.Size, 
                options.ErrorCorrection
            );

            if (options.IncludeMargins)
                qr.SetMargins(options.MarginSize);

            if (options.CustomColor.HasValue)
                qr.ChangeBarCodeColor(options.CustomColor.Value);

            return qr;
        }));

        return (await Task.WhenAll(tasks)).ToList();
    }
}

// Supporting models
public class AssetInfo
{
    public string AssetId { get; set; }
    public string AssetType { get; set; }
    public string CurrentLocation { get; set; }
    public DateTime LastMaintenanceDate { get; set; }
}

public class VisitorInfo
{
    public string Name { get; set; }
    public string Company { get; set; }
    public string HostEmployee { get; set; }
    public DateTime CheckInTime { get; set; }
    public string AccessLevel { get; set; }
}

public class ShippingInfo
{
    public string TrackingNumber { get; set; }
    public string SenderAddress { get; set; }
    public string RecipientAddress { get; set; }
    public string PostalCode { get; set; }
    public string ServiceType { get; set; }
    public decimal Weight { get; set; }
}

public class DocumentInfo
{
    public string Id { get; set; }
    public string DocumentType { get; set; }
    public DateTime CreatedDate { get; set; }
    public string Content { get; set; }
}

public class QRCodeOptions
{
    public int Size { get; set; } = 400;
    public QRCodeWriter.QrErrorCorrectionLevel ErrorCorrection { get; set; } = QRCodeWriter.QrErrorCorrectionLevel.Medium;
    public bool IncludeMargins { get; set; } = true;
    public int MarginSize { get; set; } = 10;
    public Color? CustomColor { get; set; }
}
public class BarcodeGenerationService
{
    private readonly ILogger<BarcodeGenerationService> _logger;

    // Generate QR codes for asset tracking
    public byte[] GenerateAssetQRCode(AssetInfo asset)
    {
        // Create JSON payload with asset information
        var assetData = JsonSerializer.Serialize(new
        {
            Id = asset.AssetId,
            Type = asset.AssetType,
            Location = asset.CurrentLocation,
            LastMaintenance = asset.LastMaintenanceDate,
            Url = "___PROTECTED_URL_45___"
        });

        // Generate QR code with high error correction for durability
        var qrCode = QRCodeWriter.CreateQrCode(assetData, 500, QRCodeWriter.QrErrorCorrectionLevel.High);

        // Add company branding
        qrCode.AddAnnotationTextAboveBarcode($"ASSET: {asset.AssetId}");
        qrCode.AddAnnotationTextBelowBarcode(asset.AssetType);
        qrCode.SetMargins(10);

        // Style for printing on asset labels
        qrCode.ChangeBarCodeColor(Color.Black);
        qrCode.ChangeBackgroundColor(Color.White);

        return qrCode.ToStream().ToArray();
    }

    // Generate visitor badges with QR codes
    public GeneratedBarcode CreateVisitorBadgeQR(VisitorInfo visitor)
    {
        // Encode visitor information with expiration
        var visitorData = new
        {
            Name = visitor.Name,
            Company = visitor.Company,
            Host = visitor.HostEmployee,
            ValidFrom = visitor.CheckInTime,
            ValidUntil = visitor.CheckInTime.AddHours(8),
            AccessLevel = visitor.AccessLevel,
            BadgeId = Guid.NewGuid().ToString()
        };

        var qrCode = QRCodeWriter.CreateQrCode(
            JsonSerializer.Serialize(visitorData), 
            400, 
            QRCodeWriter.QrErrorCorrectionLevel.Medium
        );

        // Add company logo for professional appearance
        if (File.Exists("company-logo.png"))
        {
            qrCode.AddLogo("company-logo.png");
        }

        // Style for badge printing
        qrCode.SetMargins(15);
        qrCode.ChangeBarCodeColor(Color.FromArgb(0, 48, 135)); // Company blue

        // Add visible text for security personnel
        qrCode.AddAnnotationTextAboveBarcode($"VISITOR: {visitor.Name}");
        qrCode.AddAnnotationTextBelowBarcode($"Expires: {visitor.CheckInTime.AddHours(8):HH:mm}");

        _logger.LogInformation($"Generated visitor badge for {visitor.Name}, BadgeId: {visitorData.BadgeId}");

        return qrCode;
    }

    // Generate shipping labels with multiple barcodes
    public byte[] GenerateShippingLabel(ShippingInfo shipping)
    {
        // Create a PDF with multiple barcodes
        var pdf = new IronPdf.ChromePdfRenderer();

        // Generate tracking barcode (Code 128 for USPS/UPS compatibility)
        var trackingBarcode = BarcodeWriter.CreateBarcode(
            shipping.TrackingNumber, 
            BarcodeEncoding.Code128
        );
        trackingBarcode.ResizeTo(300, 75);
        trackingBarcode.SetMargins(5);

        // Generate postal code barcode
        var postalBarcode = BarcodeWriter.CreateBarcode(
            shipping.PostalCode,
            BarcodeEncoding.Code128
        );
        postalBarcode.ResizeTo(200, 50);

        // Generate QR code with complete shipping data
        var shippingData = JsonSerializer.Serialize(shipping);
        var qrCode = QRCodeWriter.CreateQrCode(shippingData, 200);

        // Combine into shipping label HTML
        var labelHtml = $@
        <html>
        <body style='font-family: Arial, sans-serif;'>
            <div style='border: 2px solid black; padding: 20px; width: 4in; height: 6in;'>
                <h2>SHIPPING LABEL</h2>
                <hr/>
                <p><strong>From:</strong><br/>{shipping.SenderAddress}</p>
                <p><strong>To:</strong><br/>{shipping.RecipientAddress}</p>
                <hr/>
                <div style='text-align: center;'>
                    <img src='{trackingBarcode.ToDataUrl()}' alt='Tracking barcode'/>
                    <p>Tracking: {shipping.TrackingNumber}</p>
                </div>
                <div style='margin-top: 20px;'>
                    <img src='{postalBarcode.ToDataUrl()}' alt='Postal barcode' style='float: left;'/>
                    <img src='{qrCode.ToDataUrl()}' alt='Shipping QR code' style='float: right; width: 100px;'/>
                </div>
                <div style='clear: both; margin-top: 20px; font-size: 10px;'>
                    <p>Service: {shipping.ServiceType} | Weight: {shipping.Weight}lbs</p>
                </div>
            </div>
        </body>
        </html>";

        return pdf.RenderHtmlAsPdf(labelHtml).BinaryData;
    }

    // Generate secure document QR codes with encryption
    public class SecureDocumentQR
    {
        private readonly byte[] _encryptionKey;

        public SecureDocumentQR(byte[] encryptionKey)
        {
            _encryptionKey = encryptionKey;
        }

        public GeneratedBarcode GenerateSecureDocumentQR(DocumentInfo document)
        {
            // Create document reference with security features
            var documentRef = new
            {
                DocumentId = document.Id,
                Type = document.DocumentType,
                CreatedDate = document.CreatedDate,
                Hash = ComputeDocumentHash(document),
                AccessUrl = "___PROTECTED_URL_46___",
                ValidUntil = DateTime.UtcNow.AddDays(30)
            };

            // Encrypt sensitive data
            var jsonData = JsonSerializer.Serialize(documentRef);
            var encryptedData = EncryptData(jsonData);

            // Generate QR with encrypted payload
            var qrCode = QRCodeWriter.CreateQrCode(
                Convert.ToBase64String(encryptedData),
                500,
                QRCodeWriter.QrErrorCorrectionLevel.High
            );

            // Add visual security indicators
            qrCode.ChangeBarCodeColor(Color.DarkGreen);
            qrCode.AddAnnotationTextAboveBarcode("SECURE DOCUMENT");
            qrCode.AddAnnotationTextBelowBarcode($"Expires: {documentRef.ValidUntil:yyyy-MM-dd}");

            return qrCode;
        }

        private string ComputeDocumentHash(DocumentInfo document)
        {
            using var sha256 = SHA256.Create();
            var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(document.Content ?? document.Id));
            return BitConverter.ToString(hash).Replace("-", "");
        }

        private byte[] EncryptData(string data)
        {
            // Simplified encryption - use proper encryption in production
            using var aes = Aes.Create();
            aes.Key = _encryptionKey;
            aes.GenerateIV();

            using var encryptor = aes.CreateEncryptor();
            var dataBytes = Encoding.UTF8.GetBytes(data);
            var encrypted = encryptor.TransformFinalBlock(dataBytes, 0, dataBytes.Length);

            // Prepend IV for decryption
            return aes.IV.Concat(encrypted).ToArray();
        }
    }

    // Batch generation for high-volume scenarios
    public async Task<List<GeneratedBarcode>> GenerateBatchQRCodesAsync(List<string> data, QRCodeOptions options)
    {
        var tasks = data.Select(item => Task.Run(() =>
        {
            var qr = QRCodeWriter.CreateQrCode(
                item, 
                options.Size, 
                options.ErrorCorrection
            );

            if (options.IncludeMargins)
                qr.SetMargins(options.MarginSize);

            if (options.CustomColor.HasValue)
                qr.ChangeBarCodeColor(options.CustomColor.Value);

            return qr;
        }));

        return (await Task.WhenAll(tasks)).ToList();
    }
}

// Supporting models
public class AssetInfo
{
    public string AssetId { get; set; }
    public string AssetType { get; set; }
    public string CurrentLocation { get; set; }
    public DateTime LastMaintenanceDate { get; set; }
}

public class VisitorInfo
{
    public string Name { get; set; }
    public string Company { get; set; }
    public string HostEmployee { get; set; }
    public DateTime CheckInTime { get; set; }
    public string AccessLevel { get; set; }
}

public class ShippingInfo
{
    public string TrackingNumber { get; set; }
    public string SenderAddress { get; set; }
    public string RecipientAddress { get; set; }
    public string PostalCode { get; set; }
    public string ServiceType { get; set; }
    public decimal Weight { get; set; }
}

public class DocumentInfo
{
    public string Id { get; set; }
    public string DocumentType { get; set; }
    public DateTime CreatedDate { get; set; }
    public string Content { get; set; }
}

public class QRCodeOptions
{
    public int Size { get; set; } = 400;
    public QRCodeWriter.QrErrorCorrectionLevel ErrorCorrection { get; set; } = QRCodeWriter.QrErrorCorrectionLevel.Medium;
    public bool IncludeMargins { get; set; } = true;
    public int MarginSize { get; set; } = 10;
    public Color? CustomColor { get; set; }
}
$vbLabelText   $csharpLabel

These generation examples demonstrate enterprise-specific use cases. Asset tracking QR codes include maintenance history and direct links to asset management systems. Visitor badges incorporate expiration times and access levels for security compliance. Shipping labels combine multiple barcode formats to meet carrier requirements.

The secure document QR implementation shows how to integrate encryption for sensitive data. This approach ensures that even if someone captures the QR code, they cannot access the information without proper decryption keys. This proves essential for compliance documents, financial records, or confidential communications.

Next Steps for Production Deployment

Building an enterprise barcode scanner API with IronBarcode provides a reliable foundation for digital transformation initiatives. The combination of complete format support, advanced image processing, and cross-platform compatibility addresses the complex requirements of modern enterprises.

Key takeaways for your implementation:

  1. Security First: Implement proper authentication, input validation, and audit logging from the start
  2. Performance Optimization: Use appropriate scanning speeds and caching strategies for your use case
  3. Error Handling: Build resilient systems that gracefully handle edge cases and provide meaningful feedback
  4. Scalability: Design with horizontal scaling in mind, utilizing async patterns and efficient resource management

For production deployments, consider these additional resources:

IronBarcode's enterprise features extend beyond basic scanning. The library's style customization capabilities enable branded barcode generation. Support for Unicode barcodes ensures global compatibility. Advanced features like barcode margins and error correction levels provide fine-grained control over output quality.

Enterprise Support and Resources

When implementing mission-critical barcode solutions, having reliable support matters. IronBarcode offers:

The process from manual barcode handling to automated API-driven processing transforms operational efficiency. Whether you're processing thousands of shipping documents, managing visitor access, or tracking enterprise assets, IronBarcode provides the reliability and features that enterprise environments demand.

Ready to transform your barcode processing? Get started with a free trial and experience the difference that professional barcode processing can make. The complete API documentation provides detailed implementation guidance, while the examples section offers ready-to-use code for common scenarios.

Your enterprise deserves a barcode solution that scales with your needs, maintains security compliance, and delivers consistent results across all platforms. IronBarcode provides exactly that—backed by a company committed to long-term support and continuous improvement. Start building your scanner API today and join thousands of enterprises that trust IronBarcode for their critical barcode processing needs.

Frequently Asked Questions

What is the main benefit of using IronBarcode for building a scanner API in C#?

IronBarcode allows developers to quickly create a powerful, production-ready barcode scanner API with minimal complexity. It simplifies the process by eliminating the need for complex scanner SDK integrations.

Can IronBarcode handle damaged barcode inputs?

Yes, IronBarcode is designed to process barcode data even from damaged scan inputs, ensuring high reliability in real-world applications.

What types of input can IronBarcode process in a C# scanner API?

IronBarcode can process barcode data from various inputs such as images and PDFs, offering versatile solutions for different scanning needs.

Is there a tutorial available for building a barcode scanner API using IronBarcode?

Yes, the web page provides a comprehensive tutorial with code examples to guide developers in building a RESTful barcode scanning endpoint using IronBarcode.

How quickly can a barcode scanner API be set up using IronBarcode?

With IronBarcode, developers can set up a barcode scanner API in minutes, streamlining development time and effort.

Does IronBarcode require any complex SDK integrations?

No, IronBarcode eliminates the need for complex scanner SDK integrations, making it easier for developers to implement barcode scanning functionality.

What programming language is used with IronBarcode for building a scanner API?

IronBarcode is used with C# to build a scanner API, leveraging the .NET framework for robust performance.

Jordi Bardia
Software Engineer
Jordi is most proficient in Python, C# and C++, when he isn’t leveraging his skills at Iron Software; he’s game programming. Sharing responsibilities for product testing, product development and research, Jordi adds immense value to continual product improvement. The varied experience keeps him challenged and engaged, and he ...
Read More