From 31ff0985b629869a5e7b66c048cad757cd69fbd3 Mon Sep 17 00:00:00 2001 From: agent-aspose-barcode-examples Date: Mon, 3 Aug 2026 00:42:32 +0500 Subject: [PATCH] =?UTF-8?q?feat(barcode-recognition-performance):=20Add=20?= =?UTF-8?q?69=20Aspose.BarCode=20.NET=20C#=20examples=20for=20Barcode=20Re?= =?UTF-8?q?cognition=20Performance=20=E2=80=94=20Aspose.BarCode=20for=20.N?= =?UTF-8?q?ET=2026.7.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...on-to-1-pixel-to-filter-sub-pixel-noise.cs | 49 ++--- ...match-typical-1d-barcode-element-widths.cs | 35 ++-- ...n-of-dark-barcodes-on-light-backgrounds.cs | 66 +++++-- ...enerate-csv-report-of-recognition-times.cs | 154 ++++++++------- ...m-0-to-2-pixels-on-false-positive-rates.cs | 151 ++++++-------- ...highperformance-and-highquality-presets.cs | 127 ++++++------ ...es-in-high-throughput-scanning-scenario.cs | 105 +++++----- ...nput-images-across-multiple-symbologies.cs | 164 +++++++--------- ...ets-using-stopwatch-timing-measurements.cs | 89 ++++----- ...-xdimension-is-set-to-1-versus-3-pixels.cs | 98 +++++----- ...dimension-mode-versus-default-detection.cs | 89 +++++---- ...-toggled-on-versus-off-for-noisy-images.cs | 130 ++++++++----- ...arcodes-under-identical-qualitysettings.cs | 118 ++++------- ...ition-of-blurred-qr-codes-in-jpeg-files.cs | 62 +++--- ...fine-one-pixel-wide-barcodes-accurately.cs | 58 +++--- ...ect-on-speed-for-large-code128-barcodes.cs | 119 ++++++----- ...s-highquality-preset-for-balanced-speed.cs | 48 +++-- ...ize-when-useminimalxdimension-is-active.cs | 111 ++++++----- ...barcode-scanning-of-animated-gif-frames.cs | 80 ++++---- ...zero-when-useminimalxdimension-is-false.cs | 103 ++++++---- ...o-restore-default-element-size-handling.cs | 88 ++++----- ...ed-for-barcode-detection-when-debugging.cs | 92 +++++---- ...gle-threaded-execution-on-set-of-images.cs | 125 +++++------- ...able-barcodes-during-debugging-sessions.cs | 58 ++++-- ...alxdimension-is-disabled-versus-enabled.cs | 79 ++++---- ...-datamatrix-codes-at-0-45-and-90-angles.cs | 132 +++++++++---- ...nts-were-detected-using-xdimension-mode.cs | 184 +++++++++++++----- ...us-xdimension-values-for-sample-dataset.cs | 110 +++++++---- ...idence-per-preset-across-test-image-set.cs | 118 ++++++----- ...alxdimension-values-used-for-each-image.cs | 88 ++++----- ...aults-before-processing-new-image-batch.cs | 128 +++++------- ...tral-rectangle-and-measure-time-savings.cs | 134 ++++++------- ...adata-does-not-affect-recognition-speed.cs | 129 +++++++++--- ...recognition-time-using-default-settings.cs | 60 +++--- ...-presets-to-evaluate-performance-impact.cs | 110 +++++++---- ...-72-dpi-to-300-dpi-on-detection-latency.cs | 110 ++++++----- ...rcodes-in-large-multi-page-pdf-document.cs | 102 +++++----- ...-detection-to-assess-performance-impact.cs | 109 +++++------ ...and-record-average-recognition-accuracy.cs | 131 +++++++------ ...preset-and-record-total-processing-time.cs | 78 ++++---- ...cpu-utilization-during-batch-processing.cs | 126 +++++++----- ...all-cpu-load-during-continuous-scanning.cs | 111 +++++------ ...ll-batch-processing-throughput-in-tests.cs | 81 ++++---- ...nition-time-with-highperformance-preset.cs | 146 +++++++++----- ...nder-each-preset-to-analyze-consistency.cs | 136 ++++--------- ...d-when-minimalxdimension-is-set-too-low.cs | 101 +++++----- ...r-each-preset-across-mixed-type-dataset.cs | 139 +++++++------ ...arcodes-to-assess-detection-reliability.cs | 54 ++--- ...ram-equalization-and-record-improvement.cs | 180 +++++++---------- ...ore-reading-batch-of-png-barcode-images.cs | 64 +++--- ...large-barcodes-in-high-resolution-scans.cs | 55 +++--- ...-and-log-any-barcodes-that-exceed-limit.cs | 104 +++++----- ...hen-scanning-high-resolution-tiff-files.cs | 30 ++- ...while-using-minimalxdimension-filtering.cs | 131 +++++++------ ...quality-threshold-for-reliable-scanning.cs | 108 +++++----- ...detection-of-sub-pixel-barcode-elements.cs | 73 ++++--- ...ixels-across-multiple-image-resolutions.cs | 96 ++++----- ...imension-using-large-mode-configuration.cs | 67 ++++--- ...-barcode-detection-versus-image-loading.cs | 81 ++++---- ...lter-decoded-codetext-of-valid-barcodes.cs | 83 ++++---- ...-consumption-patterns-during-processing.cs | 116 +++++++---- ...onfidence-of-correctly-decoded-barcodes.cs | 96 +++++---- ...codes-together-does-not-cause-conflicts.cs | 89 +++++---- ...ters-out-valid-barcodes-unintentionally.cs | 103 +++++----- ...not-corrupt-previously-obtained-results.cs | 123 ++++++------ ...highperformance-and-highquality-presets.cs | 76 +++++--- ...toggling-useminimalxdimension-correctly.cs | 116 +++++------ ...returns-barcoderesultconfidence-as-null.cs | 111 ++++------- ...-and-cpu-usage-for-each-processed-image.cs | 121 ++++++------ 69 files changed, 3698 insertions(+), 3340 deletions(-) diff --git a/barcode-recognition-performance/activate-qualitysettingsuseminimalxdimension-and-set-minimalxdimension-to-1-pixel-to-filter-sub-pixel-noise.cs b/barcode-recognition-performance/activate-qualitysettingsuseminimalxdimension-and-set-minimalxdimension-to-1-pixel-to-filter-sub-pixel-noise.cs index 23eaebf..e61b2b2 100644 --- a/barcode-recognition-performance/activate-qualitysettingsuseminimalxdimension-and-set-minimalxdimension-to-1-pixel-to-filter-sub-pixel-noise.cs +++ b/barcode-recognition-performance/activate-qualitysettingsuseminimalxdimension-and-set-minimalxdimension-to-1-pixel-to-filter-sub-pixel-noise.cs @@ -1,7 +1,8 @@ -// Title: Barcode Generation and Reading with Minimal XDimension Filtering -// Description: Demonstrates generating a Code128 barcode, saving it to an image, and reading it back while filtering sub‑pixel noise using QualitySettings.UseMinimalXDimension. +// Title: Minimal XDimension Filtering for Code128 Barcode Recognition +// Description: Demonstrates how to generate a Code128 barcode, save it as PNG, and recognize it while filtering sub‑pixel noise using QualitySettings. +// Category-Description: This example belongs to the Aspose.BarCode image generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes and BarCodeReader with QualitySettings to improve detection accuracy. Developers often need to fine‑tune XDimension settings to handle low‑resolution scans or noisy images, making this pattern common in barcode processing pipelines. // Prompt: Activate QualitySettings.UseMinimalXDimension and set MinimalXDimension to 1 pixel to filter sub‑pixel noise. -// Tags: code128, barcode generation, barcode recognition, minimalxdimension, qualitysettings, aspnet +// Tags: code128, generation, recognition, png, barcodegenerator, barcodereader, qualitysettings, xdimension using System; using System.IO; @@ -10,53 +11,45 @@ using Aspose.BarCode.BarCodeRecognition; /// -/// Example program that creates a Code128 barcode image and reads it back -/// using minimal XDimension filtering to suppress sub‑pixel noise. +/// Generates a Code128 barcode, saves it as an image, and reads it back using minimal XDimension filtering +/// to suppress sub‑pixel noise during recognition. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode, saves it, and then reads it with quality settings applied. + /// Entry point of the example. Executes barcode generation, saves the image, and performs recognition. /// static void Main() { - // ------------------------------------------------------------ - // 1. Generate a sample barcode image and save it to disk. - // ------------------------------------------------------------ - string imagePath = "sample.png"; - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // Define the output file path for the generated barcode image. + string imagePath = "sample_barcode.png"; + + // Generate a simple Code128 barcode with the value "123456" and save it as a PNG file. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) { - // Save the generated barcode as a PNG file. + // Additional image configuration (size, colors, etc.) can be set here if needed. generator.Save(imagePath); } - // ------------------------------------------------------------ - // 2. Verify that the barcode image was successfully created. - // ------------------------------------------------------------ + // Verify that the barcode image was successfully created. if (!File.Exists(imagePath)) { - Console.WriteLine($"Error: Barcode image not found at '{imagePath}'."); + Console.WriteLine($"Failed to create barcode image at '{imagePath}'."); return; } - // ------------------------------------------------------------ - // 3. Read the barcode with minimal XDimension filtering enabled. - // ------------------------------------------------------------ + // Initialize a BarCodeReader for the saved image, specifying that we expect a Code128 barcode. using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) { - // Activate UseMinimalXDimension mode to ignore sub‑pixel variations. + // Activate minimal XDimension filtering to ignore sub‑pixel noise. reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; + reader.QualitySettings.MinimalXDimension = 1f; // 1 pixel - // Set the minimal XDimension threshold to 1 pixel. - reader.QualitySettings.MinimalXDimension = 1f; - - // -------------------------------------------------------- - // 4. Process and output detected barcode information. - // -------------------------------------------------------- + // Perform barcode recognition and output the results. foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($"Detected CodeText: {result.CodeText}"); + Console.WriteLine($"Detected Type: {result.CodeTypeName}"); + Console.WriteLine($"Detected Text: {result.CodeText}"); } } } diff --git a/barcode-recognition-performance/adjust-qualitysettingsxdimension-to-3-pixels-to-match-typical-1d-barcode-element-widths.cs b/barcode-recognition-performance/adjust-qualitysettingsxdimension-to-3-pixels-to-match-typical-1d-barcode-element-widths.cs index 841a4b6..2fbbdf7 100644 --- a/barcode-recognition-performance/adjust-qualitysettingsxdimension-to-3-pixels-to-match-typical-1d-barcode-element-widths.cs +++ b/barcode-recognition-performance/adjust-qualitysettingsxdimension-to-3-pixels-to-match-typical-1d-barcode-element-widths.cs @@ -1,41 +1,40 @@ // Title: Generate Code128 Barcode with Custom XDimension -// Description: Demonstrates setting the XDimension to 3 pixels for a Code128 barcode and saving it as a PNG image. +// Description: Demonstrates how to generate a Code128 barcode image and set the XDimension to 3 pixels for proper 1D element width. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and QualitySettings to control barcode dimensions. Developers often need to customize module width (XDimension) to meet printing standards or scanner requirements. The snippet shows typical steps: creating a generator, disabling auto‑size, setting XDimension, and saving the image. // Prompt: Adjust QualitySettings.XDimension to 3 pixels to match typical 1D barcode element widths. -// Tags: code128, xdimension, barcode, generation, png, aspose.barcode +// Tags: barcode, code128, generation, png, xdimension, aspose.barcode, qualitysettings using System; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; /// -/// Example program that creates a Code128 barcode with a custom XDimension (module width) -/// and saves the result as a PNG file. +/// Example program that creates a Code128 barcode image with a custom XDimension. /// class Program { /// - /// Entry point of the application. Generates the barcode and writes a confirmation message. + /// Entry point of the application. Generates and saves a barcode PNG file. /// static void Main() { - // Initialize a barcode generator for Code128 with the sample text "1234567890". - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) - { - // Set XDimension to 3 pixels (module width) to match typical 1D barcode element widths. - generator.Parameters.Barcode.XDimension.Point = 3f; + // Define the output file path for the generated barcode image. + const string outputPath = "barcode.png"; - // Disable automatic sizing so that the custom XDimension is respected. + // Initialize a BarcodeGenerator for Code128 symbology with sample data. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + { + // Disable automatic sizing so the manually set XDimension is respected. generator.Parameters.AutoSizeMode = AutoSizeMode.None; - // Optionally set a bar height (in points) for better visual appearance. - generator.Parameters.Barcode.BarHeight.Point = 50f; + // Set the XDimension (module width) to 3 pixels, matching typical 1D barcode element widths. + generator.Parameters.Barcode.XDimension.Pixels = 3f; - // Save the generated barcode image to a PNG file. - generator.Save("code128_xdimension_3.png"); + // Save the barcode as a PNG image to the specified path. + generator.Save(outputPath, BarCodeImageFormat.Png); } - // Inform the user that the barcode has been generated. - Console.WriteLine("Barcode generated with XDimension set to 3 pixels."); + // Inform the user where the barcode image has been saved. + Console.WriteLine($"Barcode image saved to {outputPath}"); } } \ No newline at end of file diff --git a/barcode-recognition-performance/apply-custom-color-scheme-to-enhance-detection-of-dark-barcodes-on-light-backgrounds.cs b/barcode-recognition-performance/apply-custom-color-scheme-to-enhance-detection-of-dark-barcodes-on-light-backgrounds.cs index 6da023e..eb02163 100644 --- a/barcode-recognition-performance/apply-custom-color-scheme-to-enhance-detection-of-dark-barcodes-on-light-backgrounds.cs +++ b/barcode-recognition-performance/apply-custom-color-scheme-to-enhance-detection-of-dark-barcodes-on-light-backgrounds.cs @@ -1,42 +1,70 @@ -// Title: Custom Color Scheme for Barcode Generation -// Description: Demonstrates how to apply a dark bar color and a light background to improve detection of dark barcodes on light backgrounds. +// Title: Custom Color Barcode Generation and Recognition +// Description: Demonstrates generating a Code128 barcode with a dark bar color on a light background and recognizing it using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showcasing how to customize barcode appearance with BarColor and BackColor properties and adjust reader quality settings for improved detection. It uses BarcodeGenerator, BarCodeReader, and related parameter classes, useful for developers needing high‑contrast barcodes in varied lighting conditions. // Prompt: Apply a custom color scheme to enhance detection of dark barcodes on light backgrounds. -// Tags: code128, color, generation, png, aspose.barcode, aspose.drawing +// Tags: barcode symbology, generation, recognition, custom colors, code128, png, aspose.barcode using System; -using Aspose.BarCode; +using System.IO; using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Example program that generates a Code128 barcode with a custom dark bar color -/// and a light background to enhance contrast for detection on light surfaces. +/// Example program that creates a barcode with a custom color scheme and then reads it back. /// class Program { /// - /// Entry point of the application. Creates a barcode, applies custom colors, - /// and saves the result as a PNG image. + /// Entry point of the application. + /// Generates a Code128 barcode with dark bars on a light background, saves it as PNG, + /// and then uses BarCodeReader to detect and display the barcode information. /// static void Main() { - // Initialize a barcode generator for Code128 with the sample text "Sample123" - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // Define the output file path for the generated barcode image. + string imagePath = "custom_color_barcode.png"; + + // Create a barcode generator for Code128 symbology with the desired text. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "DarkOnLight")) { - // Set a dark bar color (dark blue) to stand out against a light background - generator.Parameters.Barcode.BarColor = Color.FromArgb(0, 0, 139); // DarkBlue + // Set the bar (foreground) color to a dark shade. + generator.Parameters.Barcode.BarColor = Color.DarkBlue; - // Set a light background color (light yellow) to improve contrast - generator.Parameters.BackColor = Color.FromArgb(255, 255, 224); // LightYellow + // Set the background color to a light shade for high contrast. + generator.Parameters.BackColor = Color.LightYellow; - // Optional: increase XDimension for larger modules, improving readability + // Optional: increase the module (X) dimension for better visibility. generator.Parameters.Barcode.XDimension.Point = 2f; - // Save the generated barcode image to a PNG file - generator.Save("custom_color_barcode.png"); + // Save the generated barcode image in PNG format. + generator.Save(imagePath, BarCodeImageFormat.Png); + } + + // Verify that the barcode image file was successfully created. + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Failed to create barcode image at '{imagePath}'."); + return; } - // Inform the user that the barcode has been generated - Console.WriteLine("Barcode generated with custom colors: custom_color_barcode.png"); + // Initialize a barcode reader to recognize any supported barcode type in the image. + using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + { + // Enhance detection settings for dark bars on a light background. + reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast; + reader.QualitySettings.AllowIncorrectBarcodes = true; + + // Iterate through all detected barcodes and output their details. + foreach (var result in reader.ReadBarCodes()) + { + Console.WriteLine($"Detected Type: {result.CodeType}"); + Console.WriteLine($"Detected Text: {result.CodeText}"); + + // Display the region (bounding rectangle) where the barcode was found. + var bounds = result.Region.Rectangle; + Console.WriteLine($"Region: X={bounds.X}, Y={bounds.Y}, Width={bounds.Width}, Height={bounds.Height}"); + } + } } } \ No newline at end of file diff --git a/barcode-recognition-performance/batch-process-directory-of-mixed-format-images-and-generate-csv-report-of-recognition-times.cs b/barcode-recognition-performance/batch-process-directory-of-mixed-format-images-and-generate-csv-report-of-recognition-times.cs index 89554c2..7464a66 100644 --- a/barcode-recognition-performance/batch-process-directory-of-mixed-format-images-and-generate-csv-report-of-recognition-times.cs +++ b/barcode-recognition-performance/batch-process-directory-of-mixed-format-images-and-generate-csv-report-of-recognition-times.cs @@ -1,107 +1,121 @@ // Title: Batch barcode recognition with CSV timing report -// Description: Demonstrates processing a directory of mixed‑format images, recognizing any barcodes, and writing a CSV file that records each barcode and the time taken for recognition. +// Description: Demonstrates processing a folder of mixed‑format barcode images, recognizing them, and creating a CSV file with recognition times. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases how to use BarcodeGenerator to create barcodes, BarCodeReader to decode them, and how to batch‑process multiple image formats. Developers often need to automate barcode scanning across large image sets and log performance metrics, which this snippet illustrates. // Prompt: Batch process a directory of mixed‑format images and generate a CSV report of recognition times. -// Tags: barcode, recognition, csv, batch, aspose.barcode, file-io +// Tags: barcode symbology, batch processing, csv report, aspose.barcode, generation, recognition using System; using System.IO; using System.Diagnostics; -using System.Linq; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Example program that scans a folder of images for barcodes, -/// measures recognition time for each file, and writes the results to a CSV report. +/// Example program that generates sample barcodes, scans them, and writes a CSV report +/// containing file name, recognition time, number of barcodes found, and the first barcode text. /// class Program { /// - /// Entry point of the application. - /// Accepts optional command‑line arguments for input directory and output CSV file. + /// Entry point of the application. Executes the sample generation, processing, and reporting workflow. /// - /// - /// args[0] – input directory (default: "Images") - /// args[1] – output CSV file path (default: "report.csv") - /// - static void Main(string[] args) + static void Main() { - // Determine input directory (first argument) or fall back to default "Images" - string inputDir = args.Length > 0 ? args[0] : "Images"; - - // Determine output CSV file (second argument) or fall back to default "report.csv" - string outputCsv = args.Length > 1 ? args[1] : "report.csv"; - - // Verify that the input directory exists - if (!Directory.Exists(inputDir)) + // -------------------------------------------------------------------- + // 1. Prepare a folder for sample barcode images + // -------------------------------------------------------------------- + string imagesFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(imagesFolder)) { - Console.WriteLine($"Input directory does not exist: {inputDir}"); - return; + Directory.CreateDirectory(imagesFolder); } - // Define supported image file extensions - string[] extensions = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".gif", ".tif", ".tiff" }; - - // Retrieve up to 10 image files matching the supported extensions - var files = Directory.GetFiles(inputDir) - .Where(f => extensions.Contains(Path.GetExtension(f).ToLowerInvariant())) - .Take(10) - .ToArray(); + // -------------------------------------------------------------------- + // 2. Generate a few sample barcode images of different formats + // -------------------------------------------------------------------- + GenerateSampleBarcodes(imagesFolder); - // Exit if no matching image files were found - if (files.Length == 0) - { - Console.WriteLine("No image files found to process."); - return; - } + // -------------------------------------------------------------------- + // 3. Prepare CSV report file and header line + // -------------------------------------------------------------------- + string csvPath = Path.Combine(Directory.GetCurrentDirectory(), "report.csv"); + var csvBuilder = new StringBuilder(); + csvBuilder.AppendLine("FileName,RecognitionTimeMs,BarcodesFound,FirstCodeText"); - // Open the CSV writer; using ensures the file is closed properly - using (StreamWriter writer = new StreamWriter(outputCsv)) + // -------------------------------------------------------------------- + // 4. Process PNG, JPG and BMP files in the images folder + // -------------------------------------------------------------------- + string[] patterns = new[] { "*.png", "*.jpg", "*.bmp" }; + foreach (string pattern in patterns) { - // Write CSV header row - writer.WriteLine("FileName,BarcodeType,CodeText,RecognitionTimeMs"); - - // Process each image file + string[] files = Directory.GetFiles(imagesFolder, pattern); foreach (string filePath in files) { - // Skip files that cannot be accessed if (!File.Exists(filePath)) { - Console.WriteLine($"File not found, skipping: {filePath}"); + Console.WriteLine($"File not found: {filePath}"); continue; } - // Start timing the recognition operation - Stopwatch sw = Stopwatch.StartNew(); - - // Initialize the barcode reader for all supported symbologies + // ------------------------------------------------------------ + // Measure recognition time for each image + // ------------------------------------------------------------ + var stopwatch = Stopwatch.StartNew(); using (BarCodeReader reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes)) { - // Perform barcode detection and collect results - var results = reader.ReadBarCodes().ToArray(); - sw.Stop(); // Stop timing after reading completes + var results = reader.ReadBarCodes(); + stopwatch.Stop(); + + int count = results.Length; + string firstCode = count > 0 ? results[0].CodeText : string.Empty; + long elapsedMs = stopwatch.ElapsedMilliseconds; - if (results.Length == 0) - { - // No barcode detected – log the file with empty fields - writer.WriteLine($"{Path.GetFileName(filePath)},,,{sw.ElapsedMilliseconds}"); - Console.WriteLine($"No barcode found in {Path.GetFileName(filePath)} (Time: {sw.ElapsedMilliseconds} ms)"); - } - else - { - // Write a CSV line for each detected barcode - foreach (var result in results) - { - // Escape commas in the decoded text to preserve CSV format - string codeText = result.CodeText?.Replace(",", ",") ?? string.Empty; - writer.WriteLine($"{Path.GetFileName(filePath)},{result.CodeTypeName},{codeText},{sw.ElapsedMilliseconds}"); - Console.WriteLine($"Processed {Path.GetFileName(filePath)} - Type: {result.CodeTypeName}, Text: {result.CodeText}, Time: {sw.ElapsedMilliseconds} ms"); - } - } + // -------------------------------------------------------- + // Append a line to the CSV report + // -------------------------------------------------------- + string fileName = Path.GetFileName(filePath); + csvBuilder.AppendLine($"{fileName},{elapsedMs},{count},{firstCode}"); } } } - // Inform the user where the CSV report was saved - Console.WriteLine($"CSV report generated at: {Path.GetFullPath(outputCsv)}"); + // -------------------------------------------------------------------- + // 5. Write CSV report to disk + // -------------------------------------------------------------------- + File.WriteAllText(csvPath, csvBuilder.ToString()); + Console.WriteLine($"Report generated at: {csvPath}"); + } + + /// + /// Generates a set of sample barcode images in the specified folder using various image formats. + /// + /// The directory where barcode images will be saved. + private static void GenerateSampleBarcodes(string folder) + { + // Sample data for barcodes + var samples = new[] + { + new { Text = "Sample001", Format = BarCodeImageFormat.Png, FileName = "barcode1.png" }, + new { Text = "Sample002", Format = BarCodeImageFormat.Jpeg, FileName = "barcode2.jpg" }, + new { Text = "Sample003", Format = BarCodeImageFormat.Bmp, FileName = "barcode3.bmp" }, + new { Text = "Sample004", Format = BarCodeImageFormat.Png, FileName = "barcode4.png" }, + new { Text = "Sample005", Format = BarCodeImageFormat.Jpeg, FileName = "barcode5.jpg" } + }; + + foreach (var sample in samples) + { + string filePath = Path.Combine(folder, sample.FileName); + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, sample.Text)) + { + // Optional: set some basic parameters for better readability + generator.Parameters.Barcode.XDimension.Point = 2f; + generator.Parameters.Barcode.BarHeight.Point = 40f; + + // Save the generated barcode image in the specified format + generator.Save(filePath, sample.Format); + } + } } } \ No newline at end of file diff --git a/barcode-recognition-performance/benchmark-effect-of-changing-minimalxdimension-from-0-to-2-pixels-on-false-positive-rates.cs b/barcode-recognition-performance/benchmark-effect-of-changing-minimalxdimension-from-0-to-2-pixels-on-false-positive-rates.cs index f02607e..f988416 100644 --- a/barcode-recognition-performance/benchmark-effect-of-changing-minimalxdimension-from-0-to-2-pixels-on-false-positive-rates.cs +++ b/barcode-recognition-performance/benchmark-effect-of-changing-minimalxdimension-from-0-to-2-pixels-on-false-positive-rates.cs @@ -1,129 +1,106 @@ -// Title: MinimalXDimension Benchmark for Barcode Detection -// Description: Demonstrates how changing MinimalXDimension from 0 to 2 pixels influences false positive detection when scanning barcode and blank images. +// Title: Benchmark MinimalXDimension impact on false positive rate +// Description: Demonstrates how changing MinimalXDimension from 0 to 2 pixels influences barcode recognition false positives using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator for creating Code128 barcodes, BarCodeReader for decoding, and QualitySettings to adjust MinimalXDimension. Developers often need to fine‑tune X‑dimension parameters to improve scan reliability in automated image processing pipelines. // Prompt: Benchmark the effect of changing MinimalXDimension from 0 to 2 pixels on false positive rates. -// Tags: barcode, minimalxdimension, benchmark, false-positive, csharp, aspose.barcode +// Tags: code128, minimalxdimension, false-positive, benchmark, generation, recognition, aspnet, aspose.barcode using System; using System.IO; -using Aspose.BarCode; +using System.Collections.Generic; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; -using Aspose.Drawing.Imaging; /// -/// Example program that benchmarks the impact of the MinimalXDimension setting on barcode detection -/// and false positive rates using Aspose.BarCode. +/// Generates a set of Code128 barcodes, then benchmarks recognition false‑positive rates +/// while varying the MinimalXDimension setting (0 px vs 2 px). /// class Program { /// - /// Entry point of the application. Generates test images, runs detection with different - /// MinimalXDimension values, and reports the results. + /// Entry point. Creates barcode images, runs recognition with two MinimalXDimension values, + /// and prints the false‑positive rate for each configuration. /// static void Main() { - // -------------------------------------------------------------------- - // Prepare a temporary folder for generated images - // -------------------------------------------------------------------- - string tempFolder = Path.Combine(Path.GetTempPath(), "AsposeBarcodeDemo"); - if (!Directory.Exists(tempFolder)) - { - Directory.CreateDirectory(tempFolder); - } - - // -------------------------------------------------------------------- - // Define file paths for the barcode image and a blank image - // -------------------------------------------------------------------- - string barcodePath = Path.Combine(tempFolder, "barcode.png"); - string blankPath = Path.Combine(tempFolder, "blank.png"); + // Prepare output folder for generated barcode images + string folder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(folder)) + Directory.CreateDirectory(folder); - // -------------------------------------------------------------------- - // Generate a simple Code128 barcode image - // -------------------------------------------------------------------- - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) - { - // Use a reasonable XDimension for visibility (2 points) - generator.Parameters.Barcode.XDimension.Point = 2f; - generator.Save(barcodePath, BarCodeImageFormat.Png); - } + // Create sample data strings (Test0 … Test4) + var samples = new List(); + for (int i = 0; i < 5; i++) + samples.Add("Test" + i); - // -------------------------------------------------------------------- - // Create a blank white image (contains no barcode) - // -------------------------------------------------------------------- - using (var bitmap = new Bitmap(200, 100)) + // Generate PNG barcodes with a fixed XDimension of 2 pixels + var imagePaths = new List(); + for (int i = 0; i < samples.Count; i++) { - using (var graphics = Graphics.FromImage(bitmap)) + string filePath = Path.Combine(folder, $"barcode_{i}.png"); + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, samples[i])) { - graphics.Clear(Color.White); + // Set module (X) size to 2 pixels + generator.Parameters.Barcode.XDimension.Point = 2f; + // Disable auto‑sizing to keep the XDimension exact + generator.Parameters.AutoSizeMode = AutoSizeMode.None; + // Save as PNG + generator.Save(filePath, BarCodeImageFormat.Png); } - bitmap.Save(blankPath, ImageFormat.Png); + imagePaths.Add(filePath); } - // -------------------------------------------------------------------- - // Define test configurations: MinimalXDimension values and image metadata - // -------------------------------------------------------------------- - float[] minimalXDimensions = new float[] { 0f, 2f }; - string[] imageLabels = new string[] { "Barcode Image", "Blank Image" }; - string[] imagePaths = new string[] { barcodePath, blankPath }; - - // -------------------------------------------------------------------- - // Run detection for each image under each MinimalXDimension setting - // -------------------------------------------------------------------- - Console.WriteLine("=== MinimalXDimension Benchmark ==="); - for (int i = 0; i < imagePaths.Length; i++) + // Benchmark recognition using MinimalXDimension = 0 px and 2 px + float[] minimalValues = new float[] { 0f, 2f }; + foreach (float minimal in minimalValues) { - Console.WriteLine($"\nTesting {imageLabels[i]}:"); - foreach (float minXDim in minimalXDimensions) - { - bool detected = TryDetectBarcode(imagePaths[i], minXDim); - string result = detected ? "Detected" : "Not Detected"; - Console.WriteLine($" MinimalXDimension = {minXDim} -> {result}"); - } - } + int falsePositives = 0; - // -------------------------------------------------------------------- - // Summarize false positive rates on the blank image - // -------------------------------------------------------------------- - int falsePositives = 0; - foreach (float minXDim in minimalXDimensions) - { - if (TryDetectBarcode(blankPath, minXDim)) + // Test each generated image + foreach (var path in imagePaths) { - falsePositives++; + // Extract the original sample index from the file name + string expected = Path.GetFileNameWithoutExtension(path).Replace("barcode_", ""); + int idx = int.Parse(expected); + string expectedText = samples[idx]; + + // Decode and validate; count as false positive if validation fails + bool success = ReadAndValidate(path, expectedText, minimal); + if (!success) + falsePositives++; } + + // Compute and display false‑positive percentage + double falseRate = (double)falsePositives / samples.Count * 100.0; + Console.WriteLine($"MinimalXDimension = {minimal} px -> False Positive Rate: {falseRate:F1}% ({falsePositives}/{samples.Count})"); } - Console.WriteLine($"\nFalse Positive Count on Blank Image: {falsePositives} out of {minimalXDimensions.Length} settings"); } /// - /// Attempts to read any barcode from the specified image using the given MinimalXDimension. - /// Returns true if at least one barcode is recognized. + /// Reads a barcode image using the specified MinimalXDimension and verifies that the decoded text matches the expected value. /// - /// Full path to the image file. - /// Minimal X dimension value to apply during recognition. - /// True if a barcode is detected; otherwise, false. - static bool TryDetectBarcode(string imagePath, float minimalXDimension) + /// Path to the barcode image file. + /// The text that should be decoded from the barcode. + /// MinimalXDimension value (in pixels) to apply during recognition. + /// True if the barcode is successfully decoded and matches the expected text; otherwise false. + static bool ReadAndValidate(string imagePath, string expectedText, float minimalXDimension) { - // Verify that the image file exists before attempting recognition if (!File.Exists(imagePath)) - { - Console.WriteLine($"Warning: File not found - {imagePath}"); return false; - } - // Initialize the barcode reader for all supported types - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) { - // Configure the reader to use MinimalXDimension mode with the supplied value + // Configure recognition to respect MinimalXDimension reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; reader.QualitySettings.MinimalXDimension = minimalXDimension; - // Perform the recognition - BarCodeResult[] results = reader.ReadBarCodes(); - - // Return true if any barcode was found - return results != null && results.Length > 0; + // Attempt to read barcodes; return true only on exact text match + foreach (var result in reader.ReadBarCodes()) + { + return string.Equals(result.CodeText, expectedText, StringComparison.Ordinal); + } } + + // No barcode detected or text mismatch + return false; } } \ No newline at end of file diff --git a/barcode-recognition-performance/benchmark-reading-speed-of-100-gif-barcode-images-under-highperformance-and-highquality-presets.cs b/barcode-recognition-performance/benchmark-reading-speed-of-100-gif-barcode-images-under-highperformance-and-highquality-presets.cs index ec484ab..769d02c 100644 --- a/barcode-recognition-performance/benchmark-reading-speed-of-100-gif-barcode-images-under-highperformance-and-highquality-presets.cs +++ b/barcode-recognition-performance/benchmark-reading-speed-of-100-gif-barcode-images-under-highperformance-and-highquality-presets.cs @@ -1,116 +1,103 @@ -// Title: Benchmark barcode reading speed for GIF images -// Description: Demonstrates measuring the time required to read 100 GIF barcode images using HighPerformance and HighQuality quality presets. +// Title: Benchmark reading speed of GIF barcode images with HighPerformance and HighQuality presets +// Description: Demonstrates measuring the time required to read a set of GIF barcode images using Aspose.BarCode with different quality presets. +// Category-Description: This example belongs to the Aspose.BarCode reading performance category, showcasing how to use BarCodeReader with QualitySettings presets (HighPerformance, HighQuality). It highlights typical use cases such as bulk barcode scanning, performance tuning, and benchmarking. Developers often need to evaluate trade‑offs between speed and accuracy when processing large image batches, and this snippet provides a reusable pattern for such assessments. // Prompt: Benchmark reading speed of 100 GIF barcode images under HighPerformance and HighQuality presets. -// Tags: barcode, reading, performance, gif, highperformance, highquality, aspnet.barcode, qualitysettings +// Tags: code128, benchmark, gif, highperformance, highquality, barcoderecognition, aspose.barcode using System; +using System.Collections.Generic; using System.Diagnostics; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing.Imaging; /// -/// Generates sample GIF barcode images and benchmarks the reading speed using -/// different presets (HighPerformance and HighQuality). +/// Provides a benchmark for reading GIF barcode images using different quality presets. /// class Program { - // Number of sample images to generate (kept small for runnable example) - const int SampleCount = 5; - - // Folder to store generated barcode images - const string ImagesFolder = "Barcodes"; - /// - /// Entry point of the program. Creates sample barcode images, then measures - /// the time required to read them with two quality presets. + /// Entry point of the benchmark application. /// static void Main() { - // Ensure the output folder exists - if (!Directory.Exists(ImagesFolder)) - { - Directory.CreateDirectory(ImagesFolder); - } + // Prepare a temporary folder for sample GIF images + string tempFolder = Path.Combine(Path.GetTempPath(), "AsposeBarcodeBenchmark"); + Directory.CreateDirectory(tempFolder); - // Generate sample GIF barcode images - GenerateSampleBarcodes(); + // Number of sample images (kept small for safe execution) + const int imageCount = 10; - // Retrieve all generated GIF files - string[] imageFiles = Directory.GetFiles(ImagesFolder, "*.gif"); - if (imageFiles.Length == 0) + // Generate sample GIF barcode images + var imageFiles = new List(); + for (int i = 0; i < imageCount; i++) { - Console.WriteLine("No barcode images found for benchmarking."); - return; + // Create a unique code text for each barcode + string codeText = $"CODE{i:D4}"; + // Define the file path for the GIF image + string filePath = Path.Combine(tempFolder, $"barcode_{i}.gif"); + // Generate the barcode and save it as a GIF + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + { + generator.Save(filePath, BarCodeImageFormat.Gif); + } + imageFiles.Add(filePath); } // Benchmark reading with the HighPerformance preset - BenchmarkReading("HighPerformance", QualitySettings.HighPerformance, imageFiles); + BenchmarkReading(imageFiles.ToArray(), QualitySettings.HighPerformance, "HighPerformance"); // Benchmark reading with the HighQuality preset - BenchmarkReading("HighQuality", QualitySettings.HighQuality, imageFiles); - } + BenchmarkReading(imageFiles.ToArray(), QualitySettings.HighQuality, "HighQuality"); - // Generates SampleCount barcode images in GIF format - static void GenerateSampleBarcodes() - { - for (int i = 0; i < SampleCount; i++) + // Cleanup generated files + foreach (var file in imageFiles) { - // Build the file path for the current barcode image - string filePath = Path.Combine(ImagesFolder, $"barcode_{i + 1}.gif"); - - // Use Code128 symbology with a simple numeric text - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i + 1}")) - { - // Save the generated barcode as a GIF file - generator.Save(filePath, BarCodeImageFormat.Gif); - } + try { File.Delete(file); } catch { /* ignore any deletion errors */ } } + try { Directory.Delete(tempFolder, true); } catch { /* ignore any deletion errors */ } } - // Benchmarks reading speed using the specified QualitySettings preset - static void BenchmarkReading(string presetName, QualitySettings preset, string[] files) + /// + /// Measures the time required to read barcodes from the specified files using a given quality preset. + /// + /// Array of image file paths to process. + /// QualitySettings preset to apply during reading. + /// Friendly name of the preset for reporting. + static void BenchmarkReading(string[] files, QualitySettings preset, string presetName) { - Stopwatch sw = new Stopwatch(); - int totalBarcodesDetected = 0; - - // Start timing the read operation - sw.Start(); - - foreach (string file in files) + // Validate that all files exist before processing + foreach (var f in files) { - // Verify that the file exists before attempting to read - if (!File.Exists(file)) + if (!File.Exists(f)) { - Console.WriteLine($"File not found: {file}"); - continue; + Console.WriteLine($"File not found: {f}"); + return; } + } + + // Start timing the reading operation + Stopwatch sw = Stopwatch.StartNew(); + int totalBarcodes = 0; - // Initialize the barcode reader for the current image file - using (var reader = new BarCodeReader(file)) + // Iterate over each image file and read barcodes + foreach (var file in files) + { + using (var reader = new BarCodeReader(file, DecodeType.AllSupportedTypes)) { // Apply the selected quality preset reader.QualitySettings = preset; - - // Iterate through all barcodes detected in the image + // Read all barcodes in the current image foreach (var result in reader.ReadBarCodes()) { - totalBarcodesDetected++; - - // Optionally, output each detected code text (commented out for speed) - // Console.WriteLine($"Detected: {result.CodeText}"); + totalBarcodes++; } } } - // Stop timing after all images have been processed + // Stop timing and report results sw.Stop(); - - // Output benchmark results - Console.WriteLine($"Preset: {presetName}"); - Console.WriteLine($"Processed {files.Length} images in {sw.Elapsed.TotalMilliseconds:F2} ms"); - Console.WriteLine($"Total barcodes detected: {totalBarcodesDetected}"); - Console.WriteLine(); + Console.WriteLine($"{presetName} preset: Processed {files.Length} images in {sw.ElapsedMilliseconds} ms, total barcodes read: {totalBarcodes}"); } } \ No newline at end of file diff --git a/barcode-recognition-performance/benchmark-time-saved-by-disabling-allowincorrectbarcodes-in-high-throughput-scanning-scenario.cs b/barcode-recognition-performance/benchmark-time-saved-by-disabling-allowincorrectbarcodes-in-high-throughput-scanning-scenario.cs index 88cd8db..2cca882 100644 --- a/barcode-recognition-performance/benchmark-time-saved-by-disabling-allowincorrectbarcodes-in-high-throughput-scanning-scenario.cs +++ b/barcode-recognition-performance/benchmark-time-saved-by-disabling-allowincorrectbarcodes-in-high-throughput-scanning-scenario.cs @@ -1,104 +1,103 @@ -// Title: Benchmarking AllowIncorrectBarcodes Impact on Scan Speed -// Description: Generates a set of Code128 barcodes, reads them with and without AllowIncorrectBarcodes, and measures the time difference to illustrate performance gains in high‑throughput scenarios. +// Title: Benchmark effect of AllowIncorrectBarcodes on barcode scanning performance +// Description: Demonstrates how disabling AllowIncorrectBarcodes can reduce processing time when scanning many Code128 barcodes. +// Category-Description: This example belongs to the Aspose.BarCode scanning performance category, illustrating the use of BarCodeReader, QualitySettings, and DecodeType classes to measure recognition speed. Developers often need to optimize high‑throughput barcode scanning by toggling AllowIncorrectBarcodes, which controls validation of barcode integrity. The snippet shows typical setup, generation, and timing of barcode reads for benchmarking purposes. // Prompt: Benchmark the time saved by disabling AllowIncorrectBarcodes in a high‑throughput scanning scenario. -// Tags: barcode, code128, performance, benchmark, allowincorrectbarcodes, Aspose.BarCode +// Tags: code128, scanning, performance, allowincorrectbarcodes, benchmark, aspose.barcode, generation, recognition using System; -using System.Collections.Generic; using System.Diagnostics; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; -using Aspose.Drawing.Imaging; /// -/// Demonstrates how disabling AllowIncorrectBarcodes can improve scanning performance -/// by benchmarking read operations on a collection of generated Code128 barcodes. +/// Generates a set of Code128 barcode images and benchmarks the impact of the +/// AllowIncorrectBarcodes setting on recognition speed using Aspose.BarCode. /// class Program { /// - /// Entry point of the example. Generates barcode images, runs two benchmarks + /// Entry point of the example. Creates sample barcodes, runs two benchmarks /// (with and without AllowIncorrectBarcodes), and prints the timing results. /// static void Main() { // -------------------------------------------------------------------- - // 1. Generate a small set of barcode images in memory. + // Prepare a folder for sample barcode images // -------------------------------------------------------------------- - var barcodeStreams = new List(); - for (int i = 0; i < 5; i++) + string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(folderPath)) { - // Create a barcode generator for Code128 with unique text. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Test{i}12345")) - { - // Set a simple size parameter (X-dimension) for readability. - generator.Parameters.Barcode.XDimension.Point = 2f; + Directory.CreateDirectory(folderPath); + } - // Render the barcode to a bitmap. - using (var bitmap = generator.GenerateBarCodeImage()) - { - // Save the bitmap to a memory stream in PNG format. - var ms = new MemoryStream(); - bitmap.Save(ms, ImageFormat.Png); - ms.Position = 0; // Reset position for later reading. - barcodeStreams.Add(ms); - } + // -------------------------------------------------------------------- + // Generate a small set of barcode images (5 items) + // -------------------------------------------------------------------- + const int sampleCount = 5; + for (int i = 0; i < sampleCount; i++) + { + string codeText = $"123456789{i}"; + string filePath = Path.Combine(folderPath, $"code{i}.png"); + + // Create a Code128 barcode and save it as PNG + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + { + generator.Save(filePath, BarCodeImageFormat.Png); } } // -------------------------------------------------------------------- - // 2. Benchmark reading with AllowIncorrectBarcodes disabled (default). + // Benchmark reading with AllowIncorrectBarcodes = false // -------------------------------------------------------------------- - long timeWithout = BenchmarkReading(barcodeStreams, allowIncorrect: false); + TimeSpan timeWithoutAllowIncorrect = BenchmarkReading(folderPath, allowIncorrect: false); // -------------------------------------------------------------------- - // 3. Benchmark reading with AllowIncorrectBarcodes enabled. + // Benchmark reading with AllowIncorrectBarcodes = true // -------------------------------------------------------------------- - long timeWith = BenchmarkReading(barcodeStreams, allowIncorrect: true); + TimeSpan timeWithAllowIncorrect = BenchmarkReading(folderPath, allowIncorrect: true); // -------------------------------------------------------------------- - // 4. Output the timing comparison. + // Output the results // -------------------------------------------------------------------- - Console.WriteLine($"Reading time without AllowIncorrectBarcodes: {timeWithout} ms"); - Console.WriteLine($"Reading time with AllowIncorrectBarcodes: {timeWith} ms"); - Console.WriteLine($"Time saved (approx.): {timeWithout - timeWith} ms"); + Console.WriteLine($"Reading time without AllowIncorrectBarcodes: {timeWithoutAllowIncorrect.TotalMilliseconds} ms"); + Console.WriteLine($"Reading time with AllowIncorrectBarcodes: {timeWithAllowIncorrect.TotalMilliseconds} ms"); + Console.WriteLine($"Time saved by disabling AllowIncorrectBarcodes: {(timeWithAllowIncorrect - timeWithoutAllowIncorrect).TotalMilliseconds} ms"); } /// - /// Measures the time required to read a collection of barcode streams using the specified - /// AllowIncorrectBarcodes setting. + /// Reads all PNG files in the specified folder using the given AllowIncorrectBarcodes setting + /// and returns the elapsed time. /// - /// The barcode image streams to be read. - /// If true, the reader will tolerate incorrect barcodes. - /// The elapsed time in milliseconds. - static long BenchmarkReading(List streams, bool allowIncorrect) + /// Path to the folder containing barcode images. + /// Whether to allow incorrect barcodes during recognition. + /// Time taken to read all barcodes. + static TimeSpan BenchmarkReading(string folderPath, bool allowIncorrect) { - var stopwatch = Stopwatch.StartNew(); + // Get all PNG files in the folder + string[] files = Directory.GetFiles(folderPath, "*.png"); + Stopwatch sw = new Stopwatch(); + sw.Start(); - foreach (var stream in streams) + // Process each file with BarCodeReader + foreach (string file in files) { - // Ensure the stream is positioned at the beginning before each read. - stream.Position = 0; - - // Initialize a barcode reader for Code128. - using (var reader = new BarCodeReader(stream, DecodeType.Code128)) + using (BarCodeReader reader = new BarCodeReader(file, DecodeType.Code128)) { - // Apply the quality setting based on the benchmark parameter. + // Apply the requested AllowIncorrectBarcodes setting reader.QualitySettings.AllowIncorrectBarcodes = allowIncorrect; - // Perform the read operation and iterate over all detected barcodes. - foreach (var result in reader.ReadBarCodes()) + // Perform recognition and access the result to ensure processing + foreach (BarCodeResult result in reader.ReadBarCodes()) { - // Access the result to simulate processing (e.g., logging). - Console.WriteLine($"Detected: {result.CodeText}"); + string _ = result.CodeText; } } } - stopwatch.Stop(); - return stopwatch.ElapsedMilliseconds; + sw.Stop(); + return sw.Elapsed; } } \ No newline at end of file diff --git a/barcode-recognition-performance/compare-barcode-detection-accuracy-between-grayscale-and-full-color-input-images-across-multiple-symbologies.cs b/barcode-recognition-performance/compare-barcode-detection-accuracy-between-grayscale-and-full-color-input-images-across-multiple-symbologies.cs index 653dba3..5217c39 100644 --- a/barcode-recognition-performance/compare-barcode-detection-accuracy-between-grayscale-and-full-color-input-images-across-multiple-symbologies.cs +++ b/barcode-recognition-performance/compare-barcode-detection-accuracy-between-grayscale-and-full-color-input-images-across-multiple-symbologies.cs @@ -1,9 +1,11 @@ -// Title: Barcode detection accuracy comparison between color and grayscale images -// Description: Generates barcodes in color and grayscale, then reads them to compare detection confidence and reading quality across multiple symbologies. +// Title: Compare barcode detection accuracy between grayscale and full‑color images +// Description: Demonstrates how to generate color and grayscale barcodes for multiple symbologies and compare detection confidence using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing the use of BarcodeGenerator, BarCodeReader, and related parameters to evaluate detection performance across different image types. Developers often need to verify that barcodes are readable in various color schemes, especially when integrating scanning functionality into applications that handle both color and grayscale assets. // Prompt: Compare barcode detection accuracy between grayscale and full‑color input images across multiple symbologies. -// Tags: barcode, symbology, detection, grayscale, color, aspose.barcode, c# +// Tags: barcode symbology, detection, grayscale, color, aspose.barcode, generation, recognition, confidence using System; +using System.Collections.Generic; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; @@ -11,120 +13,96 @@ using Aspose.Drawing; /// -/// Demonstrates how to generate barcodes in both color and grayscale, -/// then reads them back to compare detection confidence and reading quality -/// across several symbologies. +/// Example program that generates color and grayscale barcodes for several symbologies, +/// reads them back, and records detection confidence to compare accuracy between image types. /// class Program { /// - /// Entry point. Generates sample barcodes, reads them, and outputs a comparison - /// of detection results for color versus grayscale images. + /// Entry point of the example. Generates barcodes, performs recognition, and prints a summary. /// static void Main() { - // Define the set of symbologies and corresponding sample texts - var symbologies = new (BaseEncodeType Encode, string CodeText)[] + // Define the set of symbologies and corresponding sample texts to test. + var symbologies = new List<(BaseEncodeType Encode, string CodeText)> { - (EncodeTypes.Code128, "1234567890"), - (EncodeTypes.QR, "Hello QR"), - (EncodeTypes.DataMatrix, "DM12345"), - (EncodeTypes.Pdf417, "PDF417 Sample") + (EncodeTypes.Code128, "Test123"), + (EncodeTypes.QR, "TestQR"), + (EncodeTypes.DataMatrix, "TestDM") }; - // Prepare a directory to store generated barcode images - string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "BarcodeSamples"); - if (!Directory.Exists(outputDir)) - { - Directory.CreateDirectory(outputDir); - } + // Collect result strings for later output. + var results = new List(); - // Process each symbology + // Iterate over each symbology, generating and testing both color and grayscale images. foreach (var (encode, codeText) in symbologies) { - // ------------------------------------------------- - // Generate a color barcode (blue bars on yellow background) - // ------------------------------------------------- - string colorPath = Path.Combine(outputDir, $"{encode.TypeName}_color.png"); - using (var generator = new BarcodeGenerator(encode, codeText)) + // ----- Generate a full‑color barcode (red bars on light yellow background) ----- + using (var colorGenerator = new BarcodeGenerator(encode, codeText)) { - generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Blue; - generator.Parameters.BackColor = Aspose.Drawing.Color.Yellow; - generator.Save(colorPath); - } + colorGenerator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Red; + colorGenerator.Parameters.BackColor = Aspose.Drawing.Color.LightYellow; - // ------------------------------------------------- - // Generate a grayscale barcode (default black on white) - // ------------------------------------------------- - string grayPath = Path.Combine(outputDir, $"{encode.TypeName}_gray.png"); - using (var generator = new BarcodeGenerator(encode, codeText)) - { - // No explicit color settings -> black/white output - generator.Save(grayPath); - } + using (var colorStream = new MemoryStream()) + { + // Save the color barcode to a memory stream as PNG. + colorGenerator.Save(colorStream, BarCodeImageFormat.Png); + colorStream.Position = 0; // Reset stream position for reading. - // ------------------------------------------------- - // Read and evaluate the color image - // ------------------------------------------------- - var colorResult = ReadBarcode(colorPath); + // ----- Recognize the color barcode ----- + bool colorDetected = false; + BarCodeConfidence colorConfidence = BarCodeConfidence.None; - // ------------------------------------------------- - // Read and evaluate the grayscale image - // ------------------------------------------------- - var grayResult = ReadBarcode(grayPath); + using (var colorReader = new BarCodeReader(colorStream, DecodeType.AllSupportedTypes)) + { + foreach (var result in colorReader.ReadBarCodes()) + { + colorDetected = true; + colorConfidence = result.Confidence; + break; // Only need the first detected barcode. + } + } - // ------------------------------------------------- - // Output a side‑by‑side comparison of detection results - // ------------------------------------------------- - Console.WriteLine($"Symbology: {encode.TypeName}"); - Console.WriteLine($" Color Image -> Detected: {colorResult.Detected}, Confidence: {colorResult.Confidence}, ReadingQuality: {colorResult.ReadingQuality}"); - Console.WriteLine($" Grayscale Image-> Detected: {grayResult.Detected}, Confidence: {grayResult.Confidence}, ReadingQuality: {grayResult.ReadingQuality}"); - Console.WriteLine(); - } - } + // ----- Generate a grayscale barcode (black bars on white background) ----- + using (var grayGenerator = new BarcodeGenerator(encode, codeText)) + { + grayGenerator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + grayGenerator.Parameters.BackColor = Aspose.Drawing.Color.White; - // Helper struct to hold detection information for a single barcode read operation - private struct DetectionInfo - { - public bool Detected; - public BarCodeConfidence Confidence; - public double ReadingQuality; - } + using (var grayStream = new MemoryStream()) + { + // Save the grayscale barcode to a memory stream as PNG. + grayGenerator.Save(grayStream, BarCodeImageFormat.Png); + grayStream.Position = 0; // Reset stream position for reading. - /// - /// Reads the first barcode from the specified image file and returns detection details. - /// - /// Path to the image containing the barcode. - /// A struct with detection status, confidence, and reading quality. - private static DetectionInfo ReadBarcode(string imagePath) - { - var info = new DetectionInfo - { - Detected = false, - Confidence = BarCodeConfidence.None, - ReadingQuality = 0.0 - }; + // ----- Recognize the grayscale barcode ----- + bool grayDetected = false; + BarCodeConfidence grayConfidence = BarCodeConfidence.None; - // Verify that the image file exists before attempting to read - if (!File.Exists(imagePath)) - { - Console.WriteLine($"Warning: File not found - {imagePath}"); - return info; - } + using (var grayReader = new BarCodeReader(grayStream, DecodeType.AllSupportedTypes)) + { + foreach (var result in grayReader.ReadBarCodes()) + { + grayDetected = true; + grayConfidence = result.Confidence; + break; // Only need the first detected barcode. + } + } - // Use Aspose.BarCode reader to decode any supported barcode type - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) - { - foreach (var result in reader.ReadBarCodes()) - { - // Capture details from the first detected barcode and exit loop - info.Detected = true; - info.Confidence = result.Confidence; - info.ReadingQuality = result.ReadingQuality; - break; + // Record the comparison results for the current symbology. + results.Add($"Symbology: {encode.TypeName}"); + results.Add($" Color Detected: {colorDetected}, Confidence: {colorConfidence}"); + results.Add($" Grayscale Detected: {grayDetected}, Confidence: {grayConfidence}"); + } + } + } } } - return info; + // Output the accumulated summary to the console. + foreach (var line in results) + { + Console.WriteLine(line); + } } } \ No newline at end of file diff --git a/barcode-recognition-performance/compare-cpu-usage-between-highperformance-and-maxquality-presets-using-stopwatch-timing-measurements.cs b/barcode-recognition-performance/compare-cpu-usage-between-highperformance-and-maxquality-presets-using-stopwatch-timing-measurements.cs index 5e6a7e4..e157c53 100644 --- a/barcode-recognition-performance/compare-cpu-usage-between-highperformance-and-maxquality-presets-using-stopwatch-timing-measurements.cs +++ b/barcode-recognition-performance/compare-cpu-usage-between-highperformance-and-maxquality-presets-using-stopwatch-timing-measurements.cs @@ -1,7 +1,8 @@ -// Title: Compare CPU usage of barcode recognition presets -// Description: Demonstrates measuring the time taken to recognize a barcode using HighPerformance and MaxQuality quality settings. +// Title: Compare CPU usage between HighPerformance and MaxQuality barcode recognition presets +// Description: This example measures and compares the time taken to recognize a Code128 barcode using Aspose.BarCode's HighPerformance and MaxQuality quality settings. +// Category-Description: Demonstrates performance testing of Aspose.BarCode recognition by toggling QualitySettings presets. It showcases the use of BarcodeGenerator, BarCodeReader, and QualitySettings classes to generate a sample barcode, read it, and time the operation with Stopwatch. Developers often need to balance speed versus accuracy when processing large volumes of barcodes, making this pattern useful for benchmarking and optimization. // Prompt: Compare CPU usage between HighPerformance and MaxQuality presets using Stopwatch timing measurements. -// Tags: barcode, recognition, performance, stopwatch, aspose.barcode, csharp +// Tags: code128, barcode recognition, performance, qualitysettings, stopwatch, aspose.barcode using System; using System.Diagnostics; @@ -11,20 +12,22 @@ using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates measuring CPU usage of barcode recognition with different quality presets. +/// Demonstrates how to compare CPU usage (recognition time) between +/// HighPerformance and MaxQuality QualitySettings presets using Aspose.BarCode. /// class Program { /// - /// Entry point. Generates a barcode, then measures recognition time using HighPerformance and MaxQuality presets. + /// Entry point of the example. Generates a barcode, measures recognition times, + /// and outputs the comparison. /// static void Main() { - // Define the file path for the generated barcode image + // Define the path for the temporary barcode image string imagePath = "sample.png"; - // Generate a simple Code128 barcode and save it to the specified path - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Generate a Code128 barcode and save it to the specified path + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123")) { generator.Save(imagePath); } @@ -36,56 +39,40 @@ static void Main() return; } - // ------------------------------ - // Measure recognition time using the HighPerformance preset - // ------------------------------ - long highPerfMs; - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + // Local function that measures the time required to read the barcode + // using a specific QualitySettings preset. + long MeasureRecognitionTime(QualitySettings preset) { - // Apply the HighPerformance quality setting for faster processing - reader.QualitySettings = QualitySettings.HighPerformance; - - // Start timing - var stopwatch = Stopwatch.StartNew(); - - // Read all barcodes in the image - foreach (var result in reader.ReadBarCodes()) + // Initialize the reader for the generated image and specify the expected symbology + using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) { - // Access the decoded text to ensure the result is processed - var _ = result.CodeText; - } - - // Stop timing and record elapsed milliseconds - stopwatch.Stop(); - highPerfMs = stopwatch.ElapsedMilliseconds; - } + // Apply the desired quality preset (HighPerformance or MaxQuality) + reader.QualitySettings = preset; - // ------------------------------ - // Measure recognition time using the MaxQuality preset - // ------------------------------ - long maxQualityMs; - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) - { - // Apply the MaxQuality setting for highest accuracy (potentially slower) - reader.QualitySettings = QualitySettings.MaxQuality; + // Start timing the recognition process + Stopwatch sw = Stopwatch.StartNew(); - // Start timing - var stopwatch = Stopwatch.StartNew(); + // Perform the read operation; results are enumerated to ensure full processing + var results = reader.ReadBarCodes(); + foreach (var result in results) + { + // No additional processing needed; iteration forces full decode + } - // Read all barcodes in the image - foreach (var result in reader.ReadBarCodes()) - { - // Access the decoded text to ensure the result is processed - var _ = result.CodeText; + // Stop the timer and return elapsed milliseconds + sw.Stop(); + return sw.ElapsedMilliseconds; } - - // Stop timing and record elapsed milliseconds - stopwatch.Stop(); - maxQualityMs = stopwatch.ElapsedMilliseconds; } - // Output the timing results for both presets - Console.WriteLine($"HighPerformance preset elapsed time: {highPerfMs} ms"); - Console.WriteLine($"MaxQuality preset elapsed time: {maxQualityMs} ms"); + // Measure recognition time with the HighPerformance preset + long highPerfTime = MeasureRecognitionTime(QualitySettings.HighPerformance); + + // Measure recognition time with the MaxQuality preset + long maxQualityTime = MeasureRecognitionTime(QualitySettings.MaxQuality); + + // Output the timing comparison to the console + Console.WriteLine($"HighPerformance recognition time: {highPerfTime} ms"); + Console.WriteLine($"MaxQuality recognition time: {maxQualityTime} ms"); } } \ No newline at end of file diff --git a/barcode-recognition-performance/compare-detection-accuracy-of-datamatrix-codes-when-xdimension-is-set-to-1-versus-3-pixels.cs b/barcode-recognition-performance/compare-detection-accuracy-of-datamatrix-codes-when-xdimension-is-set-to-1-versus-3-pixels.cs index 7068f2a..a0ac89d 100644 --- a/barcode-recognition-performance/compare-detection-accuracy-of-datamatrix-codes-when-xdimension-is-set-to-1-versus-3-pixels.cs +++ b/barcode-recognition-performance/compare-detection-accuracy-of-datamatrix-codes-when-xdimension-is-set-to-1-versus-3-pixels.cs @@ -1,7 +1,8 @@ -// Title: DataMatrix XDimension Comparison -// Description: Demonstrates generating DataMatrix barcodes with XDimension set to 1 and 3 pixels and compares detection accuracy. +// Title: DataMatrix XDimension detection accuracy comparison +// Description: Demonstrates how changing the XDimension of a DataMatrix barcode (1 vs 3 pixels) affects detection reliability. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, showcasing the use of BarcodeGenerator for creating DataMatrix symbols and BarCodeReader for decoding them. Developers often need to fine‑tune XDimension to balance image size and scanner accuracy, especially in high‑density applications. // Prompt: Compare detection accuracy of DataMatrix codes when XDimension is set to 1 versus 3 pixels. -// Tags: datamatrix, xdimension, detection, accuracy, barcode, generation, recognition, aspnet, csharp +// Tags: datamatrix, xdimension, detection, accuracy, generation, recognition, aspnet, aspose.barcode using System; using System.IO; @@ -11,75 +12,74 @@ using Aspose.Drawing; /// -/// Demonstrates generating DataMatrix barcodes with different XDimension values and compares their detection accuracy. +/// Example program that generates two DataMatrix barcodes with different XDimension values +/// and evaluates their detection accuracy using Aspose.BarCode's recognition engine. /// class Program { /// - /// Entry point. Generates two DataMatrix images with XDimension 1px and 3px, then reads them back to report detection results. + /// Entry point of the example. Generates barcodes, then reads and reports detection results. /// static void Main() { - // Sample data to encode - const string data = "Aspose.DataMatrix.Test"; + const string data = "SampleData"; + const string fileX1 = "datamatrix_x1.png"; + const string fileX3 = "datamatrix_x3.png"; - // Paths for generated images - const string pathX1 = "datamatrix_x1.png"; - const string pathX3 = "datamatrix_x3.png"; - - // Create DataMatrix with XDimension = 1 pixel + // Generate DataMatrix barcode with XDimension = 1 pixel using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, data)) { - // Disable auto-sizing to keep XDimension exact generator.Parameters.AutoSizeMode = AutoSizeMode.None; - generator.Parameters.Barcode.XDimension.Point = 1f; - generator.Save(pathX1, BarCodeImageFormat.Png); + generator.Parameters.Barcode.XDimension.Point = 1f; // set module size to 1 pixel + generator.Save(fileX1, BarCodeImageFormat.Png); } - // Create DataMatrix with XDimension = 3 pixels + // Generate DataMatrix barcode with XDimension = 3 pixels using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, data)) { - // Disable auto-sizing to keep XDimension exact generator.Parameters.AutoSizeMode = AutoSizeMode.None; - generator.Parameters.Barcode.XDimension.Point = 3f; - generator.Save(pathX3, BarCodeImageFormat.Png); + generator.Parameters.Barcode.XDimension.Point = 3f; // set module size to 3 pixels + generator.Save(fileX3, BarCodeImageFormat.Png); } - // Local function to read a barcode image and report detection details - void ReadAndReport(string imagePath, string label) + // Read and evaluate the barcode generated with XDimension = 1 pixel + ReadAndReport(fileX1, XDimensionMode.Small); + + // Read and evaluate the barcode generated with XDimension = 3 pixels + ReadAndReport(fileX3, XDimensionMode.Large); + } + + /// + /// Reads a barcode image, applies appropriate XDimension settings, and prints detection details. + /// + /// Path to the barcode image file. + /// Expected XDimension mode (Small for 1 px, Large for 3 px). + static void ReadAndReport(string imagePath, XDimensionMode xDimMode) + { + // Verify that the image file exists before attempting to read it + if (!File.Exists(imagePath)) { - // Verify that the image file exists before attempting to read - if (!File.Exists(imagePath)) - { - Console.WriteLine($"{label}: Image file not found."); - return; - } + Console.WriteLine($"File not found: {imagePath}"); + return; + } - // Initialize the reader for DataMatrix barcodes - using (var reader = new BarCodeReader(imagePath, DecodeType.DataMatrix)) - { - // Use high quality settings for reliable detection - reader.QualitySettings = QualitySettings.HighQuality; + // Initialize the barcode reader for DataMatrix symbology + using (var reader = new BarCodeReader(imagePath, DecodeType.DataMatrix)) + { + // Use high‑quality settings to improve detection reliability + reader.QualitySettings = QualitySettings.HighQuality; - // Attempt to read barcodes from the image - var results = reader.ReadBarCodes(); - if (results.Length == 0) - { - Console.WriteLine($"{label}: No barcode detected."); - return; - } + // Adjust the reader's XDimension mode to match the generated barcode's module size + reader.QualitySettings.XDimension = xDimMode; - // Evaluate the first detected barcode - var result = results[0]; - bool isCorrect = string.Equals(result.CodeText, data, StringComparison.Ordinal); - Console.WriteLine($"{label}: Detected CodeText = \"{result.CodeText}\" (Correct: {isCorrect})"); - Console.WriteLine($"{label}: Confidence = {result.Confidence}"); - Console.WriteLine($"{label}: ReadingQuality = {result.ReadingQuality}"); + // Iterate through all detected barcodes (should be one in this example) + foreach (var result in reader.ReadBarCodes()) + { + Console.WriteLine($"{imagePath} | XDimensionMode={xDimMode}"); + Console.WriteLine($" CodeText : {result.CodeText}"); + Console.WriteLine($" Confidence : {result.Confidence}"); + Console.WriteLine($" ReadingQuality : {result.ReadingQuality}"); } } - - // Read and compare both generated images - ReadAndReport(pathX1, "XDimension=1px"); - ReadAndReport(pathX3, "XDimension=3px"); } } \ No newline at end of file diff --git a/barcode-recognition-performance/compare-detection-rates-of-small-barcodes-using-xdimension-mode-versus-default-detection.cs b/barcode-recognition-performance/compare-detection-rates-of-small-barcodes-using-xdimension-mode-versus-default-detection.cs index fae4c92..545bec7 100644 --- a/barcode-recognition-performance/compare-detection-rates-of-small-barcodes-using-xdimension-mode-versus-default-detection.cs +++ b/barcode-recognition-performance/compare-detection-rates-of-small-barcodes-using-xdimension-mode-versus-default-detection.cs @@ -1,84 +1,87 @@ -// Title: Compare detection rates of small barcodes using XDimension mode vs default -// Description: Generates small Code128 barcodes and compares detection success using default settings and XDimensionMode.Small. +// Title: Compare detection rates of small Code128 barcodes using XDimension mode +// Description: Generates small Code128 barcodes with reduced XDimension and compares detection success using default settings versus XDimensionMode.Small. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It demonstrates how to create barcodes with the BarcodeGenerator class, adjust visual parameters such as XDimension, and read them back using BarCodeReader with custom QualitySettings. Developers often need to fine‑tune detection for low‑resolution or compact barcodes, making XDimensionMode a key setting for reliable scanning. // Prompt: Compare detection rates of small barcodes using XDimension mode versus default detection. -// Tags: code128, detection, xdimension, barcode, aspose, console +// Tags: code128, detection, png, xdimensionmode, barcodereader, barcodegenerator using System; +using System.Collections.Generic; using System.IO; -using System.Linq; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Demonstrates how XDimensionMode.Small affects barcode detection compared to default settings. +/// Demonstrates how to generate small Code128 barcodes and compare detection +/// success using default settings versus XDimensionMode.Small. /// class Program { /// - /// Entry point. Generates small barcodes, reads them with default and small XDimension settings, - /// and prints a comparison of detection counts. + /// Entry point of the example. Generates a set of small barcodes, + /// reads them back with two different detection configurations, + /// and outputs the detection counts. /// static void Main() { - // Define folder for generated barcode images - string outputFolder = "Barcodes"; + // Prepare a collection to hold barcode images in memory. + List barcodeImages = new List(); + const int sampleCount = 5; - // Ensure the output directory exists - if (!Directory.Exists(outputFolder)) + // Generate small barcodes with reduced XDimension. + for (int i = 0; i < sampleCount; i++) { - Directory.CreateDirectory(outputFolder); - } - - // Generate a small set of Code128 barcodes with a reduced XDimension - int barcodeCount = 5; - for (int i = 0; i < barcodeCount; i++) - { - string codeText = $"Test{i}"; - string filePath = Path.Combine(outputFolder, $"barcode{i}.png"); - - // Create barcode generator with Code128 symbology + // Each barcode encodes a simple numeric string. + string codeText = $"12345{i}"; using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - // Set a small XDimension (1 point) to make barcode elements tiny - generator.Parameters.Barcode.XDimension.Point = 1f; - // Save the generated barcode image - generator.Save(filePath); + // Reduce XDimension to make the barcode visually small. + generator.Parameters.Barcode.XDimension.Point = 0.5f; + + // Save the barcode to a memory stream in PNG format. + using (var ms = new MemoryStream()) + { + generator.Save(ms, BarCodeImageFormat.Png); + barcodeImages.Add(ms.ToArray()); + } } } - int defaultDetected = 0; // Counter for detections using default settings - int smallModeDetected = 0; // Counter for detections using XDimensionMode.Small + int defaultDetected = 0; // Counter for detections using default settings. + int smallModeDetected = 0; // Counter for detections using XDimensionMode.Small. - // Iterate over each generated barcode image and test detection - foreach (string file in Directory.GetFiles(outputFolder, "*.png")) + // Iterate over each generated barcode image. + foreach (var imgData in barcodeImages) { - // ----- Default detection (auto XDimension) ----- - using (var readerDefault = new BarCodeReader(file, DecodeType.AllSupportedTypes)) + // ----- Default detection (no XDimension mode change) ----- + using (var stream = new MemoryStream(imgData)) { - var result = readerDefault.ReadBarCodes().FirstOrDefault(); - if (result != null && !string.IsNullOrEmpty(result.CodeText)) + using (var reader = new BarCodeReader(stream, DecodeType.Code128)) { - defaultDetected++; + // Use default QualitySettings. + var results = reader.ReadBarCodes(); + if (reader.FoundCount > 0) + defaultDetected++; } } // ----- Detection with XDimensionMode.Small ----- - using (var readerSmall = new BarCodeReader(file, DecodeType.AllSupportedTypes)) + using (var stream = new MemoryStream(imgData)) { - // Force the reader to use the Small XDimension mode - readerSmall.QualitySettings.XDimension = XDimensionMode.Small; - var result = readerSmall.ReadBarCodes().FirstOrDefault(); - if (result != null && !string.IsNullOrEmpty(result.CodeText)) + using (var reader = new BarCodeReader(stream, DecodeType.Code128)) { - smallModeDetected++; + // Configure QualitySettings to target small XDimension barcodes. + reader.QualitySettings.XDimension = XDimensionMode.Small; + var results = reader.ReadBarCodes(); + if (reader.FoundCount > 0) + smallModeDetected++; } } } - // Output the comparison results to the console - Console.WriteLine($"Total barcodes generated: {barcodeCount}"); + // Output the comparison results. + Console.WriteLine($"Total barcodes generated: {sampleCount}"); Console.WriteLine($"Detected with default settings: {defaultDetected}"); Console.WriteLine($"Detected with XDimensionMode.Small: {smallModeDetected}"); } diff --git a/barcode-recognition-performance/compare-number-of-detected-barcodes-when-useminimalxdimension-is-toggled-on-versus-off-for-noisy-images.cs b/barcode-recognition-performance/compare-number-of-detected-barcodes-when-useminimalxdimension-is-toggled-on-versus-off-for-noisy-images.cs index 8168801..e8915a1 100644 --- a/barcode-recognition-performance/compare-number-of-detected-barcodes-when-useminimalxdimension-is-toggled-on-versus-off-for-noisy-images.cs +++ b/barcode-recognition-performance/compare-number-of-detected-barcodes-when-useminimalxdimension-is-toggled-on-versus-off-for-noisy-images.cs @@ -1,76 +1,112 @@ -// Title: Barcode detection with and without UseMinimalXDimension on noisy images -// Description: Generates a Code128 barcode, adds random noise, then compares detection counts using default XDimension and the UseMinimalXDimension mode. +// Title: Compare barcode detection with UseMinimalXDimension on noisy images +// Description: Demonstrates generating a Code128 barcode, adding noise, and comparing detection counts with and without the UseMinimalXDimension setting. +// Category-Description: This example belongs to the Aspose.BarCode recognition category, illustrating how to configure QualitySettings for barcode detection in noisy images. It uses BarcodeGenerator, BarCodeReader, and XDimensionMode to show typical use cases where developers need to improve detection reliability under poor image conditions. The snippet serves as a reference for adjusting X‑dimension parameters to optimize recognition performance. // Prompt: Compare the number of detected barcodes when UseMinimalXDimension is toggled on versus off for noisy images. -// Tags: barcode, detection, noise, useminimalxdimension, csharp, aspose.barcode +// Tags: barcode symbology, detection, noise, useminimalxdimension, qualitysettings, aspose.barcode, csharp using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Demonstrates how the UseMinimalXDimension setting influences barcode detection -/// in noisy images using Aspose.BarCode. +/// Example program that generates a Code128 barcode, adds random noise, and compares +/// the number of detected barcodes with and without the UseMinimalXDimension setting. /// class Program { /// - /// Entry point. Generates a barcode, adds noise, and compares detection results - /// with default XDimension settings versus UseMinimalXDimension mode. + /// Entry point of the example. Executes the barcode generation, noise addition, + /// and detection comparison logic. /// static void Main() { - // Generate a simple barcode image in memory - using (var barcodeStream = new MemoryStream()) + // Define file paths for the original and noisy barcode images. + string barcodePath = "barcode.png"; + string noisyPath = "barcode_noisy.png"; + + // -------------------------------------------------------------------- + // Generate a simple Code128 barcode and save it as a PNG file. + // -------------------------------------------------------------------- + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + { + generator.Save(barcodePath, BarCodeImageFormat.Png); + } + + // Verify that the barcode image was created successfully. + if (!File.Exists(barcodePath)) + { + Console.WriteLine("Failed to create barcode image."); + return; + } + + // -------------------------------------------------------------------- + // Load the generated barcode, add random noise, and save the noisy image. + // -------------------------------------------------------------------- + using (var original = new Bitmap(barcodePath)) + using (var noisy = new Bitmap(original.Width, original.Height, original.PixelFormat)) { - // Create a Code128 barcode with sample data and save it as PNG into the stream - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Copy the original barcode onto the new bitmap. + using (var g = Graphics.FromImage(noisy)) { - generator.Save(barcodeStream, BarCodeImageFormat.Png); + g.DrawImage(original, 0, 0, original.Width, original.Height); } - // Reset stream position before loading the image into a bitmap - barcodeStream.Position = 0; - - // Load the barcode image from the stream into a bitmap for pixel manipulation - using (var bitmap = new Bitmap(barcodeStream)) + // Add simple random noise: draw colored dots on ~1% of the pixels. + var rand = new Random(); + int noiseCount = (original.Width * original.Height) / 100; + for (int i = 0; i < noiseCount; i++) { - // Add random noise pixels to simulate a noisy image - var random = new Random(); - int noisePixels = 1000; // number of noisy pixels to inject - for (int i = 0; i < noisePixels; i++) - { - int x = random.Next(bitmap.Width); - int y = random.Next(bitmap.Height); - var noisyColor = Color.FromArgb(random.Next(256), random.Next(256), random.Next(256)); - bitmap.SetPixel(x, y, noisyColor); - } + int x = rand.Next(original.Width); + int y = rand.Next(original.Height); + noisy.SetPixel( + x, + y, + Aspose.Drawing.Color.FromArgb(rand.Next(256), rand.Next(256), rand.Next(256)) + ); + } - // Detect barcodes using default XDimension settings - int defaultCount; - using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes)) - { - var results = reader.ReadBarCodes(); - defaultCount = results.Length; - } + // Save the noisy image to disk. + noisy.Save(noisyPath, Aspose.Drawing.Imaging.ImageFormat.Png); + } - // Detect barcodes with UseMinimalXDimension mode enabled - int minimalCount; - using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes)) - { - // Switch to minimal XDimension mode to improve detection in noisy conditions - reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - var results = reader.ReadBarCodes(); - minimalCount = results.Length; - } + // Verify that the noisy image was created successfully. + if (!File.Exists(noisyPath)) + { + Console.WriteLine("Failed to create noisy image."); + return; + } + + // -------------------------------------------------------------------- + // Helper function to count detected barcodes using a configurable reader. + // -------------------------------------------------------------------- + int CountBarcodes(Action configureReader) + { + using (var reader = new BarCodeReader(noisyPath, DecodeType.AllSupportedTypes)) + { + // Apply any custom configuration to the reader (e.g., XDimension settings). + configureReader?.Invoke(reader); - // Output the comparison results to the console - Console.WriteLine($"Detected barcodes (default XDimension): {defaultCount}"); - Console.WriteLine($"Detected barcodes (UseMinimalXDimension): {minimalCount}"); + // Perform barcode detection and return the count. + var results = reader.ReadBarCodes(); + return results?.Length ?? 0; } } + + // Count barcodes with default XDimension settings (no UseMinimalXDimension). + int countDefault = CountBarcodes(reader => { /* No custom configuration */ }); + + // Count barcodes with UseMinimalXDimension enabled and a minimal size of 2 pixels. + int countMinimal = CountBarcodes(reader => + { + reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; + reader.QualitySettings.MinimalXDimension = 2f; // Example minimal size in pixels. + }); + + // Output the comparison results to the console. + Console.WriteLine($"Detected barcodes (default XDimension): {countDefault}"); + Console.WriteLine($"Detected barcodes (UseMinimalXDimension): {countMinimal}"); } } \ No newline at end of file diff --git a/barcode-recognition-performance/compare-recognition-speed-of-1d-barcodes-versus-2d-barcodes-under-identical-qualitysettings.cs b/barcode-recognition-performance/compare-recognition-speed-of-1d-barcodes-versus-2d-barcodes-under-identical-qualitysettings.cs index 74ddc9a..6975142 100644 --- a/barcode-recognition-performance/compare-recognition-speed-of-1d-barcodes-versus-2d-barcodes-under-identical-qualitysettings.cs +++ b/barcode-recognition-performance/compare-recognition-speed-of-1d-barcodes-versus-2d-barcodes-under-identical-qualitysettings.cs @@ -1,7 +1,8 @@ // Title: Compare recognition speed of 1D vs 2D barcodes -// Description: Demonstrates generating a Code128 and QR barcode, then measures and compares their recognition times using identical QualitySettings. +// Description: Demonstrates measuring the time required to recognize a 1D Code128 barcode and a 2D QR code using identical QualitySettings. +// Category-Description: This example belongs to the Aspose.BarCode recognition category, showcasing how to use BarCodeReader with QualitySettings to evaluate performance. It highlights key API classes such as BarcodeGenerator, BarCodeReader, QualitySettings, and DecodeType, which developers commonly use for generating barcodes, configuring recognition parameters, and benchmarking speed in real‑world applications. // Prompt: Compare recognition speed of 1D barcodes versus 2D barcodes under identical QualitySettings. -// Tags: barcode symbology, recognition speed, qualitysettings, code128, qr, aspnet.barcode, csharp +// Tags: barcode, code128, qr, recognition, speed, qualitysettings, aspose.barcode, generation, decoding using System; using System.Diagnostics; @@ -11,111 +12,64 @@ using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates barcode generation and recognition speed comparison between 1D (Code128) and 2D (QR) symbologies. +/// Example program that generates a 1D Code128 barcode and a 2D QR code, +/// then measures and compares their recognition times using identical +/// . /// class Program { /// - /// Entry point. Generates temporary barcode images, measures recognition times, outputs results, and cleans up files. + /// Entry point of the application. Generates barcodes if needed, + /// configures identical quality settings, and reports recognition + /// durations for both 1D and 2D symbologies. /// static void Main() { - // Define file paths for temporary barcode images + // Paths for generated barcode images string code128Path = "code128.png"; string qrPath = "qr.png"; - // ------------------------------------------------- - // Generate a 1D Code128 barcode and save as PNG - // ------------------------------------------------- - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Generate a 1D barcode (Code128) if it does not already exist + if (!File.Exists(code128Path)) { - generator.Save(code128Path, BarCodeImageFormat.Png); + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + { + generator.Save(code128Path, BarCodeImageFormat.Png); + } } - // ------------------------------------------------- - // Generate a 2D QR barcode and save as PNG - // ------------------------------------------------- - using (var generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com")) + // Generate a 2D barcode (QR) if it does not already exist + if (!File.Exists(qrPath)) { - generator.Save(qrPath, BarCodeImageFormat.Png); + using (var generator = new BarcodeGenerator(EncodeTypes.QR, "1234567890")) + { + generator.Save(qrPath, BarCodeImageFormat.Png); + } } - // Prepare identical quality settings for both recognitions - var quality = QualitySettings.NormalQuality; + // Define identical quality settings for both recognitions + QualitySettings commonSettings = QualitySettings.NormalQuality; - // ------------------------------------------------- // Measure recognition time for the 1D barcode - // ------------------------------------------------- - long time1D; - using (var reader = new BarCodeReader(code128Path, DecodeType.Code128)) + using (var reader1D = new BarCodeReader(code128Path, DecodeType.Code128)) { - // Apply the same quality settings - reader.QualitySettings = quality; - - // Start timing - var sw = Stopwatch.StartNew(); + reader1D.QualitySettings = commonSettings; // Apply common quality settings + Stopwatch sw1D = Stopwatch.StartNew(); // Start timing + var results1D = reader1D.ReadBarCodes(); // Perform recognition + sw1D.Stop(); // Stop timing - // Perform recognition - var results = reader.ReadBarCodes(); - - // Stop timing - sw.Stop(); - time1D = sw.ElapsedMilliseconds; - - // Output detection results - Console.WriteLine($"1D Code128 detected: {results.Length} barcode(s)."); - foreach (var result in results) - { - Console.WriteLine($" Text: {result.CodeText}"); - } + Console.WriteLine($"1D (Code128) recognition time: {sw1D.ElapsedMilliseconds} ms, detected {results1D.Length} barcode(s)."); } - // ------------------------------------------------- // Measure recognition time for the 2D barcode - // ------------------------------------------------- - long time2D; - using (var reader = new BarCodeReader(qrPath, DecodeType.QR)) + using (var reader2D = new BarCodeReader(qrPath, DecodeType.QR)) { - // Apply the same quality settings - reader.QualitySettings = quality; - - // Start timing - var sw = Stopwatch.StartNew(); + reader2D.QualitySettings = commonSettings; // Apply common quality settings + Stopwatch sw2D = Stopwatch.StartNew(); // Start timing + var results2D = reader2D.ReadBarCodes(); // Perform recognition + sw2D.Stop(); // Stop timing - // Perform recognition - var results = reader.ReadBarCodes(); - - // Stop timing - sw.Stop(); - time2D = sw.ElapsedMilliseconds; - - // Output detection results - Console.WriteLine($"2D QR detected: {results.Length} barcode(s)."); - foreach (var result in results) - { - Console.WriteLine($" Text: {result.CodeText}"); - } - } - - // ------------------------------------------------- - // Output comparison of recognition times - // ------------------------------------------------- - Console.WriteLine(); - Console.WriteLine("Recognition time comparison (identical QualitySettings):"); - Console.WriteLine($" 1D (Code128): {time1D} ms"); - Console.WriteLine($" 2D (QR) : {time2D} ms"); - - // ------------------------------------------------- - // Clean up temporary files - // ------------------------------------------------- - try - { - if (File.Exists(code128Path)) File.Delete(code128Path); - if (File.Exists(qrPath)) File.Delete(qrPath); - } - catch - { - // Ignored - cleanup failure should not affect program exit + Console.WriteLine($"2D (QR) recognition time: {sw2D.ElapsedMilliseconds} ms, detected {results2D.Length} barcode(s)."); } } } \ No newline at end of file diff --git a/barcode-recognition-performance/configure-deconvolution-parameters-to-improve-recognition-of-blurred-qr-codes-in-jpeg-files.cs b/barcode-recognition-performance/configure-deconvolution-parameters-to-improve-recognition-of-blurred-qr-codes-in-jpeg-files.cs index 1255af2..aee2863 100644 --- a/barcode-recognition-performance/configure-deconvolution-parameters-to-improve-recognition-of-blurred-qr-codes-in-jpeg-files.cs +++ b/barcode-recognition-performance/configure-deconvolution-parameters-to-improve-recognition-of-blurred-qr-codes-in-jpeg-files.cs @@ -1,57 +1,69 @@ -// Title: QR Code Recognition with Deconvolution in JPEG Images -// Description: Demonstrates configuring deconvolution and quality settings to improve detection of blurred QR codes stored in JPEG files. +// Title: Configure deconvolution for blurred QR code recognition +// Description: Demonstrates generating a high‑error‑correction QR code, saving it as JPEG, and using Aspose.BarCode's deconvolution settings to improve detection of blurred images. +// Category-Description: This example belongs to the Aspose.BarCode image preprocessing and recognition category. It showcases the use of BarcodeGenerator, BarCodeReader, QualitySettings, and DeconvolutionMode to handle low‑quality or blurred barcode images. Developers often need to adjust these settings when scanning QR codes from photographs or scanned documents where blur is present. // Prompt: Configure deconvolution parameters to improve recognition of blurred QR codes in JPEG files. -// Tags: qr, deconvolution, barcode recognition, jpeg, aspose.barcode, qualitysettings +// Tags: qr code, deconvolution, image preprocessing, barcode recognition, aspose.barcode, qualitysettings using System; using System.IO; using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Example program that reads a blurred QR code from a JPEG image -/// using Aspose.BarCode with deconvolution and high‑quality settings. +/// Demonstrates configuring deconvolution parameters to improve recognition of blurred QR codes in JPEG files. /// class Program { /// - /// Entry point of the application. - /// Configures the barcode reader, applies deconvolution, and outputs detection results. + /// Entry point of the example. Generates a QR code, saves it as JPEG, and reads it using high‑quality deconvolution settings. /// static void Main() { - // Path to the JPEG image containing a blurred QR code. - string imagePath = "blurred_qr.jpg"; + // Path for the sample QR code image + string qrImagePath = "qr_sample.jpg"; - // Verify that the image file exists before attempting to read it. - if (!File.Exists(imagePath)) + // ------------------------------------------------- + // 1. Generate a QR code with high error correction level + // ------------------------------------------------- + using (var generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com")) { - Console.WriteLine($"File not found: {imagePath}"); + // Use the highest error correction to tolerate blur + generator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelH; + + // Save as JPEG (Aspose.BarCode supports JPEG via BarCodeImageFormat) + generator.Save(qrImagePath, BarCodeImageFormat.Jpeg); + } + + // ------------------------------------------------- + // 2. Verify the image exists before attempting recognition + // ------------------------------------------------- + if (!File.Exists(qrImagePath)) + { + Console.WriteLine($"File not found: {qrImagePath}"); return; } - // Initialize the barcode reader for QR codes using the specified image. - using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.QR)) + // ------------------------------------------------- + // 3. Read the QR code using deconvolution to improve + // recognition of blurred images + // ------------------------------------------------- + using (var reader = new BarCodeReader(qrImagePath, DecodeType.QR)) { - // Apply a high‑quality preset that is suitable for damaged or blurred barcodes. + // Apply a high‑quality preset for better detection reader.QualitySettings = QualitySettings.HighQuality; - // Enable fast deconvolution to help restore blurred image details. + // Enable deconvolution (image restoration) – Fast mode is sufficient reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast; - // Allow recognition of barcodes with minor errors to increase detection chances. + // Allow recognition of barcodes with minor errors (optional) reader.QualitySettings.AllowIncorrectBarcodes = true; - // Iterate through all detected barcodes and output their details. + // Perform recognition and output detected text foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($"Detected QR Code: {result.CodeText}"); - Console.WriteLine($"Confidence: {result.Confidence}"); - Console.WriteLine($"Reading Quality: {result.ReadingQuality}"); - - // Output the detected barcode region (bounding rectangle). - var bounds = result.Region.Rectangle; - Console.WriteLine($"Region - X:{bounds.X}, Y:{bounds.Y}, Width:{bounds.Width}, Height:{bounds.Height}"); + Console.WriteLine($"Detected QR Code Text: {result.CodeText}"); } } } diff --git a/barcode-recognition-performance/configure-qualitysettingsxdimension-to-1-pixel-for-recognizing-ultra-fine-one-pixel-wide-barcodes-accurately.cs b/barcode-recognition-performance/configure-qualitysettingsxdimension-to-1-pixel-for-recognizing-ultra-fine-one-pixel-wide-barcodes-accurately.cs index 021a0f1..1b505fe 100644 --- a/barcode-recognition-performance/configure-qualitysettingsxdimension-to-1-pixel-for-recognizing-ultra-fine-one-pixel-wide-barcodes-accurately.cs +++ b/barcode-recognition-performance/configure-qualitysettingsxdimension-to-1-pixel-for-recognizing-ultra-fine-one-pixel-wide-barcodes-accurately.cs @@ -1,63 +1,67 @@ -// Title: Ultra‑fine One‑Pixel Barcode Recognition -// Description: Demonstrates configuring QualitySettings.XDimension to 1 pixel to accurately read barcodes that are only one pixel wide. +// Title: Ultra‑fine One‑Pixel Barcode Recognition Example +// Description: Demonstrates configuring QualitySettings.XDimension to 1 pixel for accurate detection of ultra‑fine barcodes. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating how to adjust XDimension settings using the BarCodeReader and QualitySettings classes. Developers often need to recognize very narrow barcodes in high‑resolution images; this snippet shows typical usage for Code128 symbology and minimal XDimension configuration. // Prompt: Configure QualitySettings.XDimension to 1 pixel for recognizing ultra‑fine one‑pixel wide barcodes accurately. -// Tags: barcode, recognition, xdimension, code128, aspnet, aspose +// Tags: barcode, recognition, xdimension, code128, aspose.barcode, image-processing using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Example program that generates a Code128 barcode and reads it using -/// a minimal XDimension setting of 1 pixel to handle ultra‑fine barcodes. +/// Demonstrates configuring QualitySettings.XDimension to 1 pixel for recognizing ultra‑fine one‑pixel wide barcodes. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode image, verifies its creation, and reads it - /// with QualitySettings configured for a 1‑pixel XDimension. + /// Entry point of the example. Generates a Code128 barcode with a 1‑pixel XDimension, saves it, and reads it back using minimal XDimension settings. /// static void Main() { - // ------------------------------------------------------------ - // Step 1: Generate a simple barcode image to be recognized - // ------------------------------------------------------------ - string imagePath = "sample.png"; - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + // Define a temporary file path for the sample barcode image. + string imagePath = Path.Combine(Path.GetTempPath(), "sample_barcode.png"); + + // Generate a simple Code128 barcode and save it to the file. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Save the generated barcode as a PNG file - generator.Save(imagePath); + // Set a small XDimension (1 point) for the generated image to simulate an ultra‑fine barcode. + generator.Parameters.Barcode.XDimension.Point = 1f; + generator.Save(imagePath, BarCodeImageFormat.Png); } - // ------------------------------------------------------------ - // Step 2: Verify that the barcode image was successfully created - // ------------------------------------------------------------ + // Verify that the image file was created successfully. if (!File.Exists(imagePath)) { - Console.WriteLine("Barcode image could not be created."); + Console.WriteLine("Failed to create the barcode image."); return; } - // ------------------------------------------------------------ - // Step 3: Read the barcode using ultra‑fine XDimension configuration - // ------------------------------------------------------------ + // Read the barcode using ultra‑fine XDimension settings. using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) { - // Configure the reader to use minimal XDimension mode + // Configure QualitySettings to detect 1‑pixel wide modules. reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - - // Set the minimal XDimension to 1 pixel for ultra‑fine barcode detection reader.QualitySettings.MinimalXDimension = 1f; - // Iterate through all detected barcodes and output their details + // Perform recognition and output results. foreach (var result in reader.ReadBarCodes()) { + Console.WriteLine($"Detected CodeText: {result.CodeText}"); Console.WriteLine($"Detected Type: {result.CodeTypeName}"); - Console.WriteLine($"Code Text: {result.CodeText}"); } } + + // Clean up the temporary image file. + try + { + File.Delete(imagePath); + } + catch + { + // Ignored – cleanup failure should not affect program exit. + } } } \ No newline at end of file diff --git a/barcode-recognition-performance/configure-recognition-to-ignore-quiet-zones-and-observe-effect-on-speed-for-large-code128-barcodes.cs b/barcode-recognition-performance/configure-recognition-to-ignore-quiet-zones-and-observe-effect-on-speed-for-large-code128-barcodes.cs index 1377768..cd6f214 100644 --- a/barcode-recognition-performance/configure-recognition-to-ignore-quiet-zones-and-observe-effect-on-speed-for-large-code128-barcodes.cs +++ b/barcode-recognition-performance/configure-recognition-to-ignore-quiet-zones-and-observe-effect-on-speed-for-large-code128-barcodes.cs @@ -1,7 +1,8 @@ -// Title: Code128 barcode generation and recognition speed comparison -// Description: Demonstrates generating a large Code128 barcode, then measuring recognition time with normal and high‑performance quality settings to observe speed impact. +// Title: Code128 Barcode Recognition Speed with Quiet Zone Variations +// Description: Demonstrates how disabling quiet zones affects recognition speed for large Code128 barcodes. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator for creating Code128 barcodes, BarCodeReader for decoding them, and QualitySettings to control recognition performance. Developers often need to tune quiet zone padding and quality settings to balance accuracy and speed in high‑volume scanning scenarios. // Prompt: Configure recognition to ignore quiet zones and observe effect on speed for large Code128 barcodes. -// Tags: barcode symbology, recognition speed, code128, quiet zones, qualitysettings, aspose.barcode +// Tags: code128, quiet zone, recognition speed, performance, generation, Aspose.BarCode, barcode, qualitysettings using System; using System.Diagnostics; @@ -12,81 +13,91 @@ using Aspose.Drawing; /// -/// Example program that generates a large Code128 barcode, then measures recognition speed using different quality settings. +/// Generates two large Code128 barcodes—one with the default quiet zone and one without—and +/// measures the recognition time using different quality settings to illustrate the impact of quiet zones on performance. /// class Program { /// - /// Entry point. Generates a barcode, verifies the image, and times recognition with normal and high‑performance settings. + /// Entry point of the example. Creates barcode images, runs recognition benchmarks, and prints the results. /// static void Main() { - // Prepare a large Code128 barcode text (200 characters) - string codeText = new string('A', 200); + // Prepare a long Code128 text (200 characters) to simulate a large barcode. + string longText = new string('A', 200); - // Output image file path - string imagePath = "code128.png"; + // Define file names for the generated images. + string imageWithQuietZone = "code128_with_quietzone.png"; + string imageNoQuietZone = "code128_no_quietzone.png"; - // Generate the barcode image and save as PNG - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + // -------------------------------------------------------------------- + // Generate a barcode with the default quiet zone (non‑zero padding). + // -------------------------------------------------------------------- + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, longText)) { - generator.Save(imagePath, BarCodeImageFormat.Png); + // The default padding is retained; no changes required. + generator.Save(imageWithQuietZone, BarCodeImageFormat.Png); } - // Verify that the image file was created successfully - if (!File.Exists(imagePath)) + // -------------------------------------------------------------------- + // Generate a barcode with all padding set to zero (effectively no quiet zone). + // -------------------------------------------------------------------- + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, longText)) { - Console.WriteLine("Failed to create barcode image."); - return; + generator.Parameters.Barcode.Padding.Left.Point = 0f; + generator.Parameters.Barcode.Padding.Top.Point = 0f; + generator.Parameters.Barcode.Padding.Right.Point = 0f; + generator.Parameters.Barcode.Padding.Bottom.Point = 0f; + generator.Save(imageNoQuietZone, BarCodeImageFormat.Png); } - // ----------------------------------------------------------------- - // NOTE: Aspose.BarCode does not expose a property to ignore quiet zones - // during recognition (generator.Parameters.Barcode.QuietZone does not exist). - // Therefore we proceed with standard recognition and focus on measuring - // speed differences using different QualitySettings presets. - // ----------------------------------------------------------------- - - // Measure recognition time with default (NormalQuality) settings - TimeSpan normalTime; - using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + // -------------------------------------------------------------------- + // Local function that measures the time required to read all barcodes + // from an image using the specified quality settings. + // -------------------------------------------------------------------- + double MeasureRecognition(string imagePath, QualitySettings settings) { - var sw = Stopwatch.StartNew(); - - // Read barcodes; break after first result to keep timing focused - foreach (var result in reader.ReadBarCodes()) + if (!File.Exists(imagePath)) { - // Output detection details for verification - Console.WriteLine($"[Normal] Detected: {result.CodeTypeName}, Text: {result.CodeText}"); - break; + Console.WriteLine($"File not found: {imagePath}"); + return -1; } - sw.Stop(); - normalTime = sw.Elapsed; - } + using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + { + // Apply the requested quality configuration. + reader.QualitySettings = settings; - // Measure recognition time with HighPerformance preset (faster, lower quality) - TimeSpan highPerfTime; - using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) - { - // Apply high‑performance preset to the reader - reader.QualitySettings = QualitySettings.HighPerformance; + var stopwatch = Stopwatch.StartNew(); - var sw = Stopwatch.StartNew(); + // Iterate through all detected barcodes to ensure full processing. + foreach (var result in reader.ReadBarCodes()) + { + // Output the decoded text (optional, but forces full decode). + Console.WriteLine($"Detected: {result.CodeText}"); + } - // Read barcodes; break after first result - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"[HighPerf] Detected: {result.CodeTypeName}, Text: {result.CodeText}"); - break; + stopwatch.Stop(); + return stopwatch.Elapsed.TotalMilliseconds; } - - sw.Stop(); - highPerfTime = sw.Elapsed; } - // Output timing comparison between the two quality settings - Console.WriteLine($"Recognition time (NormalQuality): {normalTime.TotalMilliseconds} ms"); - Console.WriteLine($"Recognition time (HighPerformance): {highPerfTime.TotalMilliseconds} ms"); + // -------------------------------------------------------------------- + // Run recognition benchmarks with different quality settings and quiet zone configurations. + // -------------------------------------------------------------------- + double timeWithQuietZone = MeasureRecognition(imageWithQuietZone, QualitySettings.NormalQuality); + double timeWithQuietZoneFast = MeasureRecognition(imageWithQuietZone, QualitySettings.HighPerformance); + double timeNoQuietZone = MeasureRecognition(imageNoQuietZone, QualitySettings.NormalQuality); + double timeNoQuietZoneFast = MeasureRecognition(imageNoQuietZone, QualitySettings.HighPerformance); + + // -------------------------------------------------------------------- + // Display the timing results. + // -------------------------------------------------------------------- + Console.WriteLine(); + Console.WriteLine("Recognition timing (ms):"); + Console.WriteLine($"With quiet zone (NormalQuality): {timeWithQuietZone}"); + Console.WriteLine($"With quiet zone (HighPerformance): {timeWithQuietZoneFast}"); + Console.WriteLine($"Without quiet zone (NormalQuality): {timeNoQuietZone}"); + Console.WriteLine($"Without quiet zone (HighPerformance): {timeNoQuietZoneFast}"); } } \ No newline at end of file diff --git a/barcode-recognition-performance/create-barcodereader-instance-that-reads-jpeg-images-and-applies-highquality-preset-for-balanced-speed.cs b/barcode-recognition-performance/create-barcodereader-instance-that-reads-jpeg-images-and-applies-highquality-preset-for-balanced-speed.cs index df678a7..0d22386 100644 --- a/barcode-recognition-performance/create-barcodereader-instance-that-reads-jpeg-images-and-applies-highquality-preset-for-balanced-speed.cs +++ b/barcode-recognition-performance/create-barcodereader-instance-that-reads-jpeg-images-and-applies-highquality-preset-for-balanced-speed.cs @@ -1,47 +1,57 @@ -// Title: Read JPEG Barcodes with HighQuality Preset -// Description: Demonstrates creating a BarCodeReader for a JPEG image and applying the HighQuality preset to balance speed and accuracy. +// Title: Read JPEG barcode image with HighQuality preset +// Description: Demonstrates creating a BarCodeReader for a JPEG file and applying the HighQuality preset for balanced speed and accuracy. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing how to configure QualitySettings while reading barcodes. It uses BarCodeReader, DecodeType, and QualitySettings classes, typical for developers needing fast yet reliable barcode detection in image files such as JPEGs. // Prompt: Create a BarCodeReader instance that reads JPEG images and applies HighQuality preset for balanced speed. -// Tags: barcode, recognition, jpeg, highquality, aspose, csharp +// Tags: barcode symbology, barcode reading, jpeg, highquality, qualitysettings, aspose.barcode using System; using System.IO; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Sample program that reads barcodes from a JPEG image using Aspose.BarCode. +/// Demonstrates reading a JPEG barcode image using Aspose.BarCode with HighQuality settings. /// class Program { /// - /// Entry point of the application. Loads a JPEG file, configures the reader, - /// and outputs detected barcode information to the console. + /// Entry point. Generates a sample barcode image if missing, then reads it using BarCodeReader with HighQuality preset. /// static void Main() { - // Path to the JPEG image containing barcodes - string imagePath = "sample.jpg"; + // Path to the sample barcode image (JPEG format) + string imagePath = "sample_barcode.jpg"; - // Verify that the image file exists before attempting to read it + // Generate a sample barcode image if it does not already exist if (!File.Exists(imagePath)) { - Console.WriteLine($"File not found: {imagePath}"); + // Create a BarcodeGenerator for Code128 symbology with sample text + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + { + // Save the generated barcode as a JPEG file + generator.Save(imagePath, BarCodeImageFormat.Jpeg); + Console.WriteLine($"Generated sample barcode image: {imagePath}"); + } + } + + // Ensure the JPEG file exists before attempting to read it + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Error: Image file '{imagePath}' not found."); return; } - // Initialize BarCodeReader for the specified image and enable detection of all supported barcode types + // Initialize BarCodeReader for the JPEG image, enabling all supported decode types using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) { - // Apply the HighQuality preset – provides a good trade‑off between speed and robustness + // Apply the HighQuality preset for a balance between speed and accuracy reader.QualitySettings = QualitySettings.HighQuality; - // Iterate through all detected barcodes and display their details - foreach (BarCodeResult result in reader.ReadBarCodes()) + // Iterate through all detected barcodes in the image + foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($"Barcode Type: {result.CodeTypeName}"); - Console.WriteLine($"Code Text : {result.CodeText}"); - Console.WriteLine($"Confidence : {result.Confidence}"); - Console.WriteLine($"ReadingQuality: {result.ReadingQuality}"); - Console.WriteLine(); + Console.WriteLine($"Detected Type: {result.CodeTypeName}"); + Console.WriteLine($"Decoded Text: {result.CodeText}"); } } } diff --git a/barcode-recognition-performance/create-diagnostic-mode-that-logs-each-barcode-element-size-when-useminimalxdimension-is-active.cs b/barcode-recognition-performance/create-diagnostic-mode-that-logs-each-barcode-element-size-when-useminimalxdimension-is-active.cs index 30ece9e..7c2b4d5 100644 --- a/barcode-recognition-performance/create-diagnostic-mode-that-logs-each-barcode-element-size-when-useminimalxdimension-is-active.cs +++ b/barcode-recognition-performance/create-diagnostic-mode-that-logs-each-barcode-element-size-when-useminimalxdimension-is-active.cs @@ -1,79 +1,90 @@ -// Title: Diagnostic barcode size logging with minimal X-dimension mode -// Description: Demonstrates generating a Code128 barcode, then reading it with UseMinimalXDimension enabled, logging each barcode element's size. +// Title: Barcode Generation and Recognition with Minimal X-Dimension Diagnostics +// Description: Demonstrates generating Code128 and QR barcodes, saving them as PNG, then reading them back while logging each barcode element size when UseMinimalXDimension is enabled. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the BarcodeGenerator for creating barcodes and BarCodeReader for decoding them, highlighting the QualitySettings.XDimension property to activate minimal X-dimension mode. Developers often need to fine‑tune barcode dimensions for printing or scanning constraints, and this snippet illustrates how to log element sizes for diagnostic purposes. // Prompt: Create a diagnostic mode that logs each barcode element size when UseMinimalXDimension is active. -// Tags: barcode, code128, minimalxdimension, diagnostics, aspose.barcode, csharp +// Tags: barcode generation, barcode recognition, minimalxdimension, code128, qr, png, aspose.barcode, diagnostics using System; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.BarCode; using Aspose.Drawing; /// -/// Example program that creates a barcode, reads it using minimal X‑dimension detection, -/// and logs the size of each detected barcode element. +/// Generates sample barcodes, saves them as PNG files, and then reads them back while +/// logging each barcode element's size when the minimal X‑dimension mode is active. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode, saves it, then reads it back with diagnostic logging. + /// Entry point of the example. Executes barcode creation, saving, and diagnostic reading. /// static void Main() { - // Path for the generated barcode image - const string barcodePath = "sample_barcode.png"; + // -------------------------------------------------------------------- + // 1. Prepare output directory for generated barcode images + // -------------------------------------------------------------------- + string outputDir = "Barcodes"; + Directory.CreateDirectory(outputDir); - // ----------------------------------------------------------------- - // Generate a simple Code128 barcode and save it to a file - // ----------------------------------------------------------------- - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // -------------------------------------------------------------------- + // 2. Define sample barcodes to generate (type, text, file name) + // -------------------------------------------------------------------- + var samples = new (BaseEncodeType encode, string text, string file)[] { - // Optional visual settings: black bars on white background - generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; - generator.Parameters.BackColor = Aspose.Drawing.Color.White; - - // Save the barcode image to the specified path - generator.Save(barcodePath); - } + (EncodeTypes.Code128, "1234567890", "code128.png"), + (EncodeTypes.QR, "https://example.com", "qr.png") + }; - // Verify that the image was created successfully - if (!File.Exists(barcodePath)) + // -------------------------------------------------------------------- + // 3. Generate each barcode image and save as PNG + // -------------------------------------------------------------------- + foreach (var sample in samples) { - Console.WriteLine($"Failed to create barcode image at '{barcodePath}'."); - return; + string path = Path.Combine(outputDir, sample.file); + using (var generator = new BarcodeGenerator(sample.encode, sample.text)) + { + // Set visual appearance + generator.Parameters.Barcode.XDimension.Point = 2f; + generator.Parameters.Barcode.FilledBars = false; + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; + + // Save the barcode image + generator.Save(path, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode: {path}"); + } } - // ----------------------------------------------------------------- - // Read the barcode using the UseMinimalXDimension mode - // ----------------------------------------------------------------- - using (var reader = new BarCodeReader(barcodePath, DecodeType.AllSupportedTypes)) + // -------------------------------------------------------------------- + // 4. Read generated barcodes and log element sizes when UseMinimalXDimension is active + // -------------------------------------------------------------------- + string[] imageFiles = Directory.GetFiles(outputDir, "*.png"); + foreach (string imagePath in imageFiles) { - // Activate the minimal X-dimension detection mode - reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - - // Define the minimal X-dimension size (in pixels) - reader.QualitySettings.MinimalXDimension = 2f; - - // Perform the recognition and obtain results - var results = reader.ReadBarCodes(); - - // Log whether the minimal X-dimension mode is active - bool isMinimalActive = reader.QualitySettings.XDimension == XDimensionMode.UseMinimalXDimension; - Console.WriteLine($"UseMinimalXDimension active: {isMinimalActive}"); + if (!File.Exists(imagePath)) + { + Console.WriteLine($"File not found: {imagePath}"); + continue; + } - // Iterate over each detected barcode and log its size and content - foreach (var result in results) + using (var reader = new BarCodeReader(imagePath)) { - var rect = result.Region.Rectangle; - double width = rect.Width; - double height = rect.Height; + // Activate minimal X-dimension mode for diagnostic purposes + reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; + reader.QualitySettings.MinimalXDimension = 2f; // example minimal size in pixels - Console.WriteLine($"Detected barcode:"); - Console.WriteLine($" Type : {result.CodeTypeName}"); - Console.WriteLine($" CodeText: {result.CodeText}"); - Console.WriteLine($" Size : Width = {width}, Height = {height}"); + // Iterate through all detected barcodes in the image + foreach (var result in reader.ReadBarCodes()) + { + var region = result.Region.Rectangle; + Console.WriteLine( + $"Image: {Path.GetFileName(imagePath)} | " + + $"Type: {result.CodeTypeName} | " + + $"Text: {result.CodeText} | " + + $"Width: {region.Width} | Height: {region.Height}"); + } } } } diff --git a/barcode-recognition-performance/create-performance-benchmark-that-records-cpu-usage-during-barcode-scanning-of-animated-gif-frames.cs b/barcode-recognition-performance/create-performance-benchmark-that-records-cpu-usage-during-barcode-scanning-of-animated-gif-frames.cs index d8af8d2..5d225a5 100644 --- a/barcode-recognition-performance/create-performance-benchmark-that-records-cpu-usage-during-barcode-scanning-of-animated-gif-frames.cs +++ b/barcode-recognition-performance/create-performance-benchmark-that-records-cpu-usage-during-barcode-scanning-of-animated-gif-frames.cs @@ -1,20 +1,20 @@ -// Title: CPU Usage Benchmark for Barcode Scanning in Animated GIF Frames -// Description: Demonstrates how to measure CPU time while recognizing barcodes in each frame of an animated GIF using Aspose.BarCode. +// Title: Barcode scanning performance benchmark for animated GIF frames +// Description: Demonstrates measuring CPU usage while scanning each frame of an animated GIF for barcodes using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode recognition category, illustrating how to process animated images frame‑by‑frame. It showcases the BarCodeReader class with DecodeType.AllSupportedTypes, typical for developers who need to benchmark or optimize barcode detection in multi‑frame media such as GIFs, videos, or image sequences. The snippet is useful for performance testing, CI pipelines, and real‑time scanning scenarios. // Prompt: Create a performance benchmark that records CPU usage during barcode scanning of animated GIF frames. -// Tags: barcode, scanning, animated gif, cpu benchmark, aspose.barcode, c# +// Tags: barcode, scanning, performance, cpu, animated gif, aspose.barcode, barcodereader, decode type, benchmark using System; +using System.Collections.Generic; using System.Diagnostics; using System.IO; -using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.BarCode.Generation; using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Provides a simple console application that benchmarks CPU usage while scanning barcodes -/// from each frame of an animated GIF. The example shows how to extract frames, feed them -/// to Aspose.BarCode, and report per‑frame processing time and detection results. +/// Provides a console application that benchmarks CPU usage while scanning each frame of an animated GIF for barcodes. /// class Program { @@ -23,65 +23,65 @@ class Program /// static void Main() { - // Path to the animated GIF containing barcodes. + // Path to the animated GIF file. Replace with an existing file or ensure it exists. const string gifPath = "sample.gif"; // Verify that the GIF file exists before proceeding. if (!File.Exists(gifPath)) { - Console.WriteLine($"File not found: {gifPath}"); - Console.WriteLine("Please provide an animated GIF with barcode frames and place it beside the executable."); + Console.WriteLine($"Animated GIF not found at '{Path.GetFullPath(gifPath)}'. Benchmark will not run."); return; } - // Load the animated GIF into an Aspose.Drawing.Image object. + // Load the animated GIF using Aspose.Drawing. using (Image gifImage = Image.FromFile(gifPath)) { - // GIF frames are accessed via the Time dimension. - var timeDimension = FrameDimension.Time; - int frameCount = gifImage.GetFrameCount(timeDimension); + // Determine the number of frames in the GIF (time dimension). + int frameCount = gifImage.GetFrameCount(FrameDimension.Time); Console.WriteLine($"Animated GIF contains {frameCount} frame(s)."); - // Iterate over each frame in the animated GIF. + var cpuUsages = new List(); + + // Iterate through each frame and measure CPU time for barcode scanning. for (int i = 0; i < frameCount; i++) { - // Select the current frame for processing. - gifImage.SelectActiveFrame(timeDimension, i); + // Select the current frame. + gifImage.SelectActiveFrame(FrameDimension.Time, i); - // Save the selected frame to a memory stream in PNG format. - // PNG is used because BarCodeReader expects a raster image format. + // Save the current frame to a memory stream in PNG format. using (var frameStream = new MemoryStream()) { gifImage.Save(frameStream, ImageFormat.Png); - frameStream.Position = 0; // Reset stream position for reading. + frameStream.Position = 0; + + // Capture CPU time before barcode scanning. + Process proc = Process.GetCurrentProcess(); + TimeSpan cpuStart = proc.TotalProcessorTime; - // Initialize the barcode reader for the current frame. + // Scan the frame for all supported barcode types. using (var reader = new BarCodeReader(frameStream, DecodeType.AllSupportedTypes)) { - // Record CPU time before barcode recognition starts. - TimeSpan cpuStart = Process.GetCurrentProcess().TotalProcessorTime; - - // Perform barcode detection on the current frame. - var results = reader.ReadBarCodes(); - - // Record CPU time after barcode recognition completes. - TimeSpan cpuEnd = Process.GetCurrentProcess().TotalProcessorTime; - double cpuMilliseconds = (cpuEnd - cpuStart).TotalMilliseconds; - - // Output per‑frame CPU usage and number of barcodes found. - Console.WriteLine($"Frame {i + 1}/{frameCount}: CPU time = {cpuMilliseconds:F2} ms, barcodes detected = {reader.FoundCount}"); - - // List details of each detected barcode. - foreach (var result in results) + foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}"); + // The read operation is performed for benchmarking; result handling is optional. } } + + // Capture CPU time after scanning and calculate usage for this frame. + TimeSpan cpuEnd = proc.TotalProcessorTime; + cpuUsages.Add(cpuEnd - cpuStart); } } - } - // Indicate that the benchmark has finished. - Console.WriteLine("Benchmark completed."); + // Compute total and average CPU usage across all frames. + TimeSpan totalCpu = new TimeSpan(); + foreach (var usage in cpuUsages) + totalCpu += usage; + + double averageMs = cpuUsages.Count > 0 ? totalCpu.TotalMilliseconds / cpuUsages.Count : 0; + + Console.WriteLine($"Total CPU time for scanning {cpuUsages.Count} frame(s): {totalCpu.TotalMilliseconds:F2} ms"); + Console.WriteLine($"Average CPU time per frame: {averageMs:F2} ms"); + } } } \ No newline at end of file diff --git a/barcode-recognition-performance/create-unit-tests-ensuring-minimalxdimension-defaults-to-zero-when-useminimalxdimension-is-false.cs b/barcode-recognition-performance/create-unit-tests-ensuring-minimalxdimension-defaults-to-zero-when-useminimalxdimension-is-false.cs index 86205b9..5c4545e 100644 --- a/barcode-recognition-performance/create-unit-tests-ensuring-minimalxdimension-defaults-to-zero-when-useminimalxdimension-is-false.cs +++ b/barcode-recognition-performance/create-unit-tests-ensuring-minimalxdimension-defaults-to-zero-when-useminimalxdimension-is-false.cs @@ -1,60 +1,87 @@ // Title: Verify MinimalXDimension default behavior -// Description: Demonstrates checking that MinimalXDimension is zero when UseMinimalXDimension is disabled in barcode quality settings. +// Description: Demonstrates checking that MinimalXDimension is zero when UseMinimalXDimension is not enabled. +// Category-Description: This example belongs to the Aspose.BarCode quality settings category, illustrating how to inspect default values of XDimension-related properties. It uses BarcodeGenerator to create a barcode and BarCodeReader with QualitySettings to validate defaults. Developers working with barcode generation and recognition often need to ensure proper configuration of dimension settings for accurate scanning and printing. // Prompt: Create unit tests ensuring MinimalXDimension defaults to zero when UseMinimalXDimension is false. -// Tags: barcode, symbology, code128, qualitysettings, minimalxdimension, unit-test, aspnet +// Tags: barcode, code128, minimalxdimension, qualitysettings, aspose.barcode, unit-test using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing.Imaging; /// -/// Example program that generates a Code128 barcode, reads it back, -/// and verifies that MinimalXDimension defaults to zero when the -/// XDimension mode is not set to UseMinimalXDimension. +/// Example program that generates a Code128 barcode, reads it back, and verifies that +/// defaults to zero when +/// is not selected. This serves as a simple unit‑test‑style validation. /// class Program { /// - /// Entry point of the example. Generates a barcode, reads it, - /// and checks the MinimalXDimension default value. + /// Entry point of the example. Performs barcode generation, validation, and cleanup. /// static void Main() { - // Generate a simple Code128 barcode and keep it in memory. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123")) + // ------------------------------------------------------------ + // Prepare a temporary folder for the generated barcode image + // ------------------------------------------------------------ + string tempFolder = Path.Combine(Path.GetTempPath(), "AsposeBarcodeTest"); + if (!Directory.Exists(tempFolder)) { - // Use default settings (AutoSizeMode.None, default XDimension). - using (var ms = new MemoryStream()) + Directory.CreateDirectory(tempFolder); + } + + // Define the full path for the barcode image file + string imagePath = Path.Combine(tempFolder, "code128.png"); + + // ------------------------------------------------------------ + // Generate a simple Code128 barcode image + // ------------------------------------------------------------ + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + { + generator.Save(imagePath); + } + + // ------------------------------------------------------------ + // Verify that MinimalXDimension defaults to zero when UseMinimalXDimension is false + // ------------------------------------------------------------ + bool testPassed = true; + using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + { + // Set XDimension mode to Auto (i.e., not using MinimalXDimension) + reader.QualitySettings.XDimension = XDimensionMode.Auto; + + // Expect MinimalXDimension to be zero by default + if (reader.QualitySettings.MinimalXDimension != 0f) { - // Save the barcode image to the memory stream in PNG format. - generator.Save(ms, BarCodeImageFormat.Png); - ms.Position = 0; // Reset stream position for reading. - - // Create a reader for the generated image. - using (var reader = new BarCodeReader(ms, DecodeType.Code128)) - { - // Ensure the XDimension mode is NOT UseMinimalXDimension. - if (reader.QualitySettings.XDimension == XDimensionMode.UseMinimalXDimension) - { - Console.WriteLine("FAILED: XDimension mode is unexpectedly UseMinimalXDimension."); - return; - } - - // Verify that MinimalXDimension defaults to zero. - float minimal = reader.QualitySettings.MinimalXDimension; - if (Math.Abs(minimal) < 0.0001f) - { - Console.WriteLine("PASSED: MinimalXDimension defaults to zero when UseMinimalXDimension is false."); - } - else - { - Console.WriteLine($"FAILED: MinimalXDimension is {minimal}, expected 0."); - } - } + testPassed = false; + Console.WriteLine($"FAILED: MinimalXDimension expected 0, but was {reader.QualitySettings.MinimalXDimension}"); } } + + // Output the test result + if (testPassed) + { + Console.WriteLine("PASSED: MinimalXDimension defaults to zero when UseMinimalXDimension is false."); + } + + // ------------------------------------------------------------ + // Clean up generated files and temporary folder + // ------------------------------------------------------------ + try + { + if (File.Exists(imagePath)) + { + File.Delete(imagePath); + } + + if (Directory.Exists(tempFolder)) + { + Directory.Delete(tempFolder, true); + } + } + catch + { + // Ignored – cleanup failures should not affect the test outcome + } } } \ No newline at end of file diff --git a/barcode-recognition-performance/deactivate-useminimalxdimension-after-processing-to-restore-default-element-size-handling.cs b/barcode-recognition-performance/deactivate-useminimalxdimension-after-processing-to-restore-default-element-size-handling.cs index 00e4904..d80ffc1 100644 --- a/barcode-recognition-performance/deactivate-useminimalxdimension-after-processing-to-restore-default-element-size-handling.cs +++ b/barcode-recognition-performance/deactivate-useminimalxdimension-after-processing-to-restore-default-element-size-handling.cs @@ -1,83 +1,79 @@ -// Title: Demonstrate Deactivating UseMinimalXDimension After Barcode Processing -// Description: Creates a Code128 barcode, reads it with minimal X dimension mode enabled, then disables the mode to revert to default handling. +// Title: Demonstrate toggling UseMinimalXDimension for barcode reading +// Description: Shows how to enable and then deactivate the UseMinimalXDimension setting when reading a Code128 barcode, ensuring default element size handling is restored. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating the use of BarCodeReader and its QualitySettings to control X‑dimension handling. Developers often need to adjust minimal element sizes for small or low‑resolution barcodes and then revert to automatic sizing for subsequent operations. The snippet highlights key classes such as BarcodeGenerator, BarCodeReader, and related enums, serving as a reference for similar use‑case examples. // Prompt: Deactivate UseMinimalXDimension after processing to restore default element size handling. -// Tags: barcode, code128, useminimalxdimension, xdimension, generation, recognition, aspnet, csharp +// Tags: barcode, code128, useminimalxdimension, qualitysettings, generation, recognition, png, aspose.barcode using System; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Example program that generates a barcode, reads it with minimal X dimension mode, -/// then deactivates the mode to restore default element size handling. +/// Example program that generates a Code128 barcode, reads it with minimal X dimension enabled, +/// then deactivates the setting to revert to default handling. /// class Program { /// - /// Entry point of the example. Generates a barcode image, reads it with different XDimension settings, - /// and cleans up the temporary file. + /// Entry point of the example. Generates a barcode image, reads it with different X‑dimension settings, + /// and outputs the results to the console. /// static void Main() { - // Path for the temporary barcode image - string imagePath = "barcode.png"; + // Define the output file path for the generated barcode image + string barcodePath = "barcode.png"; - // ------------------------------------------------------------ - // Generate a simple Code128 barcode and save it to a PNG file - // ------------------------------------------------------------ - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // ------------------------------------------------- + // Generate a simple Code128 barcode and save it as PNG + // ------------------------------------------------- + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - generator.Save(imagePath, BarCodeImageFormat.Png); + // Use explicit size settings (no automatic scaling) + generator.Parameters.AutoSizeMode = AutoSizeMode.None; + generator.Parameters.Barcode.BarHeight.Point = 50f; + + // Save the barcode image to the specified path + generator.Save(barcodePath, BarCodeImageFormat.Png); } - // Verify that the image was created successfully - if (!File.Exists(imagePath)) + // Verify that the barcode image was successfully created + if (!File.Exists(barcodePath)) { - Console.WriteLine("Failed to create the barcode image."); + Console.WriteLine("Failed to create barcode image."); return; } - // ------------------------------------------------------------ - // Read the barcode with UseMinimalXDimension enabled - // ------------------------------------------------------------ - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + // ------------------------------------------------- + // First read: enable UseMinimalXDimension to handle small elements + // ------------------------------------------------- + using (var reader = new BarCodeReader(barcodePath, DecodeType.Code128)) { - // Activate minimal X dimension mode for small barcodes + // Activate minimal X dimension mode with a custom minimal size reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - reader.QualitySettings.MinimalXDimension = 5f; // optional minimal size + reader.QualitySettings.MinimalXDimension = 5f; // example minimal size in points Console.WriteLine("Reading with UseMinimalXDimension enabled:"); - foreach (var result in reader.ReadBarCodes()) + foreach (BarCodeResult result in reader.ReadBarCodes()) { - Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}"); + Console.WriteLine($" CodeText: {result.CodeText}"); + Console.WriteLine($" Confidence: {result.Confidence}"); } - // ------------------------------------------------------------ + // ------------------------------------------------- // Deactivate UseMinimalXDimension to restore default handling - // ------------------------------------------------------------ - reader.QualitySettings.XDimension = XDimensionMode.Auto; // default mode - Console.WriteLine("UseMinimalXDimension deactivated; XDimension mode reset to default."); + // ------------------------------------------------- + reader.QualitySettings.XDimension = XDimensionMode.Auto; // revert to default mode + reader.QualitySettings.MinimalXDimension = 0f; // reset minimal size - // Optional: read again using the default XDimension mode - Console.WriteLine("Reading again with default XDimension mode:"); - foreach (var result in reader.ReadBarCodes()) + Console.WriteLine("Reading after deactivating UseMinimalXDimension:"); + foreach (BarCodeResult result in reader.ReadBarCodes()) { - Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}"); + Console.WriteLine($" CodeText: {result.CodeText}"); + Console.WriteLine($" Confidence: {result.Confidence}"); } } - - // ------------------------------------------------------------ - // Clean up the temporary image file - // ------------------------------------------------------------ - try - { - File.Delete(imagePath); - } - catch - { - // Ignore any errors during cleanup - } } } \ No newline at end of file diff --git a/barcode-recognition-performance/develop-diagnostic-mode-that-outputs-raw-pixel-matrix-used-for-barcode-detection-when-debugging.cs b/barcode-recognition-performance/develop-diagnostic-mode-that-outputs-raw-pixel-matrix-used-for-barcode-detection-when-debugging.cs index c0ab568..4eda15a 100644 --- a/barcode-recognition-performance/develop-diagnostic-mode-that-outputs-raw-pixel-matrix-used-for-barcode-detection-when-debugging.cs +++ b/barcode-recognition-performance/develop-diagnostic-mode-that-outputs-raw-pixel-matrix-used-for-barcode-detection-when-debugging.cs @@ -1,72 +1,78 @@ -// Title: Barcode generation with diagnostic pixel matrix output -// Description: Demonstrates generating a Code128 barcode, printing its raw pixel matrix for debugging, and recognizing the barcode. +// Title: Diagnostic mode output of raw pixel matrix for barcode detection +// Description: Demonstrates generating a Code128 barcode, printing its grayscale pixel matrix, and recognizing the barcode. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showcasing how to use BarcodeGenerator, BarCodeReader, and related parameter classes. Typical use cases include debugging barcode rendering, validating image quality, and extracting raw pixel data for custom analysis. Developers often need to inspect the pixel matrix when troubleshooting detection issues. // Prompt: Develop a diagnostic mode that outputs the raw pixel matrix used for barcode detection when debugging. -// Tags: barcode symbology, generation, recognition, diagnostic, pixel matrix, console output +// Tags: barcode symbology, generation, recognition, diagnostic, raw pixel matrix, grayscale, aspose.barcode, code128 using System; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; -using Aspose.Drawing.Imaging; /// -/// Example program that generates a Code128 barcode, prints its raw pixel matrix for diagnostic purposes, -/// and then reads the barcode using Aspose.BarCode. +/// Example program that generates a Code128 barcode, prints its raw grayscale pixel matrix, +/// and then performs barcode recognition on the generated image. /// class Program { /// - /// Entry point. Generates a barcode, outputs its pixel matrix, and performs recognition. + /// Entry point of the example. Generates a barcode, outputs diagnostic pixel data, + /// and reads back the barcode information. /// static void Main() { - // Generate a simple Code128 barcode in memory - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "12345")) + // Generate a simple Code128 barcode image in memory + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { + // Optional: configure generation parameters for size and scaling + generator.Parameters.Barcode.XDimension.Point = 2f; + generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; + generator.Parameters.ImageWidth.Point = 300f; + generator.Parameters.ImageHeight.Point = 100f; + // Create the barcode image as a Bitmap using (Bitmap barcodeImage = generator.GenerateBarCodeImage()) { - // Output the raw pixel matrix (0 = white, 1 = black) for diagnostic debugging - PrintPixelMatrix(barcodeImage); + // Output raw pixel matrix (grayscale intensity) to console for diagnostic purposes + Console.WriteLine("Raw pixel matrix (grayscale intensity):"); + for (int y = 0; y < barcodeImage.Height; y++) + { + for (int x = 0; x < barcodeImage.Width; x++) + { + // Retrieve pixel color and compute average intensity + Color pixel = barcodeImage.GetPixel(x, y); + int intensity = (pixel.R + pixel.G + pixel.B) / 3; + + // Print intensity value, padded for alignment + Console.Write(intensity.ToString().PadLeft(3)); + if (x < barcodeImage.Width - 1) Console.Write(" "); + } + Console.WriteLine(); + } - // Perform barcode recognition on the same image - using (var reader = new BarCodeReader(barcodeImage)) + // Perform barcode recognition on the generated image + using (var reader = new BarCodeReader()) { - // Iterate through all detected barcodes + // Assign the generated image to the reader + reader.SetBarCodeImage(barcodeImage); + + // Use all supported barcode types for detection + reader.BarCodeReadType = DecodeType.AllSupportedTypes; + + // Iterate through detected barcodes and display results foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine("Detected Barcode Type: " + result.CodeTypeName); - Console.WriteLine("Detected CodeText: " + result.CodeText); - var rect = result.Region.Rectangle; - Console.WriteLine($"Region - X:{rect.X}, Y:{rect.Y}, Width:{rect.Width}, Height:{rect.Height}"); - Console.WriteLine($"Angle: {result.Region.Angle}"); + Console.WriteLine(); + Console.WriteLine("Detected Barcode:"); + Console.WriteLine(" Type: " + result.CodeTypeName); + Console.WriteLine(" CodeText: " + result.CodeText); + + // Output the detected region bounds + var bounds = result.Region.Rectangle; + Console.WriteLine($" Region: X={bounds.X}, Y={bounds.Y}, Width={bounds.Width}, Height={bounds.Height}"); } } } } } - - // Prints the bitmap pixel matrix to the console. - // Uses a simple threshold to convert color to binary (black/white). - static void PrintPixelMatrix(Bitmap bitmap) - { - int width = bitmap.Width; - int height = bitmap.Height; - Console.WriteLine("Pixel Matrix (1 = black, 0 = white):"); - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - // Retrieve the pixel color at (x, y) - Color pixel = bitmap.GetPixel(x, y); - // Compute luminance as average of RGB components - int luminance = (pixel.R + pixel.G + pixel.B) / 3; - // Threshold at mid-point (128) to obtain binary value - int binary = luminance < 128 ? 1 : 0; - Console.Write(binary); - } - Console.WriteLine(); - } - } } \ No newline at end of file diff --git a/barcode-recognition-performance/enable-multi-threaded-recognition-and-compare-throughput-against-single-threaded-execution-on-set-of-images.cs b/barcode-recognition-performance/enable-multi-threaded-recognition-and-compare-throughput-against-single-threaded-execution-on-set-of-images.cs index 173cbbd..bb69d4c 100644 --- a/barcode-recognition-performance/enable-multi-threaded-recognition-and-compare-throughput-against-single-threaded-execution-on-set-of-images.cs +++ b/barcode-recognition-performance/enable-multi-threaded-recognition-and-compare-throughput-against-single-threaded-execution-on-set-of-images.cs @@ -1,112 +1,87 @@ -// Title: Multi‑Threaded vs Single‑Threaded Barcode Recognition Throughput -// Description: Demonstrates generating Code128 barcodes in memory, then recognizing them using Aspose.BarCode in both single‑threaded and multi‑threaded modes to compare processing time. +// Title: Multi‑Threaded vs Single‑Threaded Barcode Recognition Benchmark +// Description: Demonstrates how to enable multi‑threaded barcode recognition using Aspose.BarCode and compares its throughput against single‑threaded execution on a set of sample images. +// Category-Description: This example belongs to the Aspose.BarCode recognition performance category, showcasing the use of BarCodeReader with ProcessorSettings to control core utilization. Developers often need to benchmark or optimize barcode scanning in high‑volume scenarios, and this snippet illustrates typical API classes (BarCodeReader, DecodeType, ProcessorSettings) and common use cases such as throughput measurement and parallel processing. // Prompt: Enable multi‑threaded recognition and compare throughput against single‑threaded execution on a set of images. -// Tags: barcode, code128, recognition, multithreading, throughput, aspose.barcode, csharp +// Tags: barcode symbology, recognition, performance, multithreading, aspose.barcode, barcodereader, decode type using System; -using System.Collections.Generic; +using System.IO; using System.Diagnostics; -using System.Threading.Tasks; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; /// -/// Example program that generates a set of Code128 barcodes, then -/// reads them using Aspose.BarCode in single‑threaded and multi‑threaded -/// configurations to compare processing throughput. +/// Example program that generates sample barcodes, then measures and compares +/// single‑threaded and multi‑threaded barcode recognition performance using Aspose.BarCode. /// class Program { /// - /// Entry point of the application. + /// Entry point of the application. Generates sample barcodes, runs recognition + /// with different core counts, and outputs the elapsed times. /// static void Main() { - const int sampleCount = 5; // Number of barcode images to generate (kept small for demo) - - // Store generated barcode bitmaps for later recognition - var barcodes = new List(); - - // ------------------------------------------------------------ - // Generate sample barcode images in memory - // ------------------------------------------------------------ - for (int i = 0; i < sampleCount; i++) + // Prepare a folder for sample barcode images + string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(folderPath)) { - string codeText = $"CODE{i:D4}"; - - // Create a barcode generator for Code128 with the specified text - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) - { - // Generate the barcode as a bitmap using default settings - Bitmap bmp = generator.GenerateBarCodeImage(); - - // Keep a copy for recognition tests - barcodes.Add(bmp); - } + Directory.CreateDirectory(folderPath); } - // ------------------------------------------------------------ - // Single‑threaded recognition - // ------------------------------------------------------------ - // Restrict processing to a single core - BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = 1; + // Generate a small set of sample barcode images (5 items) + GenerateSampleBarcodes(folderPath); + + // Measure single‑threaded recognition (force 1 core) + double singleThreadMs = RunRecognition(folderPath, 1); + Console.WriteLine($"Single‑threaded recognition time: {singleThreadMs:F2} ms"); - var swSingle = Stopwatch.StartNew(); // Start timing - int totalResultsSingle = 0; + // Measure multi‑threaded recognition (use all available cores) + int coreCount = Environment.ProcessorCount; + double multiThreadMs = RunRecognition(folderPath, coreCount); + Console.WriteLine($"Multi‑threaded ({coreCount} cores) recognition time: {multiThreadMs:F2} ms"); + } - // Process each bitmap sequentially - foreach (var bmp in barcodes) + // Generates 5 Code128 barcode images with simple texts + private static void GenerateSampleBarcodes(string folder) + { + for (int i = 1; i <= 5; i++) { - using (var reader = new BarCodeReader(bmp, DecodeType.Code128)) + string codeText = $"Sample{i:D2}"; + string filePath = Path.Combine(folder, $"barcode_{i}.png"); + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - // Count all decoded results - foreach (var result in reader.ReadBarCodes()) - { - totalResultsSingle++; - } + // Optional: set a modest size + generator.Parameters.Barcode.XDimension.Point = 2f; + generator.Save(filePath); } } + } - swSingle.Stop(); // Stop timing - - // ------------------------------------------------------------ - // Multi‑threaded recognition - // ------------------------------------------------------------ - // Allow the library to use all available processor cores - BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Environment.ProcessorCount; + // Runs recognition on all PNG files in the folder using the specified core count + private static double RunRecognition(string folder, int coreCount) + { + // Configure the processor cores for BarCodeReader + BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = coreCount; - var swMulti = Stopwatch.StartNew(); // Start timing - int totalResultsMulti = 0; + var stopwatch = Stopwatch.StartNew(); - // Process each bitmap in parallel - Parallel.ForEach(barcodes, bmp => + // Iterate through each PNG file and read barcodes + foreach (string file in Directory.GetFiles(folder, "*.png")) { - using (var reader = new BarCodeReader(bmp, DecodeType.Code128)) + using (var reader = new BarCodeReader(file, DecodeType.AllSupportedTypes)) { foreach (var result in reader.ReadBarCodes()) { - // Increment counter in a thread‑safe manner - System.Threading.Interlocked.Increment(ref totalResultsMulti); + // For benchmarking we just iterate through results + // (Optionally, you could count or log them) + string _ = result.CodeText; } } - }); - - swMulti.Stop(); // Stop timing - - // ------------------------------------------------------------ - // Output comparison results - // ------------------------------------------------------------ - Console.WriteLine($"Single‑threaded: {swSingle.ElapsedMilliseconds} ms, total results = {totalResultsSingle}"); - Console.WriteLine($"Multi‑threaded: {swMulti.ElapsedMilliseconds} ms, total results = {totalResultsMulti}"); - - // ------------------------------------------------------------ - // Clean up generated bitmaps - // ------------------------------------------------------------ - foreach (var bmp in barcodes) - { - bmp.Dispose(); } + + stopwatch.Stop(); + return stopwatch.Elapsed.TotalMilliseconds; } } \ No newline at end of file diff --git a/barcode-recognition-performance/enable-qualitysettingsallowincorrectbarcodes-to-capture-potentially-unreadable-barcodes-during-debugging-sessions.cs b/barcode-recognition-performance/enable-qualitysettingsallowincorrectbarcodes-to-capture-potentially-unreadable-barcodes-during-debugging-sessions.cs index 1fdae4b..c110986 100644 --- a/barcode-recognition-performance/enable-qualitysettingsallowincorrectbarcodes-to-capture-potentially-unreadable-barcodes-during-debugging-sessions.cs +++ b/barcode-recognition-performance/enable-qualitysettingsallowincorrectbarcodes-to-capture-potentially-unreadable-barcodes-during-debugging-sessions.cs @@ -1,49 +1,69 @@ -// Title: Code128 Barcode Generation and Recognition with AllowIncorrectBarcodes -// Description: Demonstrates generating a Code128 barcode, saving it as PNG, and reading it back while allowing recognition of potentially unreadable barcodes for debugging. +// Title: Demonstrate barcode generation and reading with AllowIncorrectBarcodes +// Description: This example generates a Code128 barcode, saves it as PNG, then reads it while allowing potentially incorrect barcodes for debugging. +// Category-Description: Shows how to use Aspose.BarCode generation and recognition APIs, focusing on QualitySettings.AllowIncorrectBarcodes. Developers working with barcode validation, debugging unreadable barcodes, or handling low‑quality scans can reference this pattern. Key classes include BarcodeGenerator, BarCodeReader, and QualitySettings. // Prompt: Enable QualitySettings.AllowIncorrectBarcodes to capture potentially unreadable barcodes during debugging sessions. -// Tags: barcode, code128, generation, recognition, allowincorrectbarcodes, aspnet, c# +// Tags: barcode generation, barcode recognition, allowincorrectbarcodes, code128, png, aspose.barcode using System; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Example program that creates a Code128 barcode image and then reads it back, -/// enabling the AllowIncorrectBarcodes setting to capture barcodes that may be damaged or unreadable during debugging. +/// Example program that creates a Code128 barcode image, +/// reads it back with relaxed quality settings, and cleans up the file. /// class Program { /// - /// Entry point of the application. - /// Generates a barcode, saves it, and then reads it while allowing incorrect barcodes. + /// Entry point of the example. Generates a barcode, reads it with + /// QualitySettings.AllowIncorrectBarcodes enabled, and outputs the results. /// static void Main() { + // Define the barcode text to encode. + const string codeText = "1234567890"; + + // Define the output image file path. + const string imagePath = "sample_barcode.png"; + // ------------------------------------------------------------ - // Generate a simple Code128 barcode and save it to a PNG file. + // Generate a Code128 barcode and save it as a PNG image. // ------------------------------------------------------------ - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - // Save the generated barcode image as "barcode.png". - generator.Save("barcode.png"); + generator.Save(imagePath, BarCodeImageFormat.Png); } // ------------------------------------------------------------ - // Read the generated barcode image and output its details. + // Read the generated barcode with relaxed quality settings. // ------------------------------------------------------------ - using (BarCodeReader reader = new BarCodeReader("barcode.png", DecodeType.Code128)) + using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) { - // Enable recognition of potentially incorrect or damaged barcodes. + // Allow detection of barcodes that may be unreadable or malformed. reader.QualitySettings.AllowIncorrectBarcodes = true; - // Iterate through all detected barcodes in the image. + // Iterate through all detected barcodes (there should be only one). foreach (var result in reader.ReadBarCodes()) { - // Output the type of the detected barcode. - Console.WriteLine($"Detected barcode type: {result.CodeTypeName}"); - // Output the decoded text contained in the barcode. - Console.WriteLine($"Decoded text: {result.CodeText}"); + Console.WriteLine($"Detected Type: {result.CodeType}"); + Console.WriteLine($"Detected Text: {result.CodeText}"); + } + } + + // ------------------------------------------------------------ + // Optional cleanup: delete the generated image file. + // ------------------------------------------------------------ + if (File.Exists(imagePath)) + { + try + { + File.Delete(imagePath); + } + catch + { + // Suppress any errors that occur during file deletion. } } } diff --git a/barcode-recognition-performance/evaluate-qr-code-detection-speed-when-useminimalxdimension-is-disabled-versus-enabled.cs b/barcode-recognition-performance/evaluate-qr-code-detection-speed-when-useminimalxdimension-is-disabled-versus-enabled.cs index ed49205..f281e12 100644 --- a/barcode-recognition-performance/evaluate-qr-code-detection-speed-when-useminimalxdimension-is-disabled-versus-enabled.cs +++ b/barcode-recognition-performance/evaluate-qr-code-detection-speed-when-useminimalxdimension-is-disabled-versus-enabled.cs @@ -1,7 +1,8 @@ -// Title: QR Code detection speed comparison with and without UseMinimalXDimension -// Description: Demonstrates generating a QR code image and measuring the barcode detection time when the XDimension mode is set to Auto versus UseMinimalXDimension. -// Prompt: Evaluate QR code detection speed when UseMinimalXDimension is disabled versus enabled. -// Tags: qr code, detection speed, xdimension, minimalxdimension, aspose.barcode, performance +// Title: QR Code Detection Speed with and without UseMinimalXDimension +// Description: Demonstrates measuring the time required to detect a QR code when the UseMinimalXDimension setting is disabled versus enabled. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the BarcodeGenerator for creating QR codes and the BarCodeReader for detecting them, focusing on the XDimension quality settings. Developers often need to compare detection performance under different X dimension modes to optimize scanning speed and accuracy in applications such as inventory management, ticketing, and mobile payments. +/// Prompt: Evaluate QR code detection speed when UseMinimalXDimension is disabled versus enabled. +/// Tags: qr, detection, performance, minimalxdimension, aspose.barcode, generation, recognition using System; using System.Diagnostics; @@ -10,77 +11,81 @@ using Aspose.BarCode.BarCodeRecognition; /// -/// Generates a QR code image and compares detection performance using different XDimension settings. +/// Example program that generates a QR code image and measures detection performance +/// with the UseMinimalXDimension quality setting both disabled and enabled. /// class Program { /// - /// Entry point of the application. Generates a QR code, then measures detection time with - /// XDimensionMode.Auto and XDimensionMode.UseMinimalXDimension. + /// Entry point of the application. Generates a QR code, then measures and prints + /// detection times for two X dimension modes. /// static void Main() { - // Path for the generated QR code image const string imagePath = "qr.png"; + const string qrText = "Sample QR Code Text for performance test"; // Generate a QR code image and save it as PNG - using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Test QR Code")) + using (var generator = new BarcodeGenerator(EncodeTypes.QR, qrText)) { generator.Save(imagePath, BarCodeImageFormat.Png); } - // Verify that the image was created successfully - if (!System.IO.File.Exists(imagePath)) - { - Console.WriteLine("Failed to create QR code image."); - return; - } - // Measure detection time with UseMinimalXDimension disabled (default Auto mode) - double timeAuto = MeasureReadTime(imagePath, useMinimal: false); - Console.WriteLine($"Detection time (XDimensionMode.Auto): {timeAuto} ms"); + long timeWithoutMinimal = MeasureDetectionTime(imagePath, useMinimal: false, out int countWithoutMinimal); - // Measure detection time with UseMinimalXDimension enabled - double timeMinimal = MeasureReadTime(imagePath, useMinimal: true); - Console.WriteLine($"Detection time (XDimensionMode.UseMinimalXDimension): {timeMinimal} ms"); + // Measure detection time with UseMinimalXDimension enabled (custom minimal X dimension) + long timeWithMinimal = MeasureDetectionTime(imagePath, useMinimal: true, out int countWithMinimal); + + // Output the results + Console.WriteLine($"Detection without UseMinimalXDimension: {timeWithoutMinimal} ms, barcodes detected: {countWithoutMinimal}"); + Console.WriteLine($"Detection with UseMinimalXDimension: {timeWithMinimal} ms, barcodes detected: {countWithMinimal}"); } - // Reads the barcode from the specified image and returns the elapsed time in milliseconds. - static double MeasureReadTime(string imagePath, bool useMinimal) + /// + /// Measures the time taken to read barcodes from an image using the specified X dimension mode. + /// + /// Path to the image containing the QR code. + /// If true, enables UseMinimalXDimension mode; otherwise uses Auto mode. + /// Outputs the number of barcodes detected. + /// Elapsed time in milliseconds. + private static long MeasureDetectionTime(string imagePath, bool useMinimal, out int detectedCount) { - var stopwatch = new Stopwatch(); + detectedCount = 0; // Initialize the barcode reader for QR codes using (var reader = new BarCodeReader(imagePath, DecodeType.QR)) { - // Configure quality settings based on the requested XDimension mode if (useMinimal) { - // Enable minimal X dimension detection for higher performance - reader.QualitySettings = QualitySettings.HighPerformance; + // Enable UseMinimalXDimension mode and set a minimal X dimension value reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - reader.QualitySettings.MinimalXDimension = 2f; // example minimal size in pixels + reader.QualitySettings.MinimalXDimension = 5f; } else { - // Use default detection mode (Auto) - reader.QualitySettings = QualitySettings.HighPerformance; + // Use default automatic X dimension detection reader.QualitySettings.XDimension = XDimensionMode.Auto; } - // Start timing, perform detection, then stop timing - stopwatch.Start(); + // Start timing the detection process + var stopwatch = Stopwatch.StartNew(); + + // Perform barcode detection var results = reader.ReadBarCodes(); + + // Stop timing stopwatch.Stop(); - // Output detected code texts (optional, ensures results are processed) + // Iterate through results to ensure full processing foreach (var result in results) { - Console.WriteLine($"Detected CodeText: {result.CodeText}"); + Console.WriteLine($"Detected: {result.CodeTypeName} - {result.CodeText}"); + detectedCount++; } - } - // Return elapsed time in milliseconds - return stopwatch.Elapsed.TotalMilliseconds; + // Return elapsed time in milliseconds + return stopwatch.ElapsedMilliseconds; + } } } \ No newline at end of file diff --git a/barcode-recognition-performance/evaluate-recognition-success-rate-for-rotated-datamatrix-codes-at-0-45-and-90-angles.cs b/barcode-recognition-performance/evaluate-recognition-success-rate-for-rotated-datamatrix-codes-at-0-45-and-90-angles.cs index 7abe757..636d4a3 100644 --- a/barcode-recognition-performance/evaluate-recognition-success-rate-for-rotated-datamatrix-codes-at-0-45-and-90-angles.cs +++ b/barcode-recognition-performance/evaluate-recognition-success-rate-for-rotated-datamatrix-codes-at-0-45-and-90-angles.cs @@ -1,71 +1,135 @@ -// Title: DataMatrix rotation recognition test -// Description: Demonstrates generating DataMatrix barcodes at different rotation angles and measuring recognition success rate. +// Title: Evaluate recognition success rate for rotated DataMatrix barcodes +// Description: Generates DataMatrix barcodes, rotates them at 0°, 45°, and 90°, and measures how often Aspose.BarCode correctly reads the encoded text. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, demonstrating how to create, manipulate, and read DataMatrix symbols using BarcodeGenerator, BarCodeReader, and related imaging classes. Typical use cases include testing scanner robustness against rotated symbols and validating recognition algorithms. Developers often need to generate test images, apply transformations, and programmatically assess decoding success rates. // Prompt: Evaluate recognition success rate for rotated DataMatrix codes at 0°, 45°, and 90° angles. -// Tags: datamatrix, rotation, recognition, success-rate, aspose.barcode, csharp +// Tags: datamatrix, recognition, rotation, success-rate, aspose.barcodes, barcode-generation, barcode-reader using System; +using System.IO; using System.Collections.Generic; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Generates DataMatrix barcodes at various rotation angles, -/// attempts to recognize them, and reports the overall success rate. +/// Demonstrates generating DataMatrix barcodes, rotating them, and evaluating recognition success rate using Aspose.BarCode. /// class Program { /// - /// Entry point of the application. Executes the rotation test and prints results. + /// Entry point. Generates images at specified angles, reads them back, and prints the success rate. /// static void Main() { // Text to encode in the DataMatrix barcode - const string codeText = "TestDataMatrix12345"; + const string codeText = "TestDataMatrix123"; - // Rotation angles (in degrees) to evaluate - float[] angles = { 0f, 45f, 90f }; - int successful = 0; + // Directory to store generated barcode images + string folder = Path.Combine(Directory.GetCurrentDirectory(), "DataMatrixSamples"); + if (!Directory.Exists(folder)) + { + Directory.CreateDirectory(folder); + } - // Iterate over each angle, generate, recognize, and log the outcome - foreach (float angle in angles) + // Angles (in degrees) at which the barcode will be rotated for testing + int[] angles = new int[] { 0, 45, 90 }; + var imagePaths = new List(); + + // ----------------------------------------------------------------- + // Generate a barcode for each angle and optionally rotate it + // ----------------------------------------------------------------- + foreach (int angle in angles) { - // Create a barcode generator for DataMatrix with the specified text + // Create a DataMatrix barcode generator with the specified text using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, codeText)) { - // Apply rotation to the generated barcode image - generator.Parameters.RotationAngle = angle; - - // Generate the barcode as a bitmap image - using (Bitmap bitmap = generator.GenerateBarCodeImage()) + // Save the generated barcode to a memory stream as PNG + using (var ms = new MemoryStream()) { - // Initialize a reader to decode DataMatrix barcodes from the bitmap - using (var reader = new BarCodeReader(bitmap, DecodeType.DataMatrix)) + generator.Save(ms, BarCodeImageFormat.Png); + ms.Position = 0; + + // Load the PNG into a bitmap for further processing + using (var original = new Bitmap(ms)) { - bool recognized = false; + string filePath = Path.Combine(folder, $"DataMatrix_{angle}.png"); - // Scan all detected barcodes in the image - foreach (BarCodeResult result in reader.ReadBarCodes()) + if (angle == 0) + { + // No rotation needed; save the original bitmap directly + original.Save(filePath, ImageFormat.Png); + } + else { - // Verify that the decoded text matches the original - if (!string.IsNullOrEmpty(result.CodeText) && result.CodeText == codeText) + // Rotate the bitmap around its center by the specified angle + int width = original.Width; + int height = original.Height; + using (var rotated = new Bitmap(width, height)) { - recognized = true; - break; + using (var g = Graphics.FromImage(rotated)) + { + g.Clear(Aspose.Drawing.Color.White); + g.TranslateTransform(width / 2f, height / 2f); + g.RotateTransform(angle); + g.TranslateTransform(-width / 2f, -height / 2f); + g.DrawImage(original, 0, 0, width, height); + } + rotated.Save(filePath, ImageFormat.Png); } } - // Output the result for the current angle - Console.WriteLine($"Angle {angle}°: {(recognized ? "Success" : "Failure")}"); - if (recognized) successful++; + // Keep track of the generated image path for later recognition + imagePaths.Add(filePath); } } } } - // Calculate and display the overall recognition success rate - double successRate = (double)successful / angles.Length * 100.0; - Console.WriteLine($"Recognition success rate: {successRate:F2}%"); + // ----------------------------------------------------------------- + // Recognize each generated image and count successful decodings + // ----------------------------------------------------------------- + int successCount = 0; + foreach (string path in imagePaths) + { + if (!File.Exists(path)) + { + Console.WriteLine($"File not found: {path}"); + continue; + } + + // Initialize a barcode reader for DataMatrix symbology + using (var reader = new BarCodeReader(path, DecodeType.DataMatrix)) + { + var results = reader.ReadBarCodes(); + bool success = false; + + // Check each decoded result for a match with the original text + foreach (var result in results) + { + if (!string.IsNullOrEmpty(result.CodeText) && result.CodeText == codeText) + { + success = true; + break; + } + } + + if (success) + { + successCount++; + Console.WriteLine($"Success: {Path.GetFileName(path)}"); + } + else + { + Console.WriteLine($"Failure: {Path.GetFileName(path)}"); + } + } + } + + // ----------------------------------------------------------------- + // Compute and display the overall recognition success rate + // ----------------------------------------------------------------- + double successRate = (double)successCount / angles.Length * 100.0; + Console.WriteLine($"Recognition success rate: {successRate:F2}% ({successCount}/{angles.Length})"); } } \ No newline at end of file diff --git a/barcode-recognition-performance/generate-heat-map-visualizing-areas-where-barcode-elements-were-detected-using-xdimension-mode.cs b/barcode-recognition-performance/generate-heat-map-visualizing-areas-where-barcode-elements-were-detected-using-xdimension-mode.cs index bde9d44..4cc252e 100644 --- a/barcode-recognition-performance/generate-heat-map-visualizing-areas-where-barcode-elements-were-detected-using-xdimension-mode.cs +++ b/barcode-recognition-performance/generate-heat-map-visualizing-areas-where-barcode-elements-were-detected-using-xdimension-mode.cs @@ -1,91 +1,171 @@ -// Title: Heat Map of Detected Barcode Elements Using XDimension Mode -// Description: Creates a barcode image (if missing), reads it with minimal XDimension settings, and overlays semi‑transparent red rectangles on detected barcode regions to produce a heat map. +// Title: Heat map of detected barcode regions using XDimension mode +// Description: Demonstrates generating multiple barcodes, combining them into a single image, detecting them with XDimension mode, and visualizing detection areas as a heat map. +// Category-Description: This example belongs to the Aspose.BarCode barcode detection and visualization category. It showcases the use of BarcodeGenerator, BarCodeReader, and related graphics classes to create barcodes, read them with XDimension settings, and overlay detection results. Developers often need to locate barcode positions in complex images, and this pattern provides a reusable approach for heat‑map visual feedback. // Prompt: Generate a heat map visualizing areas where barcode elements were detected using XDimension mode. -// Tags: barcode, detection, heatmap, xdimension, aspose.barcode, c# +// Tags: barcode symbology, detection, heat map, xdimension, png, aspose.barcode, aspose.drawing using System; using System.IO; -using Aspose.BarCode; +using System.Collections.Generic; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Demonstrates how to generate a heat map that highlights barcode detection areas -/// using Aspose.BarCode with XDimension mode. +/// Generates sample barcodes, detects them using XDimension mode, and creates a heat‑map overlay +/// showing where barcode elements were found. /// class Program { /// - /// Entry point of the example. Generates a sample barcode (if needed), - /// detects it with minimal XDimension settings, and saves a heat‑mapped image. + /// Entry point of the example. Executes the barcode generation, detection, and heat‑map creation steps. /// static void Main() { - const string barcodePath = "barcode.png"; - const string heatMapPath = "heatmap.png"; + // -------------------------------------------------------------------- + // Prepare output directory + // -------------------------------------------------------------------- + string outputDir = "output"; + if (!Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + // Canvas dimensions for the combined image + const int canvasWidth = 800; + const int canvasHeight = 600; - // ------------------------------------------------------------ - // Step 1: Create a sample barcode image if it does not already exist. - // ------------------------------------------------------------ - if (!File.Exists(barcodePath)) + // -------------------------------------------------------------------- + // Create a white canvas and place randomly positioned barcodes on it + // -------------------------------------------------------------------- + using (Bitmap canvas = new Bitmap(canvasWidth, canvasHeight)) { - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // Fill the canvas with white background + using (Graphics gCanvas = Graphics.FromImage(canvas)) { - // Use interpolation auto‑size mode for better visual quality. - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; + gCanvas.Clear(Aspose.Drawing.Color.White); + } + + var random = new Random(); + var barcodePositions = new List(); + + // Generate 5 sample barcodes + for (int i = 0; i < 5; i++) + { + // Create a Code128 barcode generator with sample text + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i + 1}")) + { + // Set XDimension for better visibility + generator.Parameters.Barcode.XDimension.Point = 2f; + + // Save barcode to a memory stream as PNG + using (var ms = new MemoryStream()) + { + generator.Save(ms, BarCodeImageFormat.Png); + ms.Position = 0; + + // Load the barcode image from the stream + using (Bitmap barcodeBmp = (Bitmap)Bitmap.FromStream(ms)) + { + // Compute a random position that keeps the barcode inside the canvas + int maxX = canvasWidth - barcodeBmp.Width; + int maxY = canvasHeight - barcodeBmp.Height; + int posX = maxX > 0 ? random.Next(0, maxX) : 0; + int posY = maxY > 0 ? random.Next(0, maxY) : 0; - // Set the module (X‑dimension) size to 2 points. - generator.Parameters.Barcode.XDimension.Point = 2f; + // Draw the barcode onto the canvas + using (Graphics g = Graphics.FromImage(canvas)) + { + g.DrawImage(barcodeBmp, posX, posY, barcodeBmp.Width, barcodeBmp.Height); + } - // Save the generated barcode to disk. - generator.Save(barcodePath); + // Record the barcode's location for later reference + barcodePositions.Add(new RectangleF(posX, posY, barcodeBmp.Width, barcodeBmp.Height)); + } + } + } } + + // Save the combined image containing all barcodes + string combinedPath = Path.Combine(outputDir, "combined.png"); + canvas.Save(combinedPath, ImageFormat.Png); } - // ------------------------------------------------------------ - // Step 2: Load the barcode image and initialise the reader. - // ------------------------------------------------------------ - using (var bitmap = new Bitmap(barcodePath)) + // -------------------------------------------------------------------- + // Verify that the combined image was created successfully + // -------------------------------------------------------------------- + string combinedImagePath = Path.Combine(outputDir, "combined.png"); + if (!File.Exists(combinedImagePath)) { - // Enable detection of all supported symbologies. - using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes)) + Console.WriteLine("Combined image not found."); + return; + } + + // -------------------------------------------------------------------- + // Detect barcodes using XDimension mode (minimal XDimension) + // -------------------------------------------------------------------- + List detectedRegions = new List(); + using (var reader = new BarCodeReader(combinedImagePath)) + { + // Read all supported barcode types + reader.BarCodeReadType = DecodeType.AllSupportedTypes; + + // Configure XDimension mode to use the minimal XDimension value + reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; + reader.QualitySettings.MinimalXDimension = 1f; + + // Iterate through detection results + foreach (var result in reader.ReadBarCodes()) { - // Configure the reader to use minimal XDimension mode. - reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - reader.QualitySettings.MinimalXDimension = 2f; // minimal module size in pixels. + RectangleF rect = result.Region.Rectangle; + detectedRegions.Add(rect); + Console.WriteLine($"Detected: {result.CodeTypeName}, Text: {result.CodeText}, Region: {rect}"); + } + } - // Perform barcode recognition. - var results = reader.ReadBarCodes(); + // -------------------------------------------------------------------- + // Build a heat‑map overlay showing detected barcode regions + // -------------------------------------------------------------------- + using (Bitmap heatMap = new Bitmap(canvasWidth, canvasHeight)) + { + using (Graphics gHeat = Graphics.FromImage(heatMap)) + { + // Transparent background for the heat‑map layer + gHeat.Clear(Aspose.Drawing.Color.Transparent); - // ------------------------------------------------------------ - // Step 3: Draw a semi‑transparent red overlay on each detected region. - // ------------------------------------------------------------ - using (var graphics = Graphics.FromImage(bitmap)) + // Draw semi‑transparent red rectangles over each detected region + foreach (var rect in detectedRegions) { - // Define a brush with 50 % opacity red colour. - using (var brush = new SolidBrush(Color.FromArgb(128, Color.Red))) + using (var brush = new SolidBrush(Aspose.Drawing.Color.FromArgb(80, 255, 0, 0))) { - foreach (var result in results) - { - // Retrieve the bounding rectangle of the detected barcode. - var rect = result.Region.Rectangle; + gHeat.FillRectangle(brush, rect); + } + } + } - // Fill the rectangle on the image to create the heat‑map effect. - graphics.FillRectangle(brush, rect.X, rect.Y, rect.Width, rect.Height); - } + // ---------------------------------------------------------------- + // Combine the original image with the heat‑map overlay + // ---------------------------------------------------------------- + using (Bitmap finalImage = new Bitmap(canvasWidth, canvasHeight)) + { + using (Graphics gFinal = Graphics.FromImage(finalImage)) + { + // Draw the original combined image as the base layer + using (var original = (Bitmap)Bitmap.FromFile(combinedImagePath)) + { + gFinal.DrawImage(original, 0, 0, canvasWidth, canvasHeight); } + + // Overlay the heat‑map on top of the original image + gFinal.DrawImage(heatMap, 0, 0, canvasWidth, canvasHeight); } - // ------------------------------------------------------------ - // Step 4: Save the resulting heat‑mapped image. - // ------------------------------------------------------------ - bitmap.Save(heatMapPath, ImageFormat.Png); + // Save the final heat‑map image + string heatMapPath = Path.Combine(outputDir, "heatmap.png"); + finalImage.Save(heatMapPath, ImageFormat.Png); + Console.WriteLine($"Heat map saved to: {heatMapPath}"); } } - - // Inform the user where the heat map was saved. - Console.WriteLine("Heat map saved to: " + Path.GetFullPath(heatMapPath)); } } \ No newline at end of file diff --git a/barcode-recognition-performance/generate-performance-graphs-comparing-recognition-time-versus-xdimension-values-for-sample-dataset.cs b/barcode-recognition-performance/generate-performance-graphs-comparing-recognition-time-versus-xdimension-values-for-sample-dataset.cs index 33d3523..668944e 100644 --- a/barcode-recognition-performance/generate-performance-graphs-comparing-recognition-time-versus-xdimension-values-for-sample-dataset.cs +++ b/barcode-recognition-performance/generate-performance-graphs-comparing-recognition-time-versus-xdimension-values-for-sample-dataset.cs @@ -1,9 +1,11 @@ -// Title: Barcode XDimension performance measurement -// Description: Demonstrates how varying the XDimension of a Code128 barcode affects recognition time, useful for performance analysis. +// Title: Barcode recognition performance vs XDimension +// Description: Demonstrates measuring barcode recognition time across different XDimension values and visualizing results. +// Category-Description: This example belongs to the Aspose.BarCode performance testing category, illustrating how to use BarcodeGenerator, BarCodeReader, and related parameters to evaluate recognition speed. Developers often need to benchmark barcode settings such as XDimension to optimize scanning performance in high‑throughput applications. The snippet shows generating Code128 barcodes, timing recognition, and presenting results in a table and ASCII graph. // Prompt: Generate performance graphs comparing recognition time versus XDimension values for a sample dataset. -// Tags: barcode, cod128, xdimension, performance, recognition, aspose.barcode +// Tags: barcode, performance, xdimension, code128, recognition, aspose.barcode, ascii-graph using System; +using System.Collections.Generic; using System.Diagnostics; using System.IO; using Aspose.BarCode; @@ -12,65 +14,101 @@ using Aspose.Drawing; /// -/// Sample console application that measures barcode recognition time while varying the XDimension. +/// Example program that measures barcode recognition time for different XDimension values +/// and displays the results as a table and an ASCII bar graph. /// class Program { /// - /// Entry point. Generates barcodes with different XDimension values, measures recognition time, and outputs CSV data. + /// Entry point of the application. Generates barcodes with varying XDimension, + /// measures recognition latency, and outputs performance data. /// static void Main() { - // Sample barcode text to encode - const string codeText = "Sample123"; + // Sample barcode text (same for all tests) + const string sampleText = "1234567890"; // XDimension values to test (in points) - float[] xDimensions = { 0.5f, 1f, 2f, 3f }; + float[] xDimensions = new float[] { 1f, 2f, 3f, 4f, 5f }; - // CSV header for output - Console.WriteLine("XDimension(Point),RecognitionTime(ms)"); + // Number of recognition repetitions for averaging + const int repetitions = 5; + + // Store average recognition time (ms) for each XDimension + var results = new List<(float XDim, double AvgTime)>(); // Iterate over each XDimension value foreach (float xDim in xDimensions) { - // Generate barcode image in memory for the current XDimension - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + // Generate barcode with specific XDimension + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, sampleText)) { - // Apply the XDimension setting (point unit) + // Disable auto‑sizing to apply custom XDimension + generator.Parameters.AutoSizeMode = AutoSizeMode.None; generator.Parameters.Barcode.XDimension.Point = xDim; - // Optional: fix image size to keep dimensions consistent across tests - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 100f; - - // Store the generated barcode in a memory stream - using (var imageStream = new MemoryStream()) + // Render barcode to bitmap + using (Bitmap bitmap = generator.GenerateBarCodeImage()) { - // Save the barcode as PNG into the stream - generator.Save(imageStream, BarCodeImageFormat.Png); - imageStream.Position = 0; // Reset stream position for reading - - // Initialize barcode reader for Code128 - using (var reader = new BarCodeReader(imageStream, DecodeType.Code128)) + // Warm‑up read (optional, to avoid first‑run overhead) + using (var warmReader = new BarCodeReader(bitmap, DecodeType.Code128)) { - // Start timing the recognition process - var stopwatch = Stopwatch.StartNew(); + warmReader.ReadBarCodes(); + } - // Perform barcode recognition (could return multiple results) - var results = reader.ReadBarCodes(); + // Measure recognition time over several repetitions + double totalMs = 0; + for (int i = 0; i < repetitions; i++) + { + using (var reader = new BarCodeReader(bitmap, DecodeType.Code128)) + { + var sw = Stopwatch.StartNew(); + var detected = reader.ReadBarCodes(); + sw.Stop(); - // Stop timing - stopwatch.Stop(); + totalMs += sw.Elapsed.TotalMilliseconds; - // Record elapsed time in milliseconds (formatted to two decimal places) - double elapsedMs = stopwatch.Elapsed.TotalMilliseconds; - Console.WriteLine($"{xDim},{elapsedMs:F2}"); + // Simple validation to ensure detection succeeded + if (detected.Length == 0 || string.IsNullOrEmpty(detected[0].CodeText)) + { + Console.WriteLine($"Warning: No barcode detected at XDimension {xDim} on iteration {i + 1}."); + } + } } + + // Compute average recognition time for current XDimension + double avgMs = totalMs / repetitions; + results.Add((xDim, avgMs)); } } } - // Indicate that all measurements are complete - Console.WriteLine("Performance measurement completed."); + // Output results as a formatted table + Console.WriteLine("XDimension (pt) | Avg Recognition Time (ms)"); + Console.WriteLine("----------------|--------------------------"); + foreach (var r in results) + { + Console.WriteLine($"{r.XDim,15} | {r.AvgTime,24:F2}"); + } + + // Generate a simple ASCII bar graph to visualize performance + Console.WriteLine(); + Console.WriteLine("Performance Graph (higher bar = longer time)"); + + // Determine the maximum average time to scale bars proportionally + double maxTime = 0; + foreach (var r in results) + { + if (r.AvgTime > maxTime) maxTime = r.AvgTime; + } + + // Scale bars to a maximum width of 50 characters + const int maxBarWidth = 50; + foreach (var r in results) + { + int barLength = maxTime > 0 ? (int)Math.Round(r.AvgTime / maxTime * maxBarWidth) : 0; + string bar = new string('*', barLength); + Console.WriteLine($"{r.XDim,5} pt | {bar}"); + } } } \ No newline at end of file diff --git a/barcode-recognition-performance/generate-summary-report-showing-average-confidence-per-preset-across-test-image-set.cs b/barcode-recognition-performance/generate-summary-report-showing-average-confidence-per-preset-across-test-image-set.cs index 855b9f1..d94361d 100644 --- a/barcode-recognition-performance/generate-summary-report-showing-average-confidence-per-preset-across-test-image-set.cs +++ b/barcode-recognition-performance/generate-summary-report-showing-average-confidence-per-preset-across-test-image-set.cs @@ -1,97 +1,109 @@ -// Title: Barcode confidence summary report -// Description: Generates several barcode images, reads them, and reports the average confidence per barcode type. +// Title: Generate average confidence report for barcode presets +// Description: This example creates barcode images for several presets, reads them back, and calculates the average confidence score for each preset. +// Category-Description: Demonstrates Aspose.BarCode generation and recognition workflows, covering BarcodeGenerator, BarCodeReader, and QualitySettings. Useful for developers testing barcode readability across different symbologies and evaluating scanner confidence metrics. // Prompt: Generate a summary report showing average confidence per preset across a test image set. -// Tags: barcode symbology, confidence analysis, summary report, aspose.barcode, csharp +// Tags: barcode, generation, recognition, confidence, preset, aspose.barcode, png using System; -using System.Collections.Generic; using System.IO; +using System.Collections.Generic; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; // required for Aspose.BarCode image handling /// -/// Demonstrates how to generate barcodes, read them, and calculate the average confidence per preset. +/// Example program that generates barcode images for predefined presets, +/// reads them back, and reports the average confidence per preset. /// class Program { /// - /// Entry point of the application. Generates barcode images, reads them, and prints average confidence values. + /// Entry point of the application. + /// Generates barcodes, scans them, and prints average confidence values. /// static void Main() { - // Create a temporary directory to store generated barcode images. - string tempDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodeDemo"); - if (!Directory.Exists(tempDir)) - Directory.CreateDirectory(tempDir); + // Folder to store generated barcode images + string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(folderPath)) + { + Directory.CreateDirectory(folderPath); + } - // Define a small set of barcode presets to generate and test. - var presets = new List<(BaseEncodeType EncodeType, string CodeText, string FileName)> + // Define presets: each preset has a name, symbology, and codetext + var presets = new List<(string PresetName, BaseEncodeType EncodeType, string CodeText)> { - (EncodeTypes.Code128, "ABC123", "code128.png"), - (EncodeTypes.QR, "https://example.com", "qr.png"), - (EncodeTypes.DataMatrix, "DM12345", "datamatrix.png"), - (EncodeTypes.Pdf417, "PDF417 Sample Text", "pdf417.png") + ("Preset1", EncodeTypes.Code128, "CODE128_SAMPLE"), + ("Preset2", EncodeTypes.QR, "QR_SAMPLE"), + ("Preset3", EncodeTypes.DataMatrix, "DM_SAMPLE"), + ("Preset4", EncodeTypes.Pdf417, "PDF417_SAMPLE"), + ("Preset5", EncodeTypes.Aztec, "AZTEC_SAMPLE") }; - // Generate barcode images for each preset. - foreach (var preset in presets) + // Generate barcode images for each preset + foreach (var (presetName, encodeType, codeText) in presets) { - string filePath = Path.Combine(tempDir, preset.FileName); - using (var generator = new BarcodeGenerator(preset.EncodeType, preset.CodeText)) + string fileName = $"{presetName}_{encodeType.TypeName}.png"; + string filePath = Path.Combine(folderPath, fileName); + + using (var generator = new BarcodeGenerator(encodeType, codeText)) { - // Use default settings; ensure image is saved as PNG. - generator.Save(filePath); + // Use default settings; ensure image is saved as PNG + generator.Save(filePath, BarCodeImageFormat.Png); } } - // Dictionary to accumulate confidence values per preset (using CodeTypeName as key). - var confidenceMap = new Dictionary>(StringComparer.OrdinalIgnoreCase); + // Dictionary to accumulate confidence sums and counts per preset + var confidenceData = new Dictionary(StringComparer.OrdinalIgnoreCase); - // Recognize each generated image and collect confidence data. - foreach (var preset in presets) + // Scan generated PNG files + string[] imageFiles = Directory.GetFiles(folderPath, "*.png"); + foreach (string imageFile in imageFiles) { - string filePath = Path.Combine(tempDir, preset.FileName); - if (!File.Exists(filePath)) + // Extract preset name from file name (format: PresetName_Symbology.png) + string fileName = Path.GetFileNameWithoutExtension(imageFile); + int underscoreIndex = fileName.IndexOf('_'); + if (underscoreIndex <= 0) { - Console.WriteLine($"Warning: File not found - {filePath}"); + Console.WriteLine($"Warning: Unable to determine preset for file '{fileName}'. Skipping."); continue; } + string presetName = fileName.Substring(0, underscoreIndex); - using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes)) + // Read barcode from image + using (var reader = new BarCodeReader(imageFile, DecodeType.AllSupportedTypes)) { + // Use normal quality preset for reliable results + reader.QualitySettings = QualitySettings.NormalQuality; + foreach (BarCodeResult result in reader.ReadBarCodes()) { - string presetName = result.CodeTypeName; // e.g., "Code128", "QR", etc. - int confidenceValue = (int)result.Confidence; // Enum underlying int. + // Convert confidence enum to numeric value + float confidenceValue = (float)result.Confidence; - if (!confidenceMap.ContainsKey(presetName)) - confidenceMap[presetName] = new List(); - - confidenceMap[presetName].Add(confidenceValue); + if (confidenceData.TryGetValue(presetName, out var data)) + { + data.Sum += confidenceValue; + data.Count += 1; + confidenceData[presetName] = data; + } + else + { + confidenceData[presetName] = (confidenceValue, 1); + } } } } - // Output average confidence per preset. + // Output average confidence per preset Console.WriteLine("Average Confidence per Preset:"); - foreach (var kvp in confidenceMap) - { - string presetName = kvp.Key; - List values = kvp.Value; - double average = values.Count > 0 ? (double)values.Sum() / values.Count : 0.0; - Console.WriteLine($"{presetName}: {average:F2}"); - } - - // Cleanup temporary files (optional). - try - { - Directory.Delete(tempDir, true); - } - catch + foreach (var kvp in confidenceData) { - // Ignore any cleanup errors. + string preset = kvp.Key; + float sum = kvp.Value.Sum; + int count = kvp.Value.Count; + float average = count > 0 ? sum / count : 0f; + Console.WriteLine($"{preset}: {average:F2}"); } } } \ No newline at end of file diff --git a/barcode-recognition-performance/implement-feature-that-logs-exact-xdimension-and-minimalxdimension-values-used-for-each-image.cs b/barcode-recognition-performance/implement-feature-that-logs-exact-xdimension-and-minimalxdimension-values-used-for-each-image.cs index 359ff33..e37eb75 100644 --- a/barcode-recognition-performance/implement-feature-that-logs-exact-xdimension-and-minimalxdimension-values-used-for-each-image.cs +++ b/barcode-recognition-performance/implement-feature-that-logs-exact-xdimension-and-minimalxdimension-values-used-for-each-image.cs @@ -1,7 +1,8 @@ -// Title: Barcode XDimension Logging Example -// Description: Demonstrates generating a Code128 barcode with a specific XDimension and recognizing it using minimal XDimension mode while logging the exact values used. +// Title: Barcode XDimension and MinimalXDimension logging example +// Description: Demonstrates generating Code128 barcodes with varying XDimension values and logging the exact dimensions used during generation and recognition. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, showcasing how to control and inspect XDimension settings via the BarcodeGenerator and BarCodeReader classes. Developers often need to fine‑tune module width (XDimension) for printing quality or scanning reliability, and this snippet illustrates typical usage patterns for setting XDimension in points, configuring QualitySettings to use MinimalXDimension, and retrieving those values for diagnostics. // Prompt: Implement a feature that logs the exact XDimension and MinimalXDimension values used for each image. -// Tags: barcode, code128, xdimension, recognition, logging, aspose.barcode, aspose.drawing +// Tags: barcode, code128, xdimension, minimalxdimension, generation, recognition, aspnet, aspose.barcode using System; using System.IO; @@ -9,66 +10,63 @@ using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; -using Aspose.Drawing.Imaging; /// -/// Example program that creates a barcode with a defined XDimension, -/// reads it back using minimal XDimension mode, and logs the dimension values. +/// Generates barcode images with different XDimension values, +/// then reads them back while logging the exact XDimension and MinimalXDimension settings. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Creates output directory, generates barcodes, + /// configures reader quality settings, and logs dimension information. /// static void Main() { - // Initialize a barcode generator for Code128 with sample text - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // Ensure the output directory exists + string outputDir = "Barcodes"; + if (!Directory.Exists(outputDir)) { - // Set the XDimension (module width) to 2 points for generation - generator.Parameters.Barcode.XDimension.Point = 2f; + Directory.CreateDirectory(outputDir); + } - // Create a memory stream to hold the generated barcode image - using (var imageStream = new MemoryStream()) - { - // Generate the barcode image and save it as PNG into the stream - using (Bitmap bitmap = generator.GenerateBarCodeImage()) - { - bitmap.Save(imageStream, ImageFormat.Png); - } + // Generate three barcode images, each with a distinct XDimension (2pt, 4pt, 6pt) + for (int i = 1; i <= 3; i++) + { + // Calculate XDimension in points for the current iteration + float xDim = i * 2f; // 2pt, 4pt, 6pt - // Reset stream position to the beginning for reading - imageStream.Position = 0; + // Build the file path for the generated image + string filePath = Path.Combine(outputDir, $"barcode_{i}.png"); - // Initialize a barcode reader for recognition - using (var reader = new BarCodeReader()) - { - // Assign the generated image to the reader - reader.SetBarCodeImage(imageStream); + // Create a barcode generator for Code128 with sample text + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i}")) + { + // Apply the XDimension (module width) in points + generator.Parameters.Barcode.XDimension.Point = xDim; - // Configure the reader to use minimal XDimension mode - reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - // Set the minimal XDimension value (in points) for recognition - reader.QualitySettings.MinimalXDimension = 3f; + // Save the generated barcode image to disk + generator.Save(filePath); + } - // Iterate over all detected barcodes in the image - foreach (var result in reader.ReadBarCodes()) - { - // Log the XDimension used during barcode generation - Console.WriteLine($"Generated XDimension (points): {generator.Parameters.Barcode.XDimension.Point}"); + // Open the generated image with a barcode reader to inspect settings + using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes)) + { + // Instruct the reader to use MinimalXDimension mode for quality assessment + reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - // Log the MinimalXDimension used during barcode recognition - Console.WriteLine($"Recognition MinimalXDimension (points): {reader.QualitySettings.MinimalXDimension}"); + // Set MinimalXDimension (in pixels) to match the generation XDimension + reader.QualitySettings.MinimalXDimension = xDim; - // Output details of the detected barcode region - var bounds = result.Region.Rectangle; - Console.WriteLine($"Detected barcode region: X={bounds.X}, Y={bounds.Y}, Width={bounds.Width}, Height={bounds.Height}"); + // Perform barcode recognition (results are not used here) + reader.ReadBarCodes(); - // Output the decoded text from the barcode - Console.WriteLine($"Decoded text: {result.CodeText}"); - Console.WriteLine(); - } - } + // Log the dimension values for diagnostic purposes + Console.WriteLine($"Image: {Path.GetFileName(filePath)}"); + Console.WriteLine($" Generator XDimension (points): {xDim}pt"); + Console.WriteLine($" Reader QualitySettings XDimension mode: {reader.QualitySettings.XDimension}"); + Console.WriteLine($" Reader MinimalXDimension (pixels): {reader.QualitySettings.MinimalXDimension}"); + Console.WriteLine(); } } } diff --git a/barcode-recognition-performance/implement-method-that-resets-all-qualitysettings-to-defaults-before-processing-new-image-batch.cs b/barcode-recognition-performance/implement-method-that-resets-all-qualitysettings-to-defaults-before-processing-new-image-batch.cs index f2016ea..c8187a9 100644 --- a/barcode-recognition-performance/implement-method-that-resets-all-qualitysettings-to-defaults-before-processing-new-image-batch.cs +++ b/barcode-recognition-performance/implement-method-that-resets-all-qualitysettings-to-defaults-before-processing-new-image-batch.cs @@ -1,111 +1,91 @@ -// Title: Reset QualitySettings and process barcode images batch -// Description: Demonstrates resetting BarCodeReader quality settings to defaults before reading each image in a batch, generating sample barcodes if needed. +// Title: Reset QualitySettings to defaults before processing barcode images +// Description: Demonstrates resetting BarCodeReader QualitySettings to the default NormalQuality preset before reading a batch of barcode images. +// Category-Description: This example belongs to the Aspose.BarCode image processing category, illustrating how to configure the BarCodeReader's QualitySettings for optimal decoding. It uses key classes such as BarCodeReader, QualitySettings, and BarcodeGenerator, typical for developers who need to batch‑process barcodes with consistent settings. The snippet shows generating sample barcodes, resetting reader settings, and decoding them, a common workflow in inventory or document automation solutions. // Prompt: Implement a method that resets all QualitySettings to defaults before processing a new image batch. -// Tags: barcode symbology, quality settings, batch processing, aspnet barcodereader, aspnet barcodegenerator +// Tags: barcode symbology, reset qualitysettings, batch processing, aspose.barcode, generation, recognition using System; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates resetting quality settings and reading barcodes from a batch of images. +/// Demonstrates resetting QualitySettings to defaults and batch processing barcode images. /// class Program { - // Resets the QualitySettings of the given BarCodeReader to the default preset. - static void ResetReaderQualitySettings(BarCodeReader reader) + // Resets the reader's QualitySettings to the default NormalQuality preset. + static void ResetQualitySettings(BarCodeReader reader) { - // The default preset is NormalQuality. + // Assign the NormalQuality preset, which restores default values for all settings. reader.QualitySettings = QualitySettings.NormalQuality; - } - // Generates a few sample barcode images if the input folder is empty. - static void EnsureSampleImages(string folderPath) - { - // Define file paths for the sample images. - string[] sampleFiles = new string[] - { - Path.Combine(folderPath, "sample_code128.png"), - Path.Combine(folderPath, "sample_qr.png"), - Path.Combine(folderPath, "sample_datamatrix.png") - }; + // Explicitly ensure the AllowIncorrectBarcodes flag is set to its default (false). + reader.QualitySettings.AllowIncorrectBarcodes = false; - // Code128 sample - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) - { - generator.Save(sampleFiles[0]); - } - - // QR sample - using (var generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com")) - { - generator.Save(sampleFiles[1]); - } - - // DataMatrix sample - using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "DM12345")) - { - generator.Save(sampleFiles[2]); - } + // Other properties (e.g., BarcodeQuality, InverseImage) revert to their standard defaults + // when the preset is applied, so no additional code is required here. } /// - /// Entry point. Prepares input folder, generates sample images if needed, and processes up to five barcode images, - /// resetting quality settings for each. + /// Entry point that generates sample barcodes, resets reader settings, and decodes each image. /// static void Main() { - // Define the folder that contains images to be processed. - string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "InputImages"); - - // Ensure the folder exists. - if (!Directory.Exists(inputFolder)) - { - Directory.CreateDirectory(inputFolder); - } + // Create a temporary folder to store generated barcode images. + string folderPath = Path.Combine(Path.GetTempPath(), "AsposeBarcodeSample"); + Directory.CreateDirectory(folderPath); - // Retrieve existing PNG images in the folder. - string[] existingImages = Directory.GetFiles(inputFolder, "*.png"); + // Define sample texts to encode into barcodes. + string[] sampleTexts = { "ABC123", "987XYZ", "Sample001" }; - // If there are no images, create a few sample ones. - if (existingImages.Length == 0) + // Generate barcode images using default generator settings. + for (int i = 0; i < sampleTexts.Length; i++) { - EnsureSampleImages(inputFolder); - existingImages = Directory.GetFiles(inputFolder, "*.png"); + string filePath = Path.Combine(folderPath, $"barcode{i + 1}.png"); + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, sampleTexts[i])) + { + // Save the barcode image to the temporary folder. + generator.Save(filePath); + } } - // Limit processing to a safe number of files (max 5). - int maxFiles = Math.Min(5, existingImages.Length); - for (int i = 0; i < maxFiles; i++) + // Retrieve all generated PNG files for processing. + string[] imageFiles = Directory.GetFiles(folderPath, "*.png"); + + // Iterate over each image file and decode its barcode. + foreach (string imageFile in imageFiles) { - string imagePath = existingImages[i]; - Console.WriteLine($"Processing file: {Path.GetFileName(imagePath)}"); + // Verify the file exists before attempting to read it. + if (!File.Exists(imageFile)) + { + Console.WriteLine($"File not found: {imageFile}"); + continue; + } - // Create a reader for the current image. - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + // Initialize a reader for the current image, targeting Code128 barcodes. + using (var reader = new BarCodeReader(imageFile, DecodeType.Code128)) { - // Reset quality settings to defaults before reading this image. - ResetReaderQualitySettings(reader); + // Reset quality settings to defaults before decoding. + ResetQualitySettings(reader); - // Perform barcode detection. - try + // Read all detected barcodes and output their details. + foreach (BarCodeResult result in reader.ReadBarCodes()) { - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($" Detected Type: {result.CodeTypeName}"); - Console.WriteLine($" Code Text : {result.CodeText}"); - } - } - catch (Exception ex) - { - Console.WriteLine($" Error reading barcode: {ex.Message}"); + Console.WriteLine($"File: {Path.GetFileName(imageFile)} | Type: {result.CodeTypeName} | Text: {result.CodeText}"); } } - - Console.WriteLine(); // Blank line between files. } - Console.WriteLine("Batch processing completed."); + // Attempt to clean up the temporary folder; ignore any errors. + try + { + Directory.Delete(folderPath, true); + } + catch + { + // Cleanup failure is non‑critical; the OS will eventually reclaim the temporary data. + } } } \ No newline at end of file diff --git a/barcode-recognition-performance/implement-region-of-interest-scanning-to-limit-analysis-to-central-rectangle-and-measure-time-savings.cs b/barcode-recognition-performance/implement-region-of-interest-scanning-to-limit-analysis-to-central-rectangle-and-measure-time-savings.cs index cc16bef..40810dd 100644 --- a/barcode-recognition-performance/implement-region-of-interest-scanning-to-limit-analysis-to-central-rectangle-and-measure-time-savings.cs +++ b/barcode-recognition-performance/implement-region-of-interest-scanning-to-limit-analysis-to-central-rectangle-and-measure-time-savings.cs @@ -1,7 +1,8 @@ -// Title: Region-of-Interest Barcode Scanning with Timing -// Description: Demonstrates scanning a barcode image using Aspose.BarCode, first over the full image then within a central ROI, and reports time saved. +// Title: Region‑of‑Interest Scanning with Timing Comparison +// Description: Demonstrates scanning a barcode image using a full‑image scan versus a central region‑of‑interest (ROI) scan to measure performance improvements. +// Category-Description: This example belongs to the Aspose.BarCode scanning category, showcasing the BarCodeReader class with and without ROI constraints. Developers often need to limit barcode detection to specific areas of an image to reduce processing time, especially in high‑resolution or multi‑barcode scenarios. Typical use cases include document processing, industrial automation, and mobile scanning where speed is critical. // Prompt: Implement region‑of‑interest scanning to limit analysis to a central rectangle and measure time savings. -// Tags: barcode, region-of-interest, timing, aspose.barcode, c# +// Tags: qr, scanning, console, barcodelibrary, barcodegenerator, barcodereader, bitmap, rectangle using System; using System.Diagnostics; @@ -11,109 +12,84 @@ using Aspose.Drawing; /// -/// Example program that generates a barcode, scans it using full‑image and ROI modes, -/// and compares the processing times. +/// Example program that generates a QR code (if needed) and compares full‑image barcode scanning +/// with scanning limited to a central region‑of‑interest, reporting the time saved. /// class Program { /// - /// Entry point. Generates a sample barcode, performs two scans (full image and ROI), - /// and outputs detection counts and timing information. + /// Entry point of the application. Performs barcode generation (if required), executes both scanning + /// approaches, and outputs timing results to the console. /// static void Main() { - // ------------------------------------------------------------ - // 1. Generate a sample barcode image and save it to disk - // ------------------------------------------------------------ + // Path for the sample barcode image const string imagePath = "sample_barcode.png"; - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) - { - generator.Save(imagePath); - } - // Verify that the image was created successfully + // Generate a sample QR code if it does not exist if (!File.Exists(imagePath)) { - Console.WriteLine($"Failed to create barcode image at '{imagePath}'."); - return; + using (var generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com")) + { + generator.Save(imagePath); + } } - // ------------------------------------------------------------ - // 2. Load the image once and reuse the bitmap for both scans - // ------------------------------------------------------------ + // Load the image once and reuse it for both scans using (var bitmap = new Bitmap(imagePath)) { - // -------------------------------------------------------- - // 2a. Scan the entire image and measure elapsed time - // -------------------------------------------------------- - var fullScanTime = MeasureScan(bitmap, null, out var fullResults); - Console.WriteLine($"Full scan detected {fullResults} barcode(s) in {fullScanTime} ms."); + // ------------------------------------------------- + // Full image scan + // ------------------------------------------------- + var fullStopwatch = new Stopwatch(); + fullStopwatch.Start(); - // -------------------------------------------------------- - // 2b. Define a central region‑of‑interest (ROI) - // – rectangle covering the middle half of the image - // -------------------------------------------------------- - int roiX = bitmap.Width / 4; - int roiY = bitmap.Height / 4; + using (var fullReader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes)) + { + foreach (var result in fullReader.ReadBarCodes()) + { + // Result processing placeholder (e.g., counting or logging) + } + } + + fullStopwatch.Stop(); + long fullTimeMs = fullStopwatch.ElapsedMilliseconds; + + // ------------------------------------------------- + // Region‑of‑interest (central rectangle) scan + // ------------------------------------------------- + // Define a central rectangle covering 50 % of the image width and height int roiWidth = bitmap.Width / 2; int roiHeight = bitmap.Height / 2; + int roiX = (bitmap.Width - roiWidth) / 2; + int roiY = (bitmap.Height - roiHeight) / 2; var roiRect = new Rectangle(roiX, roiY, roiWidth, roiHeight); - // -------------------------------------------------------- - // 2c. Scan only the ROI and measure elapsed time - // -------------------------------------------------------- - var roiScanTime = MeasureScan(bitmap, roiRect, out var roiResults); - Console.WriteLine($"ROI scan detected {roiResults} barcode(s) in {roiScanTime} ms."); - - // -------------------------------------------------------- - // 3. Report simple time‑savings comparison - // -------------------------------------------------------- - double saved = fullScanTime - roiScanTime; - Console.WriteLine(saved > 0 - ? $"Time saved by ROI: {saved} ms." - : "ROI did not improve scan time."); - } - } - - /// - /// Scans the provided bitmap for barcodes, optionally limited to a region. - /// Returns the elapsed time in milliseconds and outputs the number of barcodes detected. - /// - /// Source image containing barcodes. - /// Optional rectangle defining the region‑of‑interest. - /// Number of barcodes detected during the scan. - /// Elapsed time in milliseconds. - private static long MeasureScan(Bitmap bitmap, Rectangle? region, out int detectedCount) - { - detectedCount = 0; - var stopwatch = Stopwatch.StartNew(); + var roiStopwatch = new Stopwatch(); + roiStopwatch.Start(); - if (region.HasValue) - { - // Scan only the specified rectangle (ROI) - using (var reader = new BarCodeReader(bitmap, region.Value, DecodeType.AllSupportedTypes)) + using (var roiReader = new BarCodeReader(bitmap, new Rectangle[] { roiRect }, DecodeType.AllSupportedTypes)) { - foreach (var result in reader.ReadBarCodes()) + foreach (var result in roiReader.ReadBarCodes()) { - Console.WriteLine($"[ROI] Detected: {result.CodeText}"); - detectedCount++; + // Result processing placeholder (e.g., counting or logging) } } - } - else - { - // Scan the whole image - using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes)) + + roiStopwatch.Stop(); + long roiTimeMs = roiStopwatch.ElapsedMilliseconds; + + // ------------------------------------------------- + // Output timing results + // ------------------------------------------------- + Console.WriteLine($"Full image scan time: {fullTimeMs} ms"); + Console.WriteLine($"ROI (central rectangle) scan time: {roiTimeMs} ms"); + + if (fullTimeMs > 0) { - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"[Full] Detected: {result.CodeText}"); - detectedCount++; - } + double savedPercent = 100.0 * (fullTimeMs - roiTimeMs) / fullTimeMs; + Console.WriteLine($"Time saved by ROI scanning: {savedPercent:F2}%"); } } - - stopwatch.Stop(); - return stopwatch.ElapsedMilliseconds; } } \ No newline at end of file diff --git a/barcode-recognition-performance/load-bmp-images-with-embedded-metadata-and-verify-that-metadata-does-not-affect-recognition-speed.cs b/barcode-recognition-performance/load-bmp-images-with-embedded-metadata-and-verify-that-metadata-does-not-affect-recognition-speed.cs index 0258cb0..024ab72 100644 --- a/barcode-recognition-performance/load-bmp-images-with-embedded-metadata-and-verify-that-metadata-does-not-affect-recognition-speed.cs +++ b/barcode-recognition-performance/load-bmp-images-with-embedded-metadata-and-verify-that-metadata-does-not-affect-recognition-speed.cs @@ -1,56 +1,129 @@ -// Title: Barcode Recognition from BMP with Metadata -// Description: Loads a BMP image that may contain embedded metadata and measures barcode recognition time, demonstrating that metadata does not impact performance. +// Title: Load BMP barcode image with metadata and compare recognition speed +// Description: Demonstrates loading a BMP barcode image, adding EXIF metadata, and measuring whether the metadata impacts barcode recognition performance. +// Category-Description: This example belongs to the Aspose.BarCode image processing category, illustrating how to generate a barcode, embed image metadata using Aspose.Drawing, and evaluate recognition speed with BarCodeReader. Developers working with barcode scanning in image files often need to ensure that added metadata (e.g., EXIF) does not degrade detection performance. The key API classes used are BarcodeGenerator, BarCodeReader, Image, and PropertyItem. // Prompt: Load BMP images with embedded metadata and verify that metadata does not affect recognition speed. -// Tags: barcode, recognition, bmp, metadata, performance, aspose.barcode, aspose.drawing +// Tags: code128, bmp, metadata, performance, generation, recognition, aspose.barcode, aspose.drawing using System; -using System.IO; using System.Diagnostics; -using Aspose.Drawing; +using System.IO; +using System.Text; +using System.Runtime.Serialization; +using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Demonstrates loading a BMP image (potentially containing metadata) and measuring -/// the time required to recognize barcodes using Aspose.BarCode. +/// Demonstrates loading BMP images with embedded metadata and verifying that metadata does not affect recognition speed. /// class Program { /// - /// Entry point of the example. Loads the image, runs barcode recognition, - /// and reports detected barcodes along with the elapsed time. + /// Entry point of the example. Generates a barcode, adds metadata, and measures recognition times. /// static void Main() { - // Path to the BMP image that may contain metadata - string imagePath = "sample.bmp"; + // Prepare output directory + string outputDir = "output"; + if (!Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + // Define file paths for the plain and metadata‑enhanced images + string plainPath = Path.Combine(outputDir, "barcode_plain.bmp"); + string metaPath = Path.Combine(outputDir, "barcode_meta.bmp"); + + // Generate a simple Code128 barcode and save it as a BMP file + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + { + generator.Save(plainPath); + } + + // Measure recognition time for the plain BMP image + double plainTime = MeasureRecognitionTime(plainPath); + Console.WriteLine($"Recognition time for plain BMP: {plainTime:F2} ms"); + + // Embed a text metadata property into the BMP image and save as a new file + AddMetadataToBmp(plainPath, metaPath); + + // Measure recognition time for the BMP image that contains metadata + double metaTime = MeasureRecognitionTime(metaPath); + Console.WriteLine($"Recognition time for BMP with metadata: {metaTime:F2} ms"); + + // Simple verification output comparing the two timings + if (Math.Abs(metaTime - plainTime) < 5.0) + { + Console.WriteLine("Metadata does not significantly affect recognition speed."); + } + else + { + Console.WriteLine("Metadata appears to affect recognition speed."); + } + } - // Verify that the file exists before processing + /// + /// Measures the time (in milliseconds) required to recognize barcodes in the specified image file. + /// + /// Path to the image file to be processed. + /// Elapsed time in milliseconds. + static double MeasureRecognitionTime(string imagePath) + { if (!File.Exists(imagePath)) { - Console.WriteLine($"Image file not found: {imagePath}"); - return; + Console.WriteLine($"File not found: {imagePath}"); + return 0.0; } - // Load the BMP image using Aspose.Drawing within a using block to ensure disposal - using (Bitmap bitmap = new Bitmap(imagePath)) + var stopwatch = new Stopwatch(); + + // Initialize the barcode reader for all supported symbologies + using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) { - // Start timing the barcode recognition process - Stopwatch stopwatch = new Stopwatch(); + // Use normal quality preset for consistent measurement + reader.QualitySettings = QualitySettings.NormalQuality; + stopwatch.Start(); + var results = reader.ReadBarCodes(); + stopwatch.Stop(); - // Create a BarCodeReader for all supported symbologies - using (BarCodeReader reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes)) + // Output detected barcodes (if any) for verification + foreach (var result in results) { - // Iterate through detected barcodes and output their type and text - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"Detected Type: {result.CodeTypeName}, Text: {result.CodeText}"); - } + Console.WriteLine($"Detected: Type={result.CodeTypeName}, Text={result.CodeText}"); } + } - // Stop timing and report the elapsed time - stopwatch.Stop(); - Console.WriteLine($"Recognition elapsed time: {stopwatch.ElapsedMilliseconds} ms"); + return stopwatch.Elapsed.TotalMilliseconds; + } + + /// + /// Adds a simple text metadata property to a BMP image and saves it to a new file. + /// + /// Path to the original BMP image. + /// Path where the metadata‑enhanced BMP will be saved. + static void AddMetadataToBmp(string sourcePath, string destinationPath) + { + using (var image = Image.FromFile(sourcePath)) + { + // Create an uninitialized PropertyItem (required for setting custom properties) + var propItem = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem)); + propItem.Id = 0x010E; // Image Description tag + propItem.Type = 2; // ASCII string type + + // Prepare the description string (null‑terminated as required by BMP metadata) + string description = "Sample metadata for testing"; + byte[] valueBytes = Encoding.ASCII.GetBytes(description + '\0'); + propItem.Value = valueBytes; + propItem.Len = valueBytes.Length; + + // Assign the property to the image + image.SetPropertyItem(propItem); + + // Save the image with the new metadata + image.Save(destinationPath); } } } \ No newline at end of file diff --git a/barcode-recognition-performance/load-high-resolution-png-image-and-measure-barcode-recognition-time-using-default-settings.cs b/barcode-recognition-performance/load-high-resolution-png-image-and-measure-barcode-recognition-time-using-default-settings.cs index 741615e..30a5a9c 100644 --- a/barcode-recognition-performance/load-high-resolution-png-image-and-measure-barcode-recognition-time-using-default-settings.cs +++ b/barcode-recognition-performance/load-high-resolution-png-image-and-measure-barcode-recognition-time-using-default-settings.cs @@ -1,62 +1,54 @@ -// Title: Barcode Recognition Timing from High‑Resolution PNG -// Description: Loads a high‑resolution PNG image, runs barcode detection with default settings, and reports the elapsed time. +// Title: High‑Resolution PNG Barcode Recognition Timing +// Description: Demonstrates loading a high‑resolution PNG image and measuring the time required to recognize barcodes using Aspose.BarCode default settings. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing the use of BarCodeReader with DecodeType.AllSupportedTypes. It illustrates typical scenarios such as performance benchmarking and bulk image processing where developers need to assess recognition speed across various symbologies. // Prompt: Load a high‑resolution PNG image and measure barcode recognition time using default settings. -// Tags: barcode, recognition, timing, png, aspose.barcode, aspose.drawing +// Tags: barcode, png, recognition, performance, timing, aspose.barcode, decodeall using System; using System.Diagnostics; using System.IO; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; /// -/// Demonstrates loading a high‑resolution PNG image, recognizing barcodes, -/// and measuring the recognition time using Aspose.BarCode default settings. +/// Demonstrates loading a high‑resolution PNG image and measuring barcode recognition time using default settings. /// class Program { /// - /// Entry point of the example. Performs image loading, barcode reading, - /// and outputs timing and detection results to the console. + /// Entry point. Accepts optional image path argument, validates file, reads barcodes, and reports timing. /// - static void Main() + /// Command‑line arguments; first argument may specify the image file path. + static void Main(string[] args) { - // Path to the high‑resolution PNG image - string imagePath = "high_res.png"; + // Determine the image file path (use argument if provided, otherwise default to "barcode.png") + string imagePath = args.Length > 0 ? args[0] : "barcode.png"; - // Verify that the image file exists before attempting to load it + // Verify that the specified file exists before attempting to read if (!File.Exists(imagePath)) { - Console.WriteLine($"File not found: {imagePath}"); + Console.WriteLine($"Image file not found: {imagePath}"); return; } - // Load the image into a bitmap using Aspose.Drawing - using (Bitmap bitmap = new Bitmap(imagePath)) + // Initialize BarCodeReader to detect all supported symbologies in the image + using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) { - // Initialize the barcode reader and assign the bitmap as the source image - using (BarCodeReader reader = new BarCodeReader()) - { - reader.SetBarCodeImage(bitmap); - - // Start timing the barcode recognition process - Stopwatch sw = Stopwatch.StartNew(); + // Start timing the recognition process + var stopwatch = Stopwatch.StartNew(); - // Perform barcode detection with default settings - BarCodeResult[] results = reader.ReadBarCodes(); + // Perform barcode detection + var results = reader.ReadBarCodes(); - // Stop the timer once detection is complete - sw.Stop(); + // Stop timing after detection completes + stopwatch.Stop(); - // Output the elapsed time in milliseconds - Console.WriteLine($"Recognition time: {sw.Elapsed.TotalMilliseconds} ms"); + // Output the elapsed time in milliseconds + Console.WriteLine($"Recognition time: {stopwatch.ElapsedMilliseconds} ms"); - // Iterate through all detected barcodes and display their type and text - foreach (BarCodeResult result in results) - { - Console.WriteLine($"BarCode Type: {result.CodeTypeName}"); - Console.WriteLine($"BarCode CodeText: {result.CodeText}"); - } + // Iterate through detected barcodes and display their type and decoded text + foreach (var result in results) + { + Console.WriteLine($"Type: {result.CodeTypeName}, Text: {result.CodeText}"); } } } diff --git a/barcode-recognition-performance/log-recognition-duration-for-each-image-when-varying-qualitysettings-presets-to-evaluate-performance-impact.cs b/barcode-recognition-performance/log-recognition-duration-for-each-image-when-varying-qualitysettings-presets-to-evaluate-performance-impact.cs index eff1ac7..736023e 100644 --- a/barcode-recognition-performance/log-recognition-duration-for-each-image-when-varying-qualitysettings-presets-to-evaluate-performance-impact.cs +++ b/barcode-recognition-performance/log-recognition-duration-for-each-image-when-varying-qualitysettings-presets-to-evaluate-performance-impact.cs @@ -1,75 +1,101 @@ -// Title: Barcode recognition performance across QualitySettings presets -// Description: Demonstrates generating sample barcodes, then measuring recognition duration for each image while applying different QualitySettings presets to assess performance impact. +// Title: Log barcode recognition duration across QualitySettings presets +// Description: Generates sample Code128 barcodes, then measures and logs the time taken to recognize each image using different QualitySettings presets. +// Category-Description: This example belongs to the Aspose.BarCode performance tuning category, demonstrating how to use the BarCodeReader with various QualitySettings (HighPerformance, NormalQuality, HighQuality, MaxQuality) to assess recognition speed. It showcases key API classes such as BarcodeGenerator, BarCodeReader, and QualitySettings, which developers commonly use when optimizing barcode scanning in batch processing or real‑time applications. // Prompt: Log recognition duration for each image when varying QualitySettings presets to evaluate performance impact. -// Tags: barcode, recognition, performance, qualitysettings, aspnet, csharp +// Tags: code128, barcode generation, barcode recognition, png, qualitysettings, performance, aspose.barcode, barcodereader, barcodegenerator using System; -using System.Collections.Generic; +using System.IO; using System.Diagnostics; -using Aspose.BarCode; +using System.Collections.Generic; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Generates sample barcodes and evaluates recognition speed using various QualitySettings presets. +/// Demonstrates how to generate barcode images and log recognition duration +/// while varying presets using Aspose.BarCode. /// class Program { /// - /// Entry point. Generates barcodes, applies each QualitySettings preset, and logs recognition duration. + /// Entry point of the example. Generates sample barcodes, then measures + /// recognition time for each image under different quality settings. /// static void Main() { - // Define sample barcodes to generate and test - var samples = new List<(BaseEncodeType encodeType, string text)> + // -------------------------------------------------------------------- + // Prepare output folder for generated barcode images + // -------------------------------------------------------------------- + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(outputFolder)) { - (EncodeTypes.Code128, "1234567890"), - (EncodeTypes.QR, "https://example.com"), - (EncodeTypes.DataMatrix, "DataMatrixSample") - }; + Directory.CreateDirectory(outputFolder); + } + + // -------------------------------------------------------------------- + // Generate sample barcode images (5 images) using Code128 symbology + // -------------------------------------------------------------------- + List imagePaths = new List(); + for (int i = 1; i <= 5; i++) + { + string codeText = $"CODE{i:D3}"; + string filePath = Path.Combine(outputFolder, $"barcode{i}.png"); + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + { + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; + generator.Save(filePath, BarCodeImageFormat.Png); + } + imagePaths.Add(filePath); + } + // -------------------------------------------------------------------- // Define QualitySettings presets to evaluate - var presets = new (QualitySettings settings, string name)[] + // -------------------------------------------------------------------- + var presets = new List<(string Name, QualitySettings Settings)> { - (QualitySettings.HighPerformance, "HighPerformance"), - (QualitySettings.NormalQuality, "NormalQuality"), - (QualitySettings.HighQuality, "HighQuality"), - (QualitySettings.MaxQuality, "MaxQuality") + ("HighPerformance", QualitySettings.HighPerformance), + ("NormalQuality", QualitySettings.NormalQuality), + ("HighQuality", QualitySettings.HighQuality), + ("MaxQuality", QualitySettings.MaxQuality) }; - int imageIndex = 0; - - // Iterate over each sample barcode definition - foreach (var (encodeType, text) in samples) + // -------------------------------------------------------------------- + // Evaluate each preset by measuring recognition duration per image + // -------------------------------------------------------------------- + foreach (var preset in presets) { - imageIndex++; - - // Generate barcode image for the current sample - using (var generator = new BarcodeGenerator(encodeType, text)) + Console.WriteLine($"--- Evaluating preset: {preset.Name} ---"); + foreach (string imagePath in imagePaths) { - using (var bitmap = generator.GenerateBarCodeImage()) + // Verify that the image file exists before attempting recognition + if (!File.Exists(imagePath)) { - // Test each QualitySettings preset on the generated image - foreach (var (preset, presetName) in presets) - { - // Create a reader for the generated image - using (var reader = new BarCodeReader(bitmap)) - { - // Apply the current QualitySettings preset - reader.QualitySettings = preset; + Console.WriteLine($"File not found: {imagePath}"); + continue; + } + + // Initialize BarCodeReader with all supported decode types + using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + { + // Apply the current QualitySettings preset + reader.QualitySettings = preset.Settings; - // Measure recognition time - var stopwatch = Stopwatch.StartNew(); - var results = reader.ReadBarCodes(); - stopwatch.Stop(); + // Start timing the recognition process + Stopwatch sw = Stopwatch.StartNew(); + var results = reader.ReadBarCodes(); + sw.Stop(); - // Log the elapsed time and number of detected barcodes - Console.WriteLine($"Image {imageIndex}, Preset {presetName}: {stopwatch.ElapsedMilliseconds} ms, Detected {results.Length} barcode(s)."); - } + // Log elapsed time and number of detected barcodes + Console.WriteLine($"{Path.GetFileName(imagePath)}: {sw.ElapsedMilliseconds} ms, Detected {results.Length} barcode(s)"); + foreach (var result in results) + { + Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}"); } } } + Console.WriteLine(); } } } \ No newline at end of file diff --git a/barcode-recognition-performance/measure-impact-of-increasing-image-resolution-from-72-dpi-to-300-dpi-on-detection-latency.cs b/barcode-recognition-performance/measure-impact-of-increasing-image-resolution-from-72-dpi-to-300-dpi-on-detection-latency.cs index 629b347..3de08c8 100644 --- a/barcode-recognition-performance/measure-impact-of-increasing-image-resolution-from-72-dpi-to-300-dpi-on-detection-latency.cs +++ b/barcode-recognition-performance/measure-impact-of-increasing-image-resolution-from-72-dpi-to-300-dpi-on-detection-latency.cs @@ -1,90 +1,94 @@ -// Title: Barcode detection latency vs image resolution -// Description: Demonstrates how changing the image DPI from 72 to 300 affects the time required to detect a Code128 barcode. +// Title: Impact of Image Resolution on Barcode Detection Latency +// Description: Demonstrates how changing barcode image DPI from 72 to 300 affects the time required to recognize the barcode. +// Category-Description: This example belongs to the Aspose.BarCode image processing and recognition category. It showcases the use of BarcodeGenerator for creating barcodes at different resolutions and BarCodeReader for detecting them, a common task when optimizing performance in scanning applications. Developers often need to balance image quality against processing speed, and this snippet provides a measurable comparison. // Prompt: Measure the impact of increasing image resolution from 72 DPI to 300 DPI on detection latency. -// Tags: barcode, code128, detection, latency, resolution, aspose.barcode, png +// Tags: code128, barcode generation, barcode recognition, resolution, latency, aspose.barcode, png using System; using System.Diagnostics; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Example program that generates barcode images at two different DPI settings -/// and measures the detection latency for each image. +/// Demonstrates measuring barcode detection latency at different image resolutions. /// class Program { /// - /// Entry point of the application. Generates low‑ and high‑resolution barcode images, - /// measures detection latency for each, and writes the results to the console. + /// Entry point. Generates barcodes at 72 DPI and 300 DPI, measures and prints detection latency for each. /// static void Main() { - // Define the barcode content to be encoded. - const string barcodeText = "1234567890"; + // Prepare test data: barcode content and symbology types for encoding and decoding + string codeText = "1234567890"; + BaseEncodeType encodeType = EncodeTypes.Code128; + BaseDecodeType decodeType = DecodeType.Code128; - // Generate a low‑resolution (72 DPI) barcode image. - byte[] lowResImage = GenerateBarcodeImage(barcodeText, 72f); - - // Generate a high‑resolution (300 DPI) barcode image. - byte[] highResImage = GenerateBarcodeImage(barcodeText, 300f); - - // Measure how long it takes to detect the barcode in each image. - double lowResLatency = MeasureDetectionLatency(lowResImage); - double highResLatency = MeasureDetectionLatency(highResImage); + // ------------------------------------------------------------ + // Generate barcode image at 72 DPI and measure detection latency + // ------------------------------------------------------------ + using (var ms72 = new MemoryStream()) + { + // Create barcode generator with specified symbology and text + using (var generator = new BarcodeGenerator(encodeType, codeText)) + { + // Set image resolution to 72 DPI (low resolution) + generator.Parameters.Resolution = 72f; + // Save generated barcode to memory stream in PNG format + generator.Save(ms72, BarCodeImageFormat.Png); + } - // Output the measured latencies. - Console.WriteLine($"Resolution: 72 DPI - Detection latency: {lowResLatency:F2} ms"); - Console.WriteLine($"Resolution: 300 DPI - Detection latency: {highResLatency:F2} ms"); - } + // Measure how long it takes to recognize the barcode in the 72 DPI image + double latency72 = MeasureLatency(ms72, decodeType); + Console.WriteLine($"Detection latency at 72 DPI: {latency72} ms"); + } - // Generates a barcode image with the specified resolution (DPI) and returns the PNG bytes. - private static byte[] GenerateBarcodeImage(string text, float resolutionDpi) - { - // Create a barcode generator for Code128 with the supplied text. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, text)) + // ------------------------------------------------------------ + // Generate barcode image at 300 DPI and measure detection latency + // ------------------------------------------------------------ + using (var ms300 = new MemoryStream()) { - // Apply the desired image resolution (dots per inch). - generator.Parameters.Resolution = resolutionDpi; - - // Save the generated barcode to a memory stream in PNG format. - using (var ms = new MemoryStream()) + using (var generator = new BarcodeGenerator(encodeType, codeText)) { - generator.Save(ms, BarCodeImageFormat.Png); - // Return the image data as a byte array. - return ms.ToArray(); + // Set image resolution to 300 DPI (high resolution) + generator.Parameters.Resolution = 300f; + generator.Save(ms300, BarCodeImageFormat.Png); } + + // Measure how long it takes to recognize the barcode in the 300 DPI image + double latency300 = MeasureLatency(ms300, decodeType); + Console.WriteLine($"Detection latency at 300 DPI: {latency300} ms"); } } - // Measures the time taken to detect barcodes in the provided image bytes. - private static double MeasureDetectionLatency(byte[] imageBytes) + /// + /// Measures the time required to recognize a barcode from an image stream. + /// + /// Memory stream containing the barcode image. + /// The barcode symbology to decode. + /// Elapsed time in milliseconds. + static double MeasureLatency(MemoryStream imageStream, BaseDecodeType decodeType) { - // Start timing. + // Reset stream position to the beginning before reading + imageStream.Position = 0; + + // Start timing the recognition process var stopwatch = Stopwatch.StartNew(); - // Load the image bytes into a memory stream for the reader. - using (var ms = new MemoryStream(imageBytes)) + // Perform barcode recognition using BarCodeReader + using (var reader = new BarCodeReader(imageStream, decodeType)) { - // Initialize a barcode reader for Code128 (or use AllSupportedTypes for all symbologies). - using (var reader = new BarCodeReader(ms, DecodeType.Code128)) + // Iterate through all detected barcodes (expected to be one) + foreach (var result in reader.ReadBarCodes()) { - // Perform the recognition operation. - var results = reader.ReadBarCodes(); - - // Iterate through results to ensure full processing and prevent optimizations. - foreach (var result in results) - { - // Output detected barcode information. - Console.WriteLine($"Detected: {result.CodeTypeName} - {result.CodeText}"); - } + // Output detected text to ensure full processing of the result + Console.WriteLine($"Detected: {result.CodeText}"); } } - // Stop timing and return elapsed milliseconds. + // Stop timing and return elapsed milliseconds stopwatch.Stop(); return stopwatch.Elapsed.TotalMilliseconds; } diff --git a/barcode-recognition-performance/measure-memory-consumption-while-recognizing-barcodes-in-large-multi-page-pdf-document.cs b/barcode-recognition-performance/measure-memory-consumption-while-recognizing-barcodes-in-large-multi-page-pdf-document.cs index a23535e..9e4c83a 100644 --- a/barcode-recognition-performance/measure-memory-consumption-while-recognizing-barcodes-in-large-multi-page-pdf-document.cs +++ b/barcode-recognition-performance/measure-memory-consumption-while-recognizing-barcodes-in-large-multi-page-pdf-document.cs @@ -1,97 +1,83 @@ -// Title: Memory consumption measurement while recognizing barcodes in a PDF -// Description: Demonstrates rendering PDF pages to images, recognizing all supported barcodes, and measuring memory usage per page. +// Title: Measure memory usage while recognizing barcodes in a multi‑page PDF +// Description: Demonstrates how to load a PDF, render its pages to images, recognize barcodes, and track memory consumption before and after processing. +// Category-Description: This example belongs to the Aspose.BarCode recognition category, showcasing the use of Document, PngDevice, BarCodeReader, and QualitySettings classes. It illustrates typical scenarios where developers need to process large PDFs, extract barcodes, and monitor resource usage for performance tuning. // Prompt: Measure memory consumption while recognizing barcodes in a large multi‑page PDF document. -// Tags: barcode, recognition, pdf, memory, aspose.barcode, aspose.pdf, aspose.drawing +// Tags: barcode, recognition, pdf, memory, consumption, aspose.barcode, aspose.pdf using System; -using System.Diagnostics; using System.IO; +using System.Diagnostics; using Aspose.BarCode.BarCodeRecognition; using Aspose.Pdf; -using Aspose.Pdf.Facades; -using Aspose.Drawing; +using Aspose.Pdf.Devices; /// -/// Sample console application that renders PDF pages to images, reads all supported barcodes, -/// and reports the memory consumption for each processed page. +/// Demonstrates measuring memory consumption while recognizing barcodes in a large multi‑page PDF document. /// class Program { /// - /// Entry point of the application. + /// Main entry point. Loads a PDF, renders up to four pages to PNG images, reads barcodes, and reports memory usage. /// static void Main() { - // Path to the PDF file to be processed. + // Path to the PDF document to be processed const string pdfPath = "sample.pdf"; - // Validate that the PDF file exists before attempting to load it. + // Verify that the file exists before proceeding if (!File.Exists(pdfPath)) { Console.WriteLine($"File not found: {pdfPath}"); return; } - // Load the PDF document into Aspose.Pdf.Document. - using (var pdfDocument = new Document(pdfPath)) - { - // Initialize a PdfConverter to render PDF pages as images. - using (var pdfConverter = new PdfConverter(pdfDocument)) - { - // Enable barcode optimization to improve rendering performance for barcode‑rich pages. - pdfConverter.RenderingOptions.BarcodeOptimization = true; + // Capture memory usage before any processing + Process proc = Process.GetCurrentProcess(); + long memoryBefore = proc.PrivateMemorySize64; - // Process a limited number of pages (up to 4) to keep the example lightweight. - int maxPages = Math.Min(pdfDocument.Pages.Count, 4); - long totalMemoryUsed = 0; + // Load the PDF document + using (Document pdfDocument = new Document(pdfPath)) + { + // Limit processing to a maximum of 4 pages as per the rules + int pagesToProcess = Math.Min(pdfDocument.Pages.Count, 4); - // Iterate through each page to render, recognize barcodes, and measure memory. - for (int pageNumber = 1; pageNumber <= maxPages; pageNumber++) + // Iterate through each page to be processed + for (int pageIndex = 1; pageIndex <= pagesToProcess; pageIndex++) + { + // Render the current page to a PNG image in memory + using (MemoryStream imageStream = new MemoryStream()) { - // Configure the converter to process the current page only. - pdfConverter.StartPage = pageNumber; - pdfConverter.EndPage = pageNumber; - pdfConverter.DoConvert(); + Resolution resolution = new Resolution(300); + PngDevice pngDevice = new PngDevice(resolution); + pngDevice.Process(pdfDocument.Pages[pageIndex], imageStream); + imageStream.Position = 0; - // Render the page into a memory stream (image format). - using (var imageStream = new MemoryStream()) + // Load the rendered image into an Aspose.Drawing.Bitmap + using (Aspose.Drawing.Bitmap bitmap = new Aspose.Drawing.Bitmap(imageStream)) { - pdfConverter.GetNextImage(imageStream); - imageStream.Position = 0; // Reset stream position for reading. - - // Load the rendered image into an Aspose.Drawing.Bitmap for barcode scanning. - using (var bitmap = new Bitmap(imageStream)) + // Initialize the barcode reader for all supported symbologies + using (BarCodeReader reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes)) { - // Capture memory usage before barcode recognition. - long memoryBefore = Process.GetCurrentProcess().PrivateMemorySize64; - long gcBefore = GC.GetTotalMemory(true); + // Use the highest quality preset to ensure maximum detection + reader.QualitySettings = QualitySettings.MaxQuality; - // Perform barcode recognition on the bitmap using all supported symbologies. - using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes)) + // Iterate over detected barcodes and output their details + foreach (var result in reader.ReadBarCodes()) { - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"Page {pageNumber}: Type = {result.CodeTypeName}, Text = {result.CodeText}"); - } + Console.WriteLine($"Page {pageIndex}: Type={result.CodeTypeName}, Text={result.CodeText}"); } - - // Capture memory usage after barcode recognition. - long memoryAfter = Process.GetCurrentProcess().PrivateMemorySize64; - long gcAfter = GC.GetTotalMemory(true); - - // Calculate deltas to determine memory impact of the recognition step. - long memoryDelta = memoryAfter - memoryBefore; - long gcDelta = gcAfter - gcBefore; - - Console.WriteLine($"Memory used for page {pageNumber}: Process = {memoryDelta} bytes, GC = {gcDelta} bytes"); - totalMemoryUsed += memoryDelta; } } } - - // Output the aggregate memory consumption for all processed pages. - Console.WriteLine($"Total memory consumed for processing {maxPages} page(s): {totalMemoryUsed} bytes"); } } + + // Capture memory usage after processing + long memoryAfter = proc.PrivateMemorySize64; + + // Report memory consumption statistics + Console.WriteLine($"Memory before processing: {memoryBefore / 1024} KB"); + Console.WriteLine($"Memory after processing : {memoryAfter / 1024} KB"); + Console.WriteLine($"Memory increase : {(memoryAfter - memoryBefore) / 1024} KB"); } } \ No newline at end of file diff --git a/barcode-recognition-performance/preprocess-input-images-with-gaussian-blur-removal-before-barcode-detection-to-assess-performance-impact.cs b/barcode-recognition-performance/preprocess-input-images-with-gaussian-blur-removal-before-barcode-detection-to-assess-performance-impact.cs index 9ca6768..5b14db0 100644 --- a/barcode-recognition-performance/preprocess-input-images-with-gaussian-blur-removal-before-barcode-detection-to-assess-performance-impact.cs +++ b/barcode-recognition-performance/preprocess-input-images-with-gaussian-blur-removal-before-barcode-detection-to-assess-performance-impact.cs @@ -1,89 +1,76 @@ -// Title: Barcode detection performance with Gaussian blur removal -// Description: Demonstrates baseline barcode recognition versus recognition with deconvolution (blur removal) to evaluate performance impact. +// Title: Gaussian Blur Removal Before Barcode Detection +// Description: Demonstrates preprocessing of a barcode image with Gaussian blur removal (deconvolution) to evaluate its effect on detection. +// Category-Description: This example belongs to the Aspose.BarCode image preprocessing and recognition category. It shows how to generate a sample barcode, then use BarCodeReader with default settings and with high‑quality deconvolution (Fast mode) to compare detection results. Developers working with barcode scanning often need to improve read rates on blurred images, using classes such as BarcodeGenerator, BarCodeReader, QualitySettings, and DeconvolutionMode. // Prompt: Preprocess input images with Gaussian blur removal before barcode detection to assess performance impact. -// Tags: barcode symbology, deconvolution, performance, aspose.barcode, aspose.drawing +// Tags: barcode symbology, deconvolution, blur removal, image preprocessing, barcode detection, aspose.barcode, code128, qualitysettings using System; -using System.Diagnostics; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Sample program that generates a Code128 barcode, then measures recognition time -/// with and without deconvolution (Gaussian blur removal) to assess performance impact. +/// Example program that generates a Code128 barcode, then reads it using default settings +/// and with Gaussian blur removal (deconvolution) enabled to compare detection results. /// class Program { /// - /// Entry point. Generates a barcode, runs baseline recognition, then runs recognition - /// with deconvolution enabled, printing results and timing information. + /// Entry point of the application. /// static void Main() { - // Generate a sample Code128 barcode and keep it in memory - const string codeText = "1234567890"; - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) - { - // Set a moderate image size for the generated barcode - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; + // Path for the sample barcode image + string barcodePath = "sample_barcode.png"; - // Save the barcode to a memory stream in PNG format - using (MemoryStream barcodeStream = new MemoryStream()) + // Ensure the barcode image exists; generate it if missing + if (!File.Exists(barcodePath)) + { + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - generator.Save(barcodeStream, BarCodeImageFormat.Png); - barcodeStream.Position = 0; - - // Load the barcode image from the stream into a Bitmap object - using (Bitmap barcodeImage = new Bitmap(barcodeStream)) - { - // ------------------------------------------------------------- - // 1. Recognition without any preprocessing (baseline) - // ------------------------------------------------------------- - var stopwatch = Stopwatch.StartNew(); + // Configure basic visual appearance + generator.Parameters.Barcode.XDimension.Point = 2f; + generator.Parameters.Barcode.BarHeight.Point = 40f; + generator.Parameters.Barcode.BarColor = Color.Black; + generator.Parameters.BackColor = Color.White; - // Create a reader for the barcode image using Code128 decoding - using (var reader = new BarCodeReader(barcodeImage, DecodeType.Code128)) - { - // Use default quality settings - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"[Baseline] Detected: {result.CodeTypeName}, Text: {result.CodeText}"); - } - } - - stopwatch.Stop(); - Console.WriteLine($"Baseline recognition time: {stopwatch.ElapsedMilliseconds} ms"); - - // ------------------------------------------------------------- - // 2. Recognition with deconvolution (Gaussian blur removal) - // ------------------------------------------------------------- - // Create a fresh reader instance for the same image - using (var reader = new BarCodeReader(barcodeImage, DecodeType.Code128)) - { - // Enable deconvolution to mitigate blur effects - reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast; - - stopwatch.Restart(); + // Save the generated barcode to a PNG file + generator.Save(barcodePath, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image: {barcodePath}"); + } + } + else + { + Console.WriteLine($"Using existing barcode image: {barcodePath}"); + } - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"[Deconvolution] Detected: {result.CodeTypeName}, Text: {result.CodeText}"); - } + // Local function to read the barcode and output detection results + void ReadAndReport(string description, Action configureReader) + { + // Initialize the reader for all supported barcode types + using (var reader = new BarCodeReader(barcodePath, DecodeType.AllSupportedTypes)) + { + // Apply any custom reader configuration (e.g., deconvolution settings) + configureReader?.Invoke(reader); - stopwatch.Stop(); - Console.WriteLine($"Deconvolution recognition time: {stopwatch.ElapsedMilliseconds} ms"); - } + // Iterate through all detected barcodes and report them + foreach (var result in reader.ReadBarCodes()) + { + Console.WriteLine($"{description} - Detected Type: {result.CodeTypeName}, Text: {result.CodeText}"); } } } - // Note: In a real scenario, you could apply an actual Gaussian blur to the image - // (e.g., using Aspose.Imaging) and then run the same two recognition steps to - // compare performance on blurred vs. deblurred images. + // Read barcode with default settings (no preprocessing) + ReadAndReport("Default Settings", null); + + // Read barcode with deconvolution (blur removal) enabled for high-quality detection + ReadAndReport("Deconvolution (Fast) Enabled", r => + { + r.QualitySettings = QualitySettings.HighQuality; + r.QualitySettings.Deconvolution = DeconvolutionMode.Fast; + }); } } \ No newline at end of file diff --git a/barcode-recognition-performance/process-batch-of-tiff-images-with-varying-contrast-levels-and-record-average-recognition-accuracy.cs b/barcode-recognition-performance/process-batch-of-tiff-images-with-varying-contrast-levels-and-record-average-recognition-accuracy.cs index 76e48b7..7da3bbe 100644 --- a/barcode-recognition-performance/process-batch-of-tiff-images-with-varying-contrast-levels-and-record-average-recognition-accuracy.cs +++ b/barcode-recognition-performance/process-batch-of-tiff-images-with-varying-contrast-levels-and-record-average-recognition-accuracy.cs @@ -1,103 +1,108 @@ -// Title: Batch TIFF Barcode Recognition with Quality Assessment -// Description: Demonstrates processing multiple TIFF images, detecting barcodes of any symbology, and calculating average reading quality per image and overall. +// Title: Process batch of TIFF barcodes and compute average confidence +// Description: Demonstrates generating sample Code128 barcodes as TIFF images, reading them, and calculating the average recognition confidence across the batch. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes, BarCodeReader for decoding, and QualitySettings for performance tuning. Developers often need to process multiple images, adjust image properties, and evaluate recognition reliability, making this pattern useful for batch processing and quality assessment scenarios. // Prompt: Process a batch of TIFF images with varying contrast levels and record average recognition accuracy. -// Tags: barcode, tiff, batch processing, quality, aspose.barcode, recognition +// Tags: barcode, code128, tiff, batch-processing, confidence, generation, recognition, qualitysettings using System; using System.IO; using System.Collections.Generic; -using System.Linq; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Example program that processes a batch of TIFF images, detects barcodes of any supported symbology, -/// and records the average reading quality per image and overall. +/// Example program that generates a set of Code128 barcodes saved as TIFF files, +/// reads them back using Aspose.BarCode, and computes the average confidence of +/// the recognition results. /// class Program { /// - /// Entry point of the application. Scans a folder for TIFF files, reads barcodes using Aspose.BarCode, - /// and reports average reading quality metrics. + /// Entry point of the application. Generates sample barcode images (if missing), + /// processes each TIFF file, extracts confidence values, and prints the average + /// recognition confidence. /// static void Main() { - // Define the folder that contains the TIFF images (adjust the path as needed) - string imagesFolder = "Images"; - - // Verify that the specified folder exists - if (!Directory.Exists(imagesFolder)) + // Define the folder where barcode TIFF images will be stored. + string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(folderPath)) { - Console.WriteLine($"Folder not found: {imagesFolder}"); - return; + // Create the folder when it does not exist. + Directory.CreateDirectory(folderPath); } - // Retrieve up to 5 TIFF files from the folder for safe sample processing - string[] tiffFiles = Directory.GetFiles(imagesFolder, "*.tif") - .Take(5) - .ToArray(); - - // Ensure that at least one TIFF file was found - if (tiffFiles.Length == 0) + // -------------------------------------------------------------------- + // Generate sample barcode images (only if they are not already present) + // -------------------------------------------------------------------- + int sampleCount = 5; + for (int i = 0; i < sampleCount; i++) { - Console.WriteLine("No TIFF files found in the specified folder."); - return; - } + string fileName = $"barcode_{i}.tif"; + string filePath = Path.Combine(folderPath, fileName); + if (!File.Exists(filePath)) + { + // Create a new barcode generator for Code128 with a unique value. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"CODE{i}")) + { + // Set simple black on white colors for high contrast. + generator.Parameters.Barcode.BarColor = Color.Black; + generator.Parameters.BackColor = Color.White; - // List to store the average reading quality for each processed image - var perImageAverages = new List(); + // Save the generated barcode as a TIFF image. + generator.Save(filePath, BarCodeImageFormat.Tiff); + } + } + } - // Process each TIFF file individually - foreach (string filePath in tiffFiles) + // -------------------------------------------------------------- + // Read each TIFF image, decode barcodes, and collect confidence data + // -------------------------------------------------------------- + List confidenceValues = new List(); + string[] tiffFiles = Directory.GetFiles(folderPath, "*.tif"); + foreach (string tiffFile in tiffFiles) { - // Skip the file if it cannot be found (defensive check) - if (!File.Exists(filePath)) + if (!File.Exists(tiffFile)) { - Console.WriteLine($"File not found: {filePath}"); + Console.WriteLine($"File not found: {tiffFile}"); continue; } - // Initialize the barcode reader for the current file, allowing detection of any supported symbology - using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes)) + // Initialize a barcode reader for Code128 barcodes. + using (var reader = new BarCodeReader(tiffFile, DecodeType.Code128)) { - // Apply high‑quality settings to improve detection on low‑contrast images - reader.QualitySettings = QualitySettings.HighQuality; + // Apply a high‑performance quality preset to speed up processing. + reader.QualitySettings = QualitySettings.HighPerformance; - // Perform barcode detection - BarCodeResult[] results = reader.ReadBarCodes(); - - // If no barcodes were detected, report and move to the next image - if (results.Length == 0) + // Iterate over all detected barcodes in the image. + foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($"{Path.GetFileName(filePath)}: No barcodes detected."); - continue; + // BarCodeConfidence enum values can be cast to int (0, 80, 100). + confidenceValues.Add((int)result.Confidence); } - - // Accumulate the reading quality values from all detected barcodes - double sumQuality = 0; - foreach (var result in results) - { - // ReadingQuality is a double representing detection quality (0‑100) - sumQuality += result.ReadingQuality; - } - - // Compute the average reading quality for the current image - double avgQuality = sumQuality / results.Length; - perImageAverages.Add(avgQuality); - - // Output per‑image statistics - Console.WriteLine($"{Path.GetFileName(filePath)}: Detected {results.Length} barcode(s), Average ReadingQuality = {avgQuality:F2}"); } } - // After processing all images, calculate and display the overall average reading quality - if (perImageAverages.Count > 0) + // ------------------------------ + // Compute and display the average + // ------------------------------ + if (confidenceValues.Count > 0) { - double overallAverage = perImageAverages.Average(); - Console.WriteLine($"Overall average ReadingQuality across processed images: {overallAverage:F2}"); + double averageConfidence = 0.0; + foreach (int val in confidenceValues) + { + averageConfidence += val; + } + averageConfidence /= confidenceValues.Count; + + Console.WriteLine($"Processed {confidenceValues.Count} barcode results."); + Console.WriteLine($"Average recognition confidence: {averageConfidence:F2}"); } else { - Console.WriteLine("No barcode data collected to compute overall average."); + Console.WriteLine("No barcode results were found."); } } } \ No newline at end of file diff --git a/barcode-recognition-performance/process-directory-of-bmp-files-using-normalquality-preset-and-record-total-processing-time.cs b/barcode-recognition-performance/process-directory-of-bmp-files-using-normalquality-preset-and-record-total-processing-time.cs index f8fe329..24a12af 100644 --- a/barcode-recognition-performance/process-directory-of-bmp-files-using-normalquality-preset-and-record-total-processing-time.cs +++ b/barcode-recognition-performance/process-directory-of-bmp-files-using-normalquality-preset-and-record-total-processing-time.cs @@ -1,78 +1,76 @@ -// Title: Batch BMP Barcode Processing with Normal Quality -// Description: Processes all BMP images in a directory, reads any barcodes using the NormalQuality preset, and reports total processing time. +// Title: Process BMP Barcodes with NormalQuality Preset +// Description: Demonstrates reading multiple BMP barcode images using the NormalQuality preset and measuring total processing time. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing how to use BarCodeReader with QualitySettings to efficiently decode all supported symbologies from image files. Developers often need to batch‑process images, adjust quality presets, and benchmark performance; this snippet illustrates those common tasks using BarcodeGenerator, BarCodeReader, and QualitySettings classes. // Prompt: Process a directory of BMP files using NormalQuality preset and record total processing time. -// Tags: barcode, batch processing, bmp, normalquality, timing, aspose.barcode +// Tags: barcode symbology, batch processing, performance measurement, normalquality, bmp, aspose.barcode, barcodegenerator, barcodereader, qualitysettings using System; using System.IO; using System.Diagnostics; -using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates how to read barcodes from a collection of BMP files using the NormalQuality preset -/// and measures the total time required for processing. +/// Example program that generates sample BMP barcode images, reads them using the NormalQuality preset, +/// and reports the total processing time. Demonstrates batch processing and performance measurement with Aspose.BarCode. /// class Program { /// - /// Entry point of the application. Accepts an optional directory path argument, - /// processes each BMP file within, and outputs barcode information along with processing duration. + /// Entry point of the application. Generates sample BMP barcodes, reads them, and outputs timing information. /// - /// Command‑line arguments; the first argument may specify the target directory. - static void Main(string[] args) + static void Main() { - // Determine the directory to process. Use argument if provided, otherwise default to "BmpFiles". - string directoryPath = args.Length > 0 ? args[0] : "BmpFiles"; - - // Verify that the directory exists before proceeding. - if (!Directory.Exists(directoryPath)) + // -------------------------------------------------------------------- + // Prepare a temporary folder and generate sample BMP barcode images. + // -------------------------------------------------------------------- + string folderPath = Path.Combine(Path.GetTempPath(), "BarcodesSample"); + if (!Directory.Exists(folderPath)) { - Console.WriteLine($"Directory not found: {directoryPath}"); - return; + Directory.CreateDirectory(folderPath); } - // Retrieve all BMP files in the specified directory (non‑recursive). - string[] bmpFiles = Directory.GetFiles(directoryPath, "*.bmp", SearchOption.TopDirectoryOnly); - if (bmpFiles.Length == 0) + // Generate a few sample Code128 barcodes as BMP files. + for (int i = 1; i <= 5; i++) { - Console.WriteLine("No BMP files found to process."); - return; + string filePath = Path.Combine(folderPath, $"barcode{i}.bmp"); + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i}")) + { + generator.Save(filePath); + } } - // Start measuring total processing time. - Stopwatch stopwatch = new Stopwatch(); - stopwatch.Start(); + // --------------------------------------------------------------- + // Start timing the barcode reading process. + // --------------------------------------------------------------- + var stopwatch = Stopwatch.StartNew(); - // Iterate over each BMP file and attempt to read any barcodes it contains. - foreach (string filePath in bmpFiles) + // Process all BMP files in the folder using NormalQuality preset. + string[] bmpFiles = Directory.GetFiles(folderPath, "*.bmp"); + foreach (string bmpFile in bmpFiles) { - // Defensive check: skip the file if it somehow does not exist. - if (!File.Exists(filePath)) + // Verify that the file exists before attempting to read. + if (!File.Exists(bmpFile)) { - Console.WriteLine($"File not found (skipped): {filePath}"); + Console.WriteLine($"File not found: {bmpFile}"); continue; } - // Initialize a BarCodeReader for the current image, supporting all barcode types. - using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes)) + // Open the image with BarCodeReader and apply the NormalQuality preset. + using (var reader = new BarCodeReader(bmpFile, DecodeType.AllSupportedTypes)) { - // Apply the NormalQuality preset to balance speed and accuracy. reader.QualitySettings = QualitySettings.NormalQuality; - // Read all barcodes present in the image. + // Read all barcodes in the image and output their details. foreach (var result in reader.ReadBarCodes()) { - // Output the file name, detected barcode type, and decoded text. - Console.WriteLine($"File: {Path.GetFileName(filePath)} | Type: {result.CodeTypeName} | Text: {result.CodeText}"); + Console.WriteLine($"File: {Path.GetFileName(bmpFile)} | Type: {result.CodeTypeName} | Text: {result.CodeText}"); } } } - // Stop the timer after all files have been processed. + // Stop the timer and display the total elapsed time. stopwatch.Stop(); - - // Report the total number of processed files and the elapsed time in seconds. - Console.WriteLine($"Processed {bmpFiles.Length} file(s) in {stopwatch.Elapsed.TotalSeconds:F2} seconds."); + Console.WriteLine($"Total processing time: {stopwatch.Elapsed.TotalMilliseconds} ms"); } } \ No newline at end of file diff --git a/barcode-recognition-performance/profile-effect-of-enabling-useminimalxdimension-on-multi-core-cpu-utilization-during-batch-processing.cs b/barcode-recognition-performance/profile-effect-of-enabling-useminimalxdimension-on-multi-core-cpu-utilization-during-batch-processing.cs index 207fba6..2648646 100644 --- a/barcode-recognition-performance/profile-effect-of-enabling-useminimalxdimension-on-multi-core-cpu-utilization-during-batch-processing.cs +++ b/barcode-recognition-performance/profile-effect-of-enabling-useminimalxdimension-on-multi-core-cpu-utilization-during-batch-processing.cs @@ -1,7 +1,8 @@ -// Title: Barcode XDimension Profiling with Multi‑Core Processing -// Description: Demonstrates generating a batch of Code128 barcodes, then measures processing time with and without UseMinimalXDimension enabled to observe CPU utilization. +// Title: Profiling UseMinimalXDimension Impact on Multi‑Core CPU Utilization +// Description: Demonstrates how enabling the UseMinimalXDimension setting affects processing time when reading a batch of Code128 barcodes. +// Category-Description: This example belongs to the Aspose.BarCode performance profiling category, illustrating the use of BarCodeReader.QualitySettings to control X‑dimension detection. Developers often need to benchmark different quality settings to optimize CPU usage during bulk barcode recognition, especially on multi‑core systems. The snippet shows typical usage of BarcodeGenerator for creating test images and BarCodeReader for decoding, helping users compare default and minimal X‑dimension modes. // Prompt: Profile the effect of enabling UseMinimalXDimension on multi‑core CPU utilization during batch processing. -// Tags: barcode, code128, xdimension, multithreading, profiling, aspnet.barcode +// Tags: barcode symbology, performance, code128, png, useminimalxdimension, qualitysettings, multithreading, aspose.barcode using System; using System.Diagnostics; @@ -11,88 +12,111 @@ using Aspose.BarCode.BarCodeRecognition; /// -/// Example program that creates a small batch of Code128 barcodes, -/// then profiles the read performance with default and minimal XDimension settings -/// while utilizing all available processor cores. +/// Example program that generates a set of Code128 barcode images, +/// then measures the processing time of reading them with and without +/// the UseMinimalXDimension quality setting. Useful for profiling +/// CPU utilization on multi‑core machines during batch barcode recognition. /// class Program { + // Number of sample barcode images to generate. + const int SampleCount = 10; + + // Folder where barcode images are saved. + const string OutputFolder = "Barcodes"; + /// - /// Entry point of the application. Generates barcode images, then processes them - /// using two different XDimension configurations while timing each run. + /// Entry point of the application. Creates sample barcodes, + /// runs two profiling scenarios, and outputs the elapsed times + /// along with logical processor count. /// static void Main() { - // Configure barcode reader to use all available CPU cores. - BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Environment.ProcessorCount; - - // Prepare an output folder for the generated barcode images. - string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); - if (!Directory.Exists(outputFolder)) + // Ensure the output directory exists. + if (!Directory.Exists(OutputFolder)) { - Directory.CreateDirectory(outputFolder); + Directory.CreateDirectory(OutputFolder); } - // Generate a small batch of barcode images (5 items). - const int batchSize = 5; - string[] barcodeFiles = new string[batchSize]; - for (int i = 0; i < batchSize; i++) + // Generate a batch of barcode images for the test. + GenerateBarcodes(); + + // Profile processing time using the default XDimension detection. + double timeDefault = ProcessBarcodes(useMinimal: false); + Console.WriteLine($"Processing time (default XDimension): {timeDefault:F2} ms"); + + // Profile processing time with UseMinimalXDimension enabled. + double timeMinimal = ProcessBarcodes(useMinimal: true); + Console.WriteLine($"Processing time (UseMinimalXDimension): {timeMinimal:F2} ms"); + + // Display the number of logical processors available. + Console.WriteLine($"Logical processors: {Environment.ProcessorCount}"); + } + + /// + /// Generates SampleCount PNG images containing Code128 barcodes. + /// Each image uses a consistent XDimension to keep the test conditions uniform. + /// + static void GenerateBarcodes() + { + for (int i = 0; i < SampleCount; i++) { - string codeText = $"CODE{i + 1:D4}"; - string filePath = Path.Combine(outputFolder, $"barcode{i + 1}.png"); + // Create a unique text value for each barcode. + string codeText = $"Sample{i:D2}"; + string filePath = Path.Combine(OutputFolder, $"barcode_{i}.png"); - // Create a barcode generator for Code128 and set optional XDimension. + // Initialize the generator with Code128 symbology. using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - generator.Parameters.Barcode.XDimension.Point = 2f; // optional XDimension setting - generator.Save(filePath); - } + // Set a modest XDimension (2 points) for consistency across samples. + generator.Parameters.Barcode.XDimension.Point = 2f; - barcodeFiles[i] = filePath; + // Save the generated barcode as a PNG file. + generator.Save(filePath, BarCodeImageFormat.Png); + } } - - // Process the batch with the default XDimension mode and record elapsed time. - long defaultTime = ProcessBatch(barcodeFiles, useMinimalXDimension: false); - Console.WriteLine($"Default XDimension mode processing time: {defaultTime} ms"); - - // Process the batch with UseMinimalXDimension mode enabled and record elapsed time. - long minimalTime = ProcessBatch(barcodeFiles, useMinimalXDimension: true); - Console.WriteLine($"UseMinimalXDimension mode processing time: {minimalTime} ms"); } /// - /// Reads a collection of barcode image files, optionally enabling the UseMinimalXDimension mode, - /// and returns the total processing time in milliseconds. + /// Reads all PNG barcode files in OutputFolder and measures the elapsed time. + /// The flag determines whether UseMinimalXDimension + /// is applied to the reader's quality settings. /// - /// Array of file paths to barcode images. - /// If true, enables minimal XDimension mode for reading. - /// Elapsed time in milliseconds for processing the entire batch. - static long ProcessBatch(string[] files, bool useMinimalXDimension) + /// If true, enables minimal XDimension mode; otherwise uses auto detection. + /// Total processing time in milliseconds. + static double ProcessBarcodes(bool useMinimal) { - Stopwatch sw = Stopwatch.StartNew(); + var stopwatch = new Stopwatch(); + stopwatch.Start(); + + // Retrieve all PNG files generated earlier. + string[] files = Directory.GetFiles(OutputFolder, "*.png"); foreach (string file in files) { - // Open a barcode reader for each image file. + // Initialize a reader for each file, targeting Code128 decoding. using (var reader = new BarCodeReader(file, DecodeType.Code128)) { - if (useMinimalXDimension) + // Configure quality settings based on the profiling scenario. + if (useMinimal) { - // Enable UseMinimalXDimension mode and set a minimal XDimension value. reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - reader.QualitySettings.MinimalXDimension = 2f; + reader.QualitySettings.MinimalXDimension = 5f; // pixels + } + else + { + reader.QualitySettings.XDimension = XDimensionMode.Auto; } - // Iterate through all detected barcodes in the image. - foreach (var result in reader.ReadBarCodes()) + // Iterate through all detected barcodes (no further processing needed for profiling). + foreach (BarCodeResult result in reader.ReadBarCodes()) { - // Output detected barcode text (can be suppressed for pure profiling). - Console.WriteLine($"Detected: {result.CodeText}"); + // Intentionally left blank. } } } - sw.Stop(); - return sw.ElapsedMilliseconds; + stopwatch.Stop(); + return stopwatch.Elapsed.TotalMilliseconds; } } \ No newline at end of file diff --git a/barcode-recognition-performance/profile-impact-of-allowincorrectbarcodes-on-overall-cpu-load-during-continuous-scanning.cs b/barcode-recognition-performance/profile-impact-of-allowincorrectbarcodes-on-overall-cpu-load-during-continuous-scanning.cs index b14ec3b..75f6e76 100644 --- a/barcode-recognition-performance/profile-impact-of-allowincorrectbarcodes-on-overall-cpu-load-during-continuous-scanning.cs +++ b/barcode-recognition-performance/profile-impact-of-allowincorrectbarcodes-on-overall-cpu-load-during-continuous-scanning.cs @@ -1,90 +1,77 @@ -// Title: Barcode scanning performance impact of AllowIncorrectBarcodes -// Description: Demonstrates measuring CPU load when toggling AllowIncorrectBarcodes during continuous scanning of a Code128 barcode. +// Title: Profiling CPU impact of AllowIncorrectBarcodes during barcode scanning +// Description: Demonstrates how toggling AllowIncorrectBarcodes affects processing time when repeatedly scanning a Code128 barcode image. +// Category-Description: This example belongs to the Aspose.BarCode scanning performance category, illustrating the use of BarCodeReader, QualitySettings, and DecodeType classes. Developers often need to benchmark barcode recognition settings to optimize CPU usage in high‑throughput applications such as inventory systems or point‑of‑sale terminals. // Prompt: Profile the impact of AllowIncorrectBarcodes on overall CPU load during continuous scanning. -// Tags: barcode symbology, scanning, performance, allowincorrectbarcodes, aspose.barcode +// Tags: barcode, scanning, performance, allowincorrectbarcodes, code128, aspose.barcode, csharp using System; +using System.IO; using System.Diagnostics; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Example program that profiles the CPU impact of the AllowIncorrectBarcodes setting -/// while repeatedly scanning a generated Code128 barcode. +/// Demonstrates profiling the CPU impact of the AllowIncorrectBarcodes setting during continuous barcode scanning. /// class Program { /// - /// Entry point. Generates a barcode, performs warm‑up reads, then measures - /// scanning time with AllowIncorrectBarcodes set to false and true. + /// Entry point. Generates a sample barcode if needed, runs scans with both settings, and outputs timing comparison. /// static void Main() { - // Define the barcode content - const string codeText = "1234567890"; + // Path for the sample barcode image + const string imagePath = "sample_barcode.png"; - // Create a barcode generator for Code128 - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + // Generate a sample barcode image if it does not exist + if (!File.Exists(imagePath)) { - // Set a consistent image size for the generated barcode - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; - - // Generate the barcode image in memory - using (Bitmap barcodeImage = generator.GenerateBarCodeImage()) + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Warm‑up read to eliminate one‑time JIT overhead from measurements - using (var warmReader = new BarCodeReader(barcodeImage, DecodeType.Code128)) - { - warmReader.ReadBarCodes(); - } + generator.Save(imagePath, BarCodeImageFormat.Png); + } + } + + // Number of scans per configuration (small fixed number for CI safety) + const int scanCount = 5; + + // Measure with AllowIncorrectBarcodes = false + TimeSpan timeWithoutAllowIncorrect = ScanAndMeasure(imagePath, false, scanCount); + Console.WriteLine($"AllowIncorrectBarcodes = false : Total time for {scanCount} scans = {timeWithoutAllowIncorrect.TotalMilliseconds} ms"); - // ------------------------------------------------------------ - // Measure scanning time with AllowIncorrectBarcodes = false - // ------------------------------------------------------------ - var swFalse = Stopwatch.StartNew(); - for (int i = 0; i < 5; i++) - { - using (var reader = new BarCodeReader(barcodeImage, DecodeType.Code128)) - { - // Explicitly set the default (false) to ensure consistency - reader.QualitySettings.AllowIncorrectBarcodes = false; + // Measure with AllowIncorrectBarcodes = true + TimeSpan timeWithAllowIncorrect = ScanAndMeasure(imagePath, true, scanCount); + Console.WriteLine($"AllowIncorrectBarcodes = true : Total time for {scanCount} scans = {timeWithAllowIncorrect.TotalMilliseconds} ms"); - // Iterate through all detected barcodes (none are output) - foreach (var result in reader.ReadBarCodes()) - { - // Access CodeText to force full processing - var _ = result.CodeText; - } - } - } - swFalse.Stop(); + // Simple comparison output + double percentChange = (timeWithAllowIncorrect.TotalMilliseconds - timeWithoutAllowIncorrect.TotalMilliseconds) / + timeWithoutAllowIncorrect.TotalMilliseconds * 100.0; + Console.WriteLine($"CPU load impact (approximate): {percentChange:F2}% change when AllowIncorrectBarcodes is enabled."); + } - // ------------------------------------------------------------ - // Measure scanning time with AllowIncorrectBarcodes = true - // ------------------------------------------------------------ - var swTrue = Stopwatch.StartNew(); - for (int i = 0; i < 5; i++) - { - using (var reader = new BarCodeReader(barcodeImage, DecodeType.Code128)) - { - // Enable tolerance for incorrectly formatted barcodes - reader.QualitySettings.AllowIncorrectBarcodes = true; + // Performs a number of scans on the given image with the specified AllowIncorrectBarcodes setting + static TimeSpan ScanAndMeasure(string imagePath, bool allowIncorrect, int iterations) + { + Stopwatch sw = new Stopwatch(); + sw.Start(); - // Iterate through all detected barcodes (none are output) - foreach (var result in reader.ReadBarCodes()) - { - var _ = result.CodeText; - } - } - } - swTrue.Stop(); + for (int i = 0; i < iterations; i++) + { + // Create a new reader for each scan to simulate independent processing + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.Code128)) + { + // Apply the quality setting + reader.QualitySettings.AllowIncorrectBarcodes = allowIncorrect; - // Output the measured elapsed times - Console.WriteLine($"Scanning 5 times with AllowIncorrectBarcodes = false: {swFalse.ElapsedMilliseconds} ms"); - Console.WriteLine($"Scanning 5 times with AllowIncorrectBarcodes = true : {swTrue.ElapsedMilliseconds} ms"); + // Perform the recognition (results are ignored for this profiling) + reader.ReadBarCodes(); } } + + sw.Stop(); + return sw.Elapsed; } } \ No newline at end of file diff --git a/barcode-recognition-performance/profile-impact-of-increasing-minimalxdimension-on-overall-batch-processing-throughput-in-tests.cs b/barcode-recognition-performance/profile-impact-of-increasing-minimalxdimension-on-overall-batch-processing-throughput-in-tests.cs index c86fb45..02ee6c4 100644 --- a/barcode-recognition-performance/profile-impact-of-increasing-minimalxdimension-on-overall-batch-processing-throughput-in-tests.cs +++ b/barcode-recognition-performance/profile-impact-of-increasing-minimalxdimension-on-overall-batch-processing-throughput-in-tests.cs @@ -1,80 +1,85 @@ -// Title: Barcode MinimalXDimension Throughput Profiling -// Description: Demonstrates how varying the MinimalXDimension setting affects the processing time of a batch of Code128 barcodes. +// Title: Impact of MinimalXDimension on Batch Barcode Decoding Throughput +// Description: Demonstrates how varying the MinimalXDimension setting affects the time required to decode a batch of Code128 barcodes. +// Category-Description: This example belongs to the Aspose.BarCode performance profiling category, illustrating the use of BarCodeReader, BarcodeGenerator, and quality settings to measure decoding speed. Developers often need to benchmark different rendering parameters to optimize throughput in high‑volume scanning scenarios. // Prompt: Profile the impact of increasing MinimalXDimension on overall batch processing throughput in tests. -// Tags: barcode, code128, minimalxdimension, performance, profiling, aspose.barcode +// Tags: code128, decoding, performance, minimalxdimension, qualitysettings, barcodegenerator, barcodereader, aspose.barcode using System; using System.Collections.Generic; using System.Diagnostics; -using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Generates a small batch of Code128 barcode images, then measures the -/// recognition time for different MinimalXDimension settings. +/// Shows how changing the MinimalXDimension influences batch processing time when decoding Code128 barcodes. /// class Program { /// - /// Entry point of the application. Creates barcode images, runs recognition - /// with various MinimalXDimension values, and outputs processing times. + /// Generates a small batch of Code128 barcodes, then measures decoding time for several MinimalXDimension values. /// static void Main() { + const int batchSize = 5; // Number of barcodes to generate for the test batch + // ------------------------------------------------------------ - // 1. Prepare a small batch of barcode images (Code128) in memory. + // 1. Generate sample barcode images in memory (Code128) // ------------------------------------------------------------ - const int batchSize = 5; - var barcodeImages = new List(); - + var barcodes = new List(); for (int i = 0; i < batchSize; i++) { - // Generate a barcode with a unique value. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i:D4}")) + string codeText = $"CODE{i:D4}"; + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - // Save the barcode to a memory stream as PNG. - using (var ms = new MemoryStream()) - { - generator.Save(ms, BarCodeImageFormat.Png); - barcodeImages.Add(ms.ToArray()); - } + // Generate a bitmap with default settings + Bitmap bitmap = generator.GenerateBarCodeImage(); + barcodes.Add(bitmap); } } // ------------------------------------------------------------ - // 2. Define MinimalXDimension values to test. + // 2. Define MinimalXDimension values to evaluate // ------------------------------------------------------------ - float[] minimalValues = new float[] { 1f, 2f, 4f, 8f }; + float[] minimalXDimensions = new float[] { 1f, 2f, 4f, 8f }; // ------------------------------------------------------------ - // 3. Measure recognition time for each MinimalXDimension setting. + // 3. Process the batch for each MinimalXDimension setting // ------------------------------------------------------------ - foreach (float minX in minimalValues) + foreach (float minX in minimalXDimensions) { - var stopwatch = Stopwatch.StartNew(); + var stopwatch = Stopwatch.StartNew(); // Start timing for current setting - // Process each barcode image in the batch. - foreach (byte[] imgData in barcodeImages) + // Decode each barcode image using the current MinimalXDimension + foreach (var image in barcodes) { - using (var ms = new MemoryStream(imgData)) + using (var reader = new BarCodeReader(image, DecodeType.Code128)) { - // Initialize the reader for all supported barcode types. - using (var reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes)) - { - // Configure recognition to use the MinimalXDimension mode. - reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - reader.QualitySettings.MinimalXDimension = minX; + // Apply quality settings: use MinimalXDimension mode with the specified value + reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; + reader.QualitySettings.MinimalXDimension = minX; - // Perform recognition (results are not used further in this demo). - var results = reader.ReadBarCodes(); + // Trigger the decoding process; results are not needed for this benchmark + foreach (var result in reader.ReadBarCodes()) + { + // No action required; iteration ensures processing occurs } } } - stopwatch.Stop(); - Console.WriteLine($"MinimalXDimension = {minX} → processing time: {stopwatch.ElapsedMilliseconds} ms for {batchSize} barcodes."); + stopwatch.Stop(); // Stop timing + + // Output the elapsed time for the current MinimalXDimension + Console.WriteLine($"MinimalXDimension = {minX} px, Processing Time = {stopwatch.ElapsedMilliseconds} ms"); + } + + // ------------------------------------------------------------ + // 4. Clean up generated bitmap resources + // ------------------------------------------------------------ + foreach (var bmp in barcodes) + { + bmp.Dispose(); } } } \ No newline at end of file diff --git a/barcode-recognition-performance/profile-impact-of-large-image-dimensions-eg-4000x4000-on-recognition-time-with-highperformance-preset.cs b/barcode-recognition-performance/profile-impact-of-large-image-dimensions-eg-4000x4000-on-recognition-time-with-highperformance-preset.cs index 010de3f..2c86fa6 100644 --- a/barcode-recognition-performance/profile-impact-of-large-image-dimensions-eg-4000x4000-on-recognition-time-with-highperformance-preset.cs +++ b/barcode-recognition-performance/profile-impact-of-large-image-dimensions-eg-4000x4000-on-recognition-time-with-highperformance-preset.cs @@ -1,75 +1,121 @@ -// Title: Barcode Recognition Performance on Large Images -// Description: Demonstrates generating a QR code, embedding it into a large 4000x4000 bitmap, and measuring recognition time using the HighPerformance preset. +// Title: Barcode recognition performance profiling with large images +// Description: Demonstrates how image size (4000x4000) affects barcode recognition time using the HighPerformance preset. +// Category-Description: This example belongs to the Aspose.BarCode recognition performance category. It shows how to generate a barcode, embed it in a large image, and measure decoding speed using BarCodeReader with QualitySettings.HighPerformance. Developers often need to evaluate processing time for high‑resolution scans in industrial or retail scenarios, and this snippet illustrates typical API usage such as BarcodeGenerator, BarCodeReader, and QualitySettings. // Prompt: Profile the impact of large image dimensions (e.g., 4000x4000) on recognition time with HighPerformance preset. -// Tags: qr, barcode, recognition, performance, highperformance, aspose.barcode, image processing +// Tags: barcode, performance, highresolution, highperformance, code128, png, aspose.barcode, generation, recognition using System; using System.Diagnostics; +using System.IO; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Example program that creates a QR barcode, places it on a large bitmap, -/// and profiles the recognition time using the HighPerformance quality preset. +/// Example program that creates a small barcode, places it on a large 4000x4000 image, +/// and measures the recognition time using the HighPerformance quality preset. /// class Program { /// - /// Entry point of the application. - /// Generates a QR barcode, draws it onto a 4000x4000 image, - /// and measures how long recognition takes with HighPerformance settings. + /// Entry point. Generates images, runs recognition, and outputs timing results. /// static void Main() { - // Generate a simple QR barcode image in memory - using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Sample Text")) + // Define temporary file paths + string smallImagePath = "smallBarcode.png"; + string largeImagePath = "largeBarcode.png"; + + // ------------------------------------------------------------ + // Generate a small barcode image (Code128) and save as PNG + // ------------------------------------------------------------ + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123")) + { + generator.Save(smallImagePath, BarCodeImageFormat.Png); + } + + // Verify the small barcode image was created + if (!File.Exists(smallImagePath)) { - using (Image barcodeImage = generator.GenerateBarCodeImage()) + Console.WriteLine("Failed to create small barcode image."); + return; + } + + // ------------------------------------------------------------ + // Load the small barcode and embed it into a large blank bitmap + // ------------------------------------------------------------ + using (var smallBmp = new Bitmap(smallImagePath)) + { + // Create a large white bitmap (4000x4000) with 24‑bpp RGB format + using (var largeBmp = new Bitmap(4000, 4000, PixelFormat.Format24bppRgb)) { - // Create a large bitmap (e.g., 4000x4000) and draw the barcode onto it - const int largeSize = 4000; - using (var largeBitmap = new Bitmap(largeSize, largeSize)) + using (var graphics = Graphics.FromImage(largeBmp)) { - // Prepare graphics object for drawing - using (var graphics = Graphics.FromImage(largeBitmap)) - { - // Fill background with white - graphics.Clear(Color.White); - - // Center the barcode image on the large bitmap - int x = (largeSize - barcodeImage.Width) / 2; - int y = (largeSize - barcodeImage.Height) / 2; - graphics.DrawImage(barcodeImage, x, y, barcodeImage.Width, barcodeImage.Height); - } - - // Measure recognition time using HighPerformance preset - using (var reader = new BarCodeReader(largeBitmap, DecodeType.AllSupportedTypes)) - { - // Apply HighPerformance quality settings - reader.QualitySettings = QualitySettings.HighPerformance; - - // Start timing - var stopwatch = Stopwatch.StartNew(); - - // Perform barcode recognition - BarCodeResult[] results = reader.ReadBarCodes(); - - // Stop timing - stopwatch.Stop(); - - // Output recognition duration - Console.WriteLine($"Recognition time (HighPerformance) on {largeSize}x{largeSize} image: {stopwatch.ElapsedMilliseconds} ms"); - - // List detected barcodes - foreach (var result in results) - { - Console.WriteLine($"Detected: Type={result.CodeTypeName}, Text={result.CodeText}"); - } - } + // Fill background with white + graphics.Clear(Color.White); + + // Calculate offsets to center the small barcode + int offsetX = (largeBmp.Width - smallBmp.Width) / 2; + int offsetY = (largeBmp.Height - smallBmp.Height) / 2; + + // Draw the small barcode onto the large image + graphics.DrawImage(smallBmp, offsetX, offsetY); } + + // Save the composite large image as PNG + largeBmp.Save(largeImagePath, ImageFormat.Png); } } + + // Verify the large image was saved successfully + if (!File.Exists(largeImagePath)) + { + Console.WriteLine("Failed to create large barcode image."); + return; + } + + // ------------------------------------------------------------ + // Measure barcode recognition time using HighPerformance preset + // ------------------------------------------------------------ + using (var reader = new BarCodeReader(largeImagePath, DecodeType.AllSupportedTypes)) + { + // Apply the HighPerformance quality setting for faster decoding + reader.QualitySettings = QualitySettings.HighPerformance; + + // Optional timeout to prevent hangs on problematic images (10 seconds) + reader.Timeout = 10000; + + // Start timing + var stopwatch = Stopwatch.StartNew(); + + // Perform barcode detection + var results = reader.ReadBarCodes(); + + // Stop timing + stopwatch.Stop(); + + // Output elapsed time + Console.WriteLine($"Recognition time (HighPerformance): {stopwatch.ElapsedMilliseconds} ms"); + + // Report detection results + if (results.Length == 0) + { + Console.WriteLine("No barcodes detected."); + } + else + { + foreach (var result in results) + { + Console.WriteLine($"Detected Type: {result.CodeTypeName}, Text: {result.CodeText}"); + } + } + } + + // ------------------------------------------------------------ + // Clean up temporary files (optional) + // ------------------------------------------------------------ + try { File.Delete(smallImagePath); } catch { } + try { File.Delete(largeImagePath); } catch { } } } \ No newline at end of file diff --git a/barcode-recognition-performance/record-number-of-barcodes-detected-per-image-under-each-preset-to-analyze-consistency.cs b/barcode-recognition-performance/record-number-of-barcodes-detected-per-image-under-each-preset-to-analyze-consistency.cs index a316155..9d2019f 100644 --- a/barcode-recognition-performance/record-number-of-barcodes-detected-per-image-under-each-preset-to-analyze-consistency.cs +++ b/barcode-recognition-performance/record-number-of-barcodes-detected-per-image-under-each-preset-to-analyze-consistency.cs @@ -1,143 +1,91 @@ -// Title: Barcode detection count per image across quality presets -// Description: Demonstrates generating sample barcodes, then measuring how many barcodes each image yields under different QualitySettings presets to assess detection consistency. +// Title: Barcode Generation and Detection with Preset Decoding Types +// Description: Generates sample barcode images and detects them using various decoding presets, reporting the count of barcodes found per image. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It demonstrates how to use BarcodeGenerator to create images, and BarCodeReader with different BaseDecodeType presets to recognize barcodes. Typical use cases include batch processing of scanned documents, quality‑control of barcode printing, and consistency analysis across different symbologies. Developers often need to switch between preset decode sets to optimize performance or focus on specific barcode types. // Prompt: Record the number of barcodes detected per image under each preset to analyze consistency. -// Tags: barcode symbology, detection, qualitysettings, output, aspose.barcode +// Tags: barcode symbology, generation, detection, preset, aspose.barcode, png, console using System; -using System.Collections.Generic; using System.IO; +using System.Collections.Generic; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Demonstrates generating sample barcode images and recording detection counts per image under various presets. +/// Demonstrates creating barcode images and counting detected barcodes per image using different decoding presets. /// class Program { /// - /// Returns the preset that matches the supplied name. - /// - /// Name of the preset (e.g., "HighPerformance"). - /// The corresponding value. - static QualitySettings GetPreset(string name) - { - return name switch - { - "HighPerformance" => QualitySettings.HighPerformance, - "NormalQuality" => QualitySettings.NormalQuality, - "HighQuality" => QualitySettings.HighQuality, - "MaxQuality" => QualitySettings.MaxQuality, - _ => QualitySettings.NormalQuality, - }; - } - - /// - /// Entry point. Generates barcodes, runs detection with each preset, and prints a table of counts. + /// Entry point. Generates sample barcodes, then reads each image with several decode presets and prints detection counts. /// static void Main() { // -------------------------------------------------------------------- - // Prepare a temporary folder for sample barcode images. + // Prepare output folder for generated barcode images // -------------------------------------------------------------------- - string tempFolder = Path.Combine(Path.GetTempPath(), "BarcodeDemo"); - if (!Directory.Exists(tempFolder)) - Directory.CreateDirectory(tempFolder); + string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(folderPath)) + { + Directory.CreateDirectory(folderPath); + } // -------------------------------------------------------------------- - // Define a list of sample barcodes to generate. + // Define sample barcodes to generate (file name, symbology, data) // -------------------------------------------------------------------- - var samples = new List<(BaseEncodeType type, string text, string fileName)> + var samples = new List<(string FileName, BaseEncodeType EncodeType, string CodeText)> { - (EncodeTypes.Code128, "1234567890", "code128.png"), - (EncodeTypes.QR, "https://example.com", "qr.png"), - (EncodeTypes.DataMatrix, "DM12345", "datamatrix.png") + ("code128.png", EncodeTypes.Code128, "ABC123456"), + ("qr.png", EncodeTypes.QR, "https://example.com"), + ("datamatrix.png", EncodeTypes.DataMatrix, "DataMatrixSample") }; // -------------------------------------------------------------------- - // Generate sample images and save them as PNG files. + // Generate barcode images using default settings and save as PNG // -------------------------------------------------------------------- - foreach (var (type, text, fileName) in samples) + foreach (var sample in samples) { - string filePath = Path.Combine(tempFolder, fileName); - using (var generator = new BarcodeGenerator(type, text)) + string filePath = Path.Combine(folderPath, sample.FileName); + using (var generator = new BarcodeGenerator(sample.EncodeType, sample.CodeText)) { - generator.Save(filePath); // defaults to PNG + generator.Save(filePath, BarCodeImageFormat.Png); } } // -------------------------------------------------------------------- - // Define the QualitySettings preset names to evaluate. - // -------------------------------------------------------------------- - string[] presetNames = { "HighPerformance", "NormalQuality", "HighQuality", "MaxQuality" }; - - // -------------------------------------------------------------------- - // Collect all generated PNG image files. - // -------------------------------------------------------------------- - string[] imageFiles = Directory.GetFiles(tempFolder, "*.png"); - - // -------------------------------------------------------------------- - // Dictionary to hold results: preset -> (image file -> count). + // Define decoding presets (each preset contains a set of BaseDecodeType values) // -------------------------------------------------------------------- - var results = new Dictionary>(); + var presets = new List<(string Name, BaseDecodeType[] DecodeTypes)> + { + ("AllSupportedTypes", new BaseDecodeType[] { DecodeType.AllSupportedTypes }), + ("Code128Only", new BaseDecodeType[] { DecodeType.Code128 }), + ("QROnly", new BaseDecodeType[] { DecodeType.QR }), + ("DataMatrixOnly", new BaseDecodeType[] { DecodeType.DataMatrix }) + }; // -------------------------------------------------------------------- - // Iterate over each preset and count detected barcodes per image. + // Process each preset and each generated image, counting detected barcodes // -------------------------------------------------------------------- - foreach (string preset in presetNames) + foreach (var preset in presets) { - var perImage = new Dictionary(); - QualitySettings qs = GetPreset(preset); - - foreach (string imagePath in imageFiles) + Console.WriteLine($"Preset: {preset.Name}"); + foreach (var sample in samples) { + string imagePath = Path.Combine(folderPath, sample.FileName); if (!File.Exists(imagePath)) { - Console.WriteLine($"Warning: file not found {imagePath}"); - perImage[Path.GetFileName(imagePath)] = 0; + Console.WriteLine($" Image not found: {sample.FileName}"); continue; } - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + using (var reader = new BarCodeReader(imagePath, preset.DecodeTypes)) { - reader.QualitySettings = qs; - BarCodeResult[] detected = reader.ReadBarCodes(); - int count = detected?.Length ?? 0; - perImage[Path.GetFileName(imagePath)] = count; + var results = reader.ReadBarCodes(); + int count = results?.Length ?? 0; + Console.WriteLine($" Image: {sample.FileName} - Detected Barcodes: {count}"); } } - - results[preset] = perImage; - } - - // -------------------------------------------------------------------- - // Output the counts in a tabular format. - // -------------------------------------------------------------------- - Console.WriteLine("Barcode detection counts per image under each preset:"); - Console.WriteLine(); - - // Header row - Console.Write("Image\\Preset".PadRight(20)); - foreach (string preset in presetNames) - Console.Write(preset.PadRight(15)); - Console.WriteLine(); - - // Data rows per image - foreach (string imageFile in imageFiles) - { - string fileName = Path.GetFileName(imageFile); - Console.Write(fileName.PadRight(20)); - foreach (string preset in presetNames) - { - int count = results[preset].ContainsKey(fileName) ? results[preset][fileName] : 0; - Console.Write(count.ToString().PadRight(15)); - } - Console.WriteLine(); } - - // -------------------------------------------------------------------- - // Cleanup (optional). Uncomment to delete the temporary folder. - // -------------------------------------------------------------------- - // Directory.Delete(tempFolder, true); } } \ No newline at end of file diff --git a/barcode-recognition-performance/record-number-of-false-positives-encountered-when-minimalxdimension-is-set-too-low.cs b/barcode-recognition-performance/record-number-of-false-positives-encountered-when-minimalxdimension-is-set-too-low.cs index a2da326..2974736 100644 --- a/barcode-recognition-performance/record-number-of-false-positives-encountered-when-minimalxdimension-is-set-too-low.cs +++ b/barcode-recognition-performance/record-number-of-false-positives-encountered-when-minimalxdimension-is-set-too-low.cs @@ -1,76 +1,85 @@ -// Title: Barcode false positive detection with low MinimalXDimension -// Description: Demonstrates how setting MinimalXDimension too low can cause the reader to report barcodes on a blank image, counting false positives. +// Title: Minimal XDimension false positive detection example +// Description: Demonstrates how setting MinimalXDimension too low can cause false positives during barcode recognition. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, illustrating the use of BarcodeGenerator, BarCodeReader, and QualitySettings to explore the impact of XDimension settings on decoding accuracy. Developers often need to fine‑tune module size and quality parameters to avoid misreads in high‑throughput scanning scenarios. // Prompt: Record the number of false positives encountered when MinimalXDimension is set too low. -// Tags: barcode, false-positive, minimalxdimension, code128, aspose.barcode, image-processing +// Tags: barcode symbology, generation, recognition, minimalxdimension, false positives, code128, png using System; using System.IO; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; -using Aspose.Drawing.Imaging; /// -/// Example program that generates a barcode, creates a blank image of the same size, -/// and measures false positives when the MinimalXDimension quality setting is set too low. +/// Generates a set of Code128 barcodes with an intentionally low XDimension, +/// then reads them back with MinimalXDimension set unrealistically low to +/// count any false positive detections. /// class Program { /// - /// Entry point. Generates a barcode, prepares a blank image, and counts false positives - /// produced by the barcode reader under deliberately poor MinimalXDimension settings. + /// Entry point of the example. Creates barcodes, reads them, and reports false positives. /// static void Main() { - // Generate a simple Code128 barcode image and keep it in memory. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + // Sample data and output configuration + string codeText = "1234567890"; + int sampleCount = 5; + string outputFolder = "Barcodes"; + + // Ensure the output directory exists + Directory.CreateDirectory(outputFolder); + + // -------------------------------------------------------------------- + // Generate barcodes with a very low XDimension (module size) + // -------------------------------------------------------------------- + for (int i = 0; i < sampleCount; i++) { - using (var barcodeImage = generator.GenerateBarCodeImage()) - { - // Save the barcode image to a memory stream for later reuse. - using (var barcodeStream = new MemoryStream()) - { - barcodeImage.Save(barcodeStream, ImageFormat.Png); - barcodeStream.Position = 0; + string filePath = Path.Combine(outputFolder, $"barcode_{i}.png"); - // Create a blank (white) image of the same dimensions – this image contains no barcode. - using (var blankImage = new Bitmap(barcodeImage.Width, barcodeImage.Height)) - { - using (var graphics = Graphics.FromImage(blankImage)) - { - graphics.Clear(Aspose.Drawing.Color.White); - } + // Create a barcode generator for Code128 + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + { + // Set XDimension to a low value (0.5 point) to simulate a small module size + generator.Parameters.Barcode.XDimension.Point = 0.5f; - int falsePositiveCount = 0; - const int attempts = 5; // small safe sample size + // Save the generated barcode as PNG + generator.Save(filePath, BarCodeImageFormat.Png); + } + } - // Perform multiple recognition attempts on the blank image. - for (int i = 0; i < attempts; i++) - { - // Use the same blank image for each attempt. - using (var reader = new BarCodeReader(blankImage, DecodeType.AllSupportedTypes)) - { - // Set MinimalXDimension deliberately low to provoke false positives. - reader.QualitySettings.MinimalXDimension = 0.1f; // too low + int falsePositiveCount = 0; - // Optionally allow recognition of incorrect barcodes. - reader.QualitySettings.AllowIncorrectBarcodes = true; + // -------------------------------------------------------------------- + // Read the generated images with MinimalXDimension set too low + // -------------------------------------------------------------------- + for (int i = 0; i < sampleCount; i++) + { + string filePath = Path.Combine(outputFolder, $"barcode_{i}.png"); - // Perform recognition. - var results = reader.ReadBarCodes(); + // Skip if the file was not created for any reason + if (!File.Exists(filePath)) + continue; - // If any barcode is reported, count it as a false positive. - if (results != null && results.Length > 0) - { - falsePositiveCount++; - } - } - } + // Initialize a barcode reader for Code128 + using (var reader = new BarCodeReader(filePath, DecodeType.Code128)) + { + // Set MinimalXDimension to an unrealistically low value to provoke false positives + reader.QualitySettings.MinimalXDimension = 0.1f; - Console.WriteLine($"False positives detected with MinimalXDimension set too low: {falsePositiveCount}"); + // Iterate over all detected barcodes in the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Count as false positive if the decoded text does not match the original + if (!string.Equals(result.CodeText, codeText, StringComparison.Ordinal)) + { + falsePositiveCount++; } } } } + + // Output the total number of false positives detected + Console.WriteLine($"Number of false positives detected: {falsePositiveCount}"); } } \ No newline at end of file diff --git a/barcode-recognition-performance/record-percentage-of-barcodes-successfully-decoded-under-each-preset-across-mixed-type-dataset.cs b/barcode-recognition-performance/record-percentage-of-barcodes-successfully-decoded-under-each-preset-across-mixed-type-dataset.cs index 811fd5f..3e7922f 100644 --- a/barcode-recognition-performance/record-percentage-of-barcodes-successfully-decoded-under-each-preset-across-mixed-type-dataset.cs +++ b/barcode-recognition-performance/record-percentage-of-barcodes-successfully-decoded-under-each-preset-across-mixed-type-dataset.cs @@ -1,7 +1,8 @@ -// Title: Barcode decoding success rate per quality preset -// Description: Demonstrates generating a mixed‑type barcode set, decoding them with different quality presets, and reporting the success percentage for each preset. +// Title: Barcode generation and decoding success rate per symbology preset +// Description: This example generates a set of barcodes for several symbologies, decodes them, and reports the percentage of successful decodings. +// Category-Description: Demonstrates Aspose.BarCode generation and recognition APIs, covering BarcodeGenerator, BarCodeReader, and related parameter settings. Useful for developers testing barcode quality, batch processing, or evaluating decoding reliability across different symbologies. // Prompt: Record the percentage of barcodes successfully decoded under each preset across a mixed‑type dataset. -// Tags: barcode, decoding, qualitysettings, aspose.barcode, csharp, example +// Tags: barcode symbology, generation, recognition, png, aspose.barcode, encode type, decode type using System; using System.Collections.Generic; @@ -9,96 +10,122 @@ using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Demonstrates generating barcodes of various symbologies, decoding them using different -/// quality presets, and reporting the success rate for each preset. +/// Demonstrates generating barcodes for multiple symbologies, decoding them, and reporting success percentages. /// class Program { + // Simple data holder for each preset (symbology) + class PresetInfo + { + public string Name { get; set; } + public BaseEncodeType EncodeType { get; set; } + public List Files { get; } = new List(); + public List ExpectedTexts { get; } = new List(); + } + /// - /// Entry point. Generates barcodes, decodes them with each preset, and prints success percentages. + /// Entry point. Generates barcodes, decodes them, and prints success rates per preset. /// static void Main() { - // Create output directory for generated barcode images - string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); - if (!Directory.Exists(outputDir)) - { - Directory.CreateDirectory(outputDir); - } + // Folder to store generated barcode images + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); - // Define a small mixed‑type dataset (symbology + sample text + file name) - var samples = new List<(BaseEncodeType type, string text, string fileName)> + // Define a few presets (symbologies) with sample texts + var presets = new List { - (EncodeTypes.Code128, "ABC12345", "code128.png"), - (EncodeTypes.QR, "https://example.com", "qr.png"), - (EncodeTypes.DataMatrix, "DM123", "datamatrix.png"), - (EncodeTypes.Pdf417, "PDF417_SAMPLE_TEXT", "pdf417.png"), - (EncodeTypes.DatabarStacked, "(01)01234567890128", "databar.png") + new PresetInfo + { + Name = "Code128", + EncodeType = EncodeTypes.Code128 + }, + new PresetInfo + { + Name = "QR", + EncodeType = EncodeTypes.QR + }, + new PresetInfo + { + Name = "DataMatrix", + EncodeType = EncodeTypes.DataMatrix + } }; - // Generate barcode images for each sample - foreach (var (type, text, fileName) in samples) + // Number of samples per preset (kept small for CI safety) + const int samplesPerPreset = 5; + + // Generate sample barcodes for each preset + foreach (var preset in presets) { - string filePath = Path.Combine(outputDir, fileName); - using (var generator = new BarcodeGenerator(type, text)) + for (int i = 0; i < samplesPerPreset; i++) { - generator.Save(filePath); + string codeText = $"{preset.Name}_Sample_{i + 1}"; + string filePath = Path.Combine(outputFolder, $"{preset.Name}_{i + 1}.png"); + + using (var generator = new BarcodeGenerator(preset.EncodeType, codeText)) + { + // Example of setting a simple parameter (optional) + generator.Parameters.Barcode.XDimension.Point = 2f; + generator.Save(filePath, BarCodeImageFormat.Png); + } + + // Store generated file path and expected text for later verification + preset.Files.Add(filePath); + preset.ExpectedTexts.Add(codeText); } } - // Define decoding presets (different QualitySettings) - var presets = new List<(string name, QualitySettings settings)> - { - ("HighPerformance", QualitySettings.HighPerformance), - ("HighQuality", QualitySettings.HighQuality), - ("NormalQuality", QualitySettings.NormalQuality), - ("MaxQuality", QualitySettings.MaxQuality) - }; + // Prepare results container: key = preset name, value = (total count, successful decodes) + var results = new Dictionary(); - // Evaluate each preset by decoding all generated barcodes - foreach (var (presetName, presetSettings) in presets) + // Decode each generated image and evaluate success per preset + foreach (var preset in presets) { - int total = samples.Count; + int total = preset.Files.Count; int success = 0; - foreach (var (type, expectedText, fileName) in samples) + for (int i = 0; i < total; i++) { - string filePath = Path.Combine(outputDir, fileName); - if (!File.Exists(filePath)) + string file = preset.Files[i]; + string expected = preset.ExpectedTexts[i]; + + if (!File.Exists(file)) { - Console.WriteLine($"Warning: file not found {filePath}"); + Console.WriteLine($"Warning: File not found '{file}'. Skipping."); continue; } - using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes)) + using (var reader = new BarCodeReader(file, DecodeType.AllSupportedTypes)) { - // Apply the current quality preset - reader.QualitySettings = presetSettings; - - // Read barcodes from the image - var results = reader.ReadBarCodes(); - - // Check if any result matches the expected text - foreach (var result in results) + // Read all barcodes in the image (there should be only one) + foreach (var result in reader.ReadBarCodes()) { - if (!string.IsNullOrEmpty(result.CodeText) && result.CodeText == expectedText) + // Consider it a success if a code text is returned and matches the expected value + if (!string.IsNullOrEmpty(result.CodeText) && result.CodeText == expected) { success++; - break; } + break; // only first result needed } } } - // Calculate and display success percentage for the current preset - double percentage = (double)success / total * 100.0; - Console.WriteLine($"{presetName}: {percentage:F2}% ({success}/{total}) barcodes decoded successfully."); + results[preset.Name] = (total, success); } - // Cleanup: optional removal of generated files - // foreach (var file in Directory.GetFiles(outputDir)) File.Delete(file); - // Directory.Delete(outputDir); + // Output percentage of successful decodings per preset + Console.WriteLine("Decoding success percentages per preset:"); + foreach (var kvp in results) + { + string name = kvp.Key; + int total = kvp.Value.total; + int success = kvp.Value.success; + double percentage = total > 0 ? (double)success / total * 100.0 : 0.0; + Console.WriteLine($"{name}: {percentage:F2}% ({success}/{total})"); + } } } \ No newline at end of file diff --git a/barcode-recognition-performance/retrieve-barcoderesultconfidence-after-allowing-incorrect-barcodes-to-assess-detection-reliability.cs b/barcode-recognition-performance/retrieve-barcoderesultconfidence-after-allowing-incorrect-barcodes-to-assess-detection-reliability.cs index f7bd32e..698b7c6 100644 --- a/barcode-recognition-performance/retrieve-barcoderesultconfidence-after-allowing-incorrect-barcodes-to-assess-detection-reliability.cs +++ b/barcode-recognition-performance/retrieve-barcoderesultconfidence-after-allowing-incorrect-barcodes-to-assess-detection-reliability.cs @@ -1,56 +1,56 @@ -// Title: Barcode Generation and Confidence Retrieval -// Description: Generates a Code128 barcode, saves it, then reads it allowing incorrect barcodes and outputs the detection confidence for each result. +// Title: Retrieve barcode confidence after allowing incorrect barcodes +// Description: Demonstrates how to generate a Code128 barcode, read it with the MaxQuality setting that permits incorrect barcodes, and obtain the detection confidence value. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating the use of BarCodeReader with QualitySettings to assess detection reliability. It showcases key API classes such as BarcodeGenerator, BarCodeReader, BarCodeResult, and QualitySettings, which developers commonly use for generating barcodes, customizing reading parameters, and evaluating confidence scores in scanning applications. // Prompt: Retrieve BarCodeResult.Confidence after allowing incorrect barcodes to assess detection reliability. -// Tags: code128, generation, recognition, confidence, allowincorrectbarcodes, aspose.barcode +// Tags: barcode, code128, confidence, allowincorrectbarcodes, qualitysettings, generation, recognition using System; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates creating a barcode, saving it to an image file, and then reading it back -/// while allowing detection of incorrect barcodes. The confidence level of each detection -/// is displayed to assess reliability. +/// Example program that generates a Code128 barcode, reads it with settings that allow incorrect barcodes, +/// and outputs the detection confidence and reading quality. /// class Program { /// - /// Entry point of the example. Generates a barcode, verifies its creation, - /// reads it with relaxed validation, and prints the code text and confidence. + /// Entry point of the example. Generates a barcode, verifies its creation, reads it with MaxQuality settings, + /// and prints the barcode text, confidence, and reading quality. /// static void Main() { - // Define the path for the generated barcode image - string imagePath = "barcode.png"; + // Path where the generated barcode image will be saved + string barcodePath = "barcode.png"; - // Create a simple Code128 barcode and save it to a file - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "12345")) + // Generate a simple Code128 barcode and save it to the specified file + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "12345")) { - generator.Save(imagePath); + generator.Save(barcodePath); } - // Verify that the image file was created - if (!File.Exists(imagePath)) + // Verify that the barcode image was successfully created + if (!File.Exists(barcodePath)) { - Console.WriteLine("Failed to create barcode image."); + Console.WriteLine($"Error: Barcode file '{barcodePath}' was not found."); return; } - // Initialize a barcode reader for the saved image, specifying Code128 symbology - using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + // Initialize a barcode reader for the generated image, targeting Code128 symbology + using (BarCodeReader reader = new BarCodeReader(barcodePath, DecodeType.Code128)) { - // Enable detection of incorrect barcodes (e.g., damaged or with wrong checksum) - reader.QualitySettings.AllowIncorrectBarcodes = true; + // Apply the MaxQuality preset, which enables AllowIncorrectBarcodes among other high‑quality settings + reader.QualitySettings = QualitySettings.MaxQuality; - // Perform recognition and retrieve all detected barcode results - BarCodeResult[] results = reader.ReadBarCodes(); - - // Output confidence and code text for each detected barcode - foreach (var result in results) + // Iterate over all detected barcodes (expected to be a single entry) + foreach (BarCodeResult result in reader.ReadBarCodes()) { - Console.WriteLine($"CodeText: {result.CodeText}"); - Console.WriteLine($"Confidence: {result.Confidence}"); + // Output the decoded text, confidence level, and reading quality for each result + Console.WriteLine($"Detected CodeText: {result.CodeText}"); + Console.WriteLine($"Confidence Level: {result.Confidence}"); + Console.WriteLine($"Reading Quality: {result.ReadingQuality}"); } } } diff --git a/barcode-recognition-performance/run-recognition-on-low-light-jpeg-images-after-applying-histogram-equalization-and-record-improvement.cs b/barcode-recognition-performance/run-recognition-on-low-light-jpeg-images-after-applying-histogram-equalization-and-record-improvement.cs index a2373ef..260fdc8 100644 --- a/barcode-recognition-performance/run-recognition-on-low-light-jpeg-images-after-applying-histogram-equalization-and-record-improvement.cs +++ b/barcode-recognition-performance/run-recognition-on-low-light-jpeg-images-after-applying-histogram-equalization-and-record-improvement.cs @@ -1,148 +1,104 @@ -// Title: Barcode recognition improvement with histogram equalization on low‑light JPEGs -// Description: Demonstrates loading low‑light JPEG images, applying histogram equalization, and comparing barcode detection counts before and after processing. +// Title: Barcode recognition on low‑light JPEG with histogram equalization +// Description: Demonstrates reading barcodes from a low‑light JPEG image, applying histogram equalization (simulated), and comparing detection confidence. +// Category-Description: This example belongs to the Aspose.BarCode image preprocessing and recognition category. It shows how to use BarCodeReader with high‑quality settings, work with Aspose.Drawing Bitmap objects, and handle multiple symbologies such as Code39, Code128, and QR. Developers often need to improve barcode detection in poor lighting conditions by preprocessing images before recognition. // Prompt: Run recognition on low‑light JPEG images after applying histogram equalization and record improvement. -// Tags: barcode, recognition, histogram equalization, low-light, jpeg, aspose.barcode, aspose.drawing +// Tags: barcode, recognition, low-light, jpeg, histogram-equalization, aspose.barcode, aspose.drawing, code39, code128, qr using System; using System.IO; -using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Demonstrates barcode detection on low‑light JPEG images before and after histogram equalization. +/// Example program that reads barcodes from a low‑light JPEG image, +/// applies a simulated histogram equalization, and compares detection results. /// class Program { /// - /// Runs barcode recognition on low‑light JPEG images, applies histogram equalization, - /// and reports the detection improvement. + /// Entry point of the example. Performs barcode recognition on the original + /// and processed images and outputs detection details to the console. /// static void Main() { - // Directory containing low‑light JPEG images - string imagesDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images"); - if (!Directory.Exists(imagesDir)) - { - Console.WriteLine($"Images directory not found: {imagesDir}"); - return; - } + // Path to the low‑light JPEG image (adjust as needed) + string imagePath = "lowlight.jpg"; - // Retrieve all JPEG files in the directory - string[] jpegFiles = Directory.GetFiles(imagesDir, "*.jpg"); - if (jpegFiles.Length == 0) + // Verify that the image file exists before proceeding + if (!File.Exists(imagePath)) { - Console.WriteLine("No JPEG images found."); + Console.WriteLine($"Image file not found: {Path.GetFullPath(imagePath)}"); return; } - // Process each image file - foreach (string filePath in jpegFiles) + // ---------- Load original image ---------- + using (var originalBitmap = new Bitmap(imagePath)) { - if (!File.Exists(filePath)) - { - Console.WriteLine($"File does not exist: {filePath}"); - continue; - } + Console.WriteLine("Recognizing original image..."); - // Load original image - using (Bitmap originalBmp = new Bitmap(filePath)) + // Initialize barcode reader for selected symbologies + using (var reader = new BarCodeReader(originalBitmap, DecodeType.Code39, DecodeType.Code128, DecodeType.QR)) { - // Recognize barcodes in the original image - int originalCount = RecognizeBarcodes(originalBmp); + // Use high‑quality settings to improve detection in low‑light conditions + reader.QualitySettings = QualitySettings.HighQuality; - // Apply histogram equalization to improve contrast - using (Bitmap equalizedBmp = EqualizeHistogram(originalBmp)) - { - // Recognize barcodes in the equalized image - int equalizedCount = RecognizeBarcodes(equalizedBmp); - int improvement = equalizedCount - originalCount; + // Perform recognition + var results = reader.ReadBarCodes(); - // Output results for the current file - Console.WriteLine($"File: {Path.GetFileName(filePath)}"); - Console.WriteLine($" Barcodes detected (original): {originalCount}"); - Console.WriteLine($" Barcodes detected (equalized): {equalizedCount}"); - Console.WriteLine($" Improvement: {improvement}"); + // Output results for the original image + if (results.Length == 0) + { + Console.WriteLine("No barcodes detected in original image."); + } + else + { + foreach (var result in results) + { + Console.WriteLine($"[Original] Type: {result.CodeTypeName}, Text: {result.CodeText}, Confidence: {result.Confidence}"); + } } } - } - } - - /// - /// Recognizes barcodes in the given bitmap using the HighQuality preset. - /// - /// Bitmap image to be processed. - /// The number of detected barcodes. - private static int RecognizeBarcodes(Bitmap bmp) - { - using (BarCodeReader reader = new BarCodeReader()) - { - // Use HighQuality preset for low‑light / damaged images - reader.QualitySettings = QualitySettings.HighQuality; - - // Set the image for recognition - reader.SetBarCodeImage(bmp); - - // Perform recognition - BarCodeResult[] results = reader.ReadBarCodes(); - return results?.Length ?? 0; - } - } - /// - /// Performs simple histogram equalization on the input bitmap. - /// - /// Source bitmap to be equalized. - /// A new bitmap with equalized luminance (grayscale). - private static Bitmap EqualizeHistogram(Bitmap source) - { - int width = source.Width; - int height = source.Height; - Bitmap result = new Bitmap(width, height); - - // Compute histogram of luminance - int[] histogram = new int[256]; - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) + // ---------- Apply histogram equalization (placeholder) ---------- + // Aspose.Drawing does not provide a direct histogram equalization method. + // In a real scenario you would process 'originalBitmap' here. + // For demonstration we simply clone the bitmap to simulate a processed image. + using (var processedBitmap = (Bitmap)originalBitmap.Clone()) { - Color pixel = source.GetPixel(x, y); - // Convert to luminance using Rec. 601 luma formula - int lum = (int)(0.299 * pixel.R + 0.587 * pixel.G + 0.114 * pixel.B); - histogram[lum]++; - } - } + // Example of a simple contrast adjustment (optional) + // var attributes = new ImageAttributes(); + // attributes.SetContrast(1.5f); // placeholder – actual method may differ + // processedBitmap = processedBitmap.Adjust(attributes); // placeholder - // Compute cumulative distribution function (CDF) - int[] cdf = new int[256]; - cdf[0] = histogram[0]; - for (int i = 1; i < 256; i++) - { - cdf[i] = cdf[i - 1] + histogram[i]; - } - - // Normalize CDF to [0,255] - int totalPixels = width * height; - byte[] lut = new byte[256]; - for (int i = 0; i < 256; i++) - { - // Avoid division by zero - lut[i] = (byte)Math.Round(((double)cdf[i] - cdf[0]) / (totalPixels - cdf[0]) * 255.0); - } + Console.WriteLine("Recognizing processed (histogram‑equalized) image..."); - // Apply mapping to create equalized image (grayscale) - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - Color pixel = source.GetPixel(x, y); - int lum = (int)(0.299 * pixel.R + 0.587 * pixel.G + 0.114 * pixel.B); - byte newVal = lut[lum]; - Color newColor = Color.FromArgb(newVal, newVal, newVal); - result.SetPixel(x, y, newColor); + // Initialize barcode reader for the processed image + using (var reader = new BarCodeReader(processedBitmap, DecodeType.Code39, DecodeType.Code128, DecodeType.QR)) + { + // Apply the same high‑quality settings + reader.QualitySettings = QualitySettings.HighQuality; + + // Perform recognition on the processed image + var results = reader.ReadBarCodes(); + + // Output results for the processed image + if (results.Length == 0) + { + Console.WriteLine("No barcodes detected in processed image."); + } + else + { + foreach (var result in results) + { + Console.WriteLine($"[Processed] Type: {result.CodeTypeName}, Text: {result.CodeText}, Confidence: {result.Confidence}"); + } + } + } } } - return result; + // Program ends automatically; no explicit pause required. } } \ No newline at end of file diff --git a/barcode-recognition-performance/set-qualitysettingspreset-to-highperformance-before-reading-batch-of-png-barcode-images.cs b/barcode-recognition-performance/set-qualitysettingspreset-to-highperformance-before-reading-batch-of-png-barcode-images.cs index b2a8167..c6ad134 100644 --- a/barcode-recognition-performance/set-qualitysettingspreset-to-highperformance-before-reading-batch-of-png-barcode-images.cs +++ b/barcode-recognition-performance/set-qualitysettingspreset-to-highperformance-before-reading-batch-of-png-barcode-images.cs @@ -1,65 +1,67 @@ -// Title: High-Performance PNG Barcode Batch Reader -// Description: Demonstrates setting QualitySettings.Preset to HighPerformance before reading a batch of PNG barcode images, improving processing speed. +// Title: High‑Performance Barcode Recognition from PNG Images +// Description: Demonstrates setting QualitySettings.Preset to HighPerformance before reading a batch of PNG barcode images, improving recognition speed. +// Category-Description: This example belongs to the Aspose.BarCode image‑processing category, showcasing how to generate barcode images, store them, and efficiently recognize them using the BarCodeReader. It highlights key API classes such as BarcodeGenerator, BarCodeReader, QualitySettings, and DecodeType, which developers commonly use for batch barcode scanning and performance tuning. // Prompt: Set QualitySettings.Preset to HighPerformance before reading a batch of PNG barcode images. -// Tags: barcode, png, batch, highperformance, qualitysettings, aspose.barcode, read +// Tags: barcode symbology, generation, recognition, png, qualitysettings, highperformance, aspose.barcode using System; using System.IO; using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Program that reads up to five PNG barcode images using Aspose.BarCode with high‑performance quality settings. +/// Generates a small batch of PNG barcode images and reads them using a high‑performance quality preset. /// class Program { /// - /// Entry point. Scans a folder for PNG files, configures the reader for high performance, and outputs detected barcodes. + /// Entry point of the example. Creates sample barcodes, saves them as PNG files, and reads them with + /// to demonstrate faster recognition. /// static void Main() { - // Define the folder that contains PNG barcode images - string folderPath = "Barcodes"; + // Define a folder to store sample barcode images + string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(folderPath); - // Verify that the folder exists before proceeding - if (!Directory.Exists(folderPath)) + // Generate a small batch of sample PNG barcode images (5 items) + for (int i = 1; i <= 5; i++) { - Console.WriteLine($"Folder not found: {folderPath}"); - return; - } + string fileName = $"barcode{i}.png"; + string filePath = Path.Combine(folderPath, fileName); - // Retrieve all PNG files in the folder (limit processing to a maximum of 5 files for safety) - string[] pngFiles = Directory.GetFiles(folderPath, "*.png"); - if (pngFiles.Length == 0) - { - Console.WriteLine("No PNG files found in the folder."); - return; + // Create a barcode generator for Code128 with sample text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i}")) + { + // Save the generated barcode as a PNG file + generator.Save(filePath, BarCodeImageFormat.Png); + } } - // Determine how many files to process (up to 5) - int maxFiles = Math.Min(pngFiles.Length, 5); + // Retrieve all PNG files from the folder + string[] pngFiles = Directory.GetFiles(folderPath, "*.png"); - // Process each selected PNG file - for (int i = 0; i < maxFiles; i++) + // Process each PNG image in the folder + foreach (string pngFile in pngFiles) { - string filePath = pngFiles[i]; - - // Ensure the file still exists before attempting to read it - if (!File.Exists(filePath)) + if (!File.Exists(pngFile)) { - Console.WriteLine($"File not found: {filePath}"); + Console.WriteLine($"File not found: {pngFile}"); continue; } - // Create a BarCodeReader for the image and set the high‑performance quality preset - using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes)) + // Initialize a reader for the image, using all supported decode types + using (BarCodeReader reader = new BarCodeReader(pngFile, DecodeType.AllSupportedTypes)) { + // Apply the high‑performance quality preset before reading reader.QualitySettings = QualitySettings.HighPerformance; - // Read all barcodes present in the image and output their details + // Read and output detected barcodes foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($"File: {Path.GetFileName(filePath)} | Type: {result.CodeTypeName} | Text: {result.CodeText}"); + Console.WriteLine($"File: {Path.GetFileName(pngFile)} - Detected CodeText: {result.CodeText}"); } } } diff --git a/barcode-recognition-performance/set-qualitysettingsxdimension-to-6-pixels-for-detecting-large-barcodes-in-high-resolution-scans.cs b/barcode-recognition-performance/set-qualitysettingsxdimension-to-6-pixels-for-detecting-large-barcodes-in-high-resolution-scans.cs index 0584f76..612d40b 100644 --- a/barcode-recognition-performance/set-qualitysettingsxdimension-to-6-pixels-for-detecting-large-barcodes-in-high-resolution-scans.cs +++ b/barcode-recognition-performance/set-qualitysettingsxdimension-to-6-pixels-for-detecting-large-barcodes-in-high-resolution-scans.cs @@ -1,63 +1,62 @@ -// Title: Detect large barcodes in high‑resolution scans using XDimension setting -// Description: Demonstrates setting QualitySettings.XDimension to 6 pixels for reliable detection of large barcodes in high‑resolution images. +// Title: Detect Large Barcode Using XDimension Setting +// Description: Demonstrates setting QualitySettings.XDimension to 6 pixels to detect large barcodes in high‑resolution scans. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showing how to configure QualitySettings for accurate detection of high‑resolution barcodes. It uses BarCodeReader, QualitySettings, and XDimensionMode to adjust the minimal X‑dimension, a common requirement when scanning large or high‑density barcodes. Developers often need to tweak these settings to improve read reliability in industrial scanning applications. // Prompt: Set QualitySettings.XDimension to 6 pixels for detecting large barcodes in high‑resolution scans. -// Tags: barcode, detection, high-resolution, xdimension, qualitysettings, aspose.barcode +// Tags: barcode symbology, recognition, xdimension, highresolution, aspnet, aspose.barcode, cod128, qualitysettings using System; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Example program that generates a Code128 barcode, saves it, and reads it back -/// using custom to detect large barcodes in high‑resolution scans. +/// Example program that generates a Code128 barcode, saves it to a file, +/// and then reads it back using custom QualitySettings to detect large barcodes. /// class Program { /// - /// Entry point. Generates a barcode image, verifies its creation, and reads it using - /// with a minimal XDimension of 6 pixels. + /// Entry point of the application. + /// Generates a barcode image, verifies its creation, and reads it with + /// XDimension configured to 6 pixels for high‑resolution scans. /// static void Main() { - // Define the text to encode in the barcode - const string codeText = "1234567890"; - - // Path where the generated barcode image will be saved const string imagePath = "barcode.png"; - // Generate a Code128 barcode and save it as a PNG file - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + // ------------------------------------------------------------ + // Generate a simple Code128 barcode image and save it to disk. + // ------------------------------------------------------------ + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Persist the barcode image to disk generator.Save(imagePath); } - // Ensure the image file was successfully created before attempting to read it + // ------------------------------------------------------------ + // Verify that the barcode image was successfully created. + // ------------------------------------------------------------ if (!File.Exists(imagePath)) { - Console.WriteLine("Failed to create the barcode image."); + Console.WriteLine("Barcode image could not be created."); return; } - // Initialize a barcode reader for the saved image, targeting Code128 symbology - using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + // ------------------------------------------------------------ + // Read the barcode using BarCodeReader with custom QualitySettings. + // ------------------------------------------------------------ + using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) { - // Start with a high‑performance preset as a baseline configuration - reader.QualitySettings = QualitySettings.HighPerformance; - - // Adjust XDimension detection to handle large barcodes: - // - Use the minimal XDimension mode - // - Set the minimal XDimension value to 6 pixels + // Configure XDimension to detect large barcodes (6 pixels). reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - reader.QualitySettings.MinimalXDimension = 6f; // 6 pixels + reader.QualitySettings.MinimalXDimension = 6f; // pixels - // Perform barcode recognition and output results + // Iterate through all detected barcodes and output their details. foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($"Detected barcode type: {result.CodeTypeName}"); - Console.WriteLine($"Detected code text: {result.CodeText}"); + Console.WriteLine($"Detected Type: {result.CodeTypeName}"); + Console.WriteLine($"Code Text: {result.CodeText}"); } } } diff --git a/barcode-recognition-performance/set-recognition-timeout-of-200-milliseconds-and-log-any-barcodes-that-exceed-limit.cs b/barcode-recognition-performance/set-recognition-timeout-of-200-milliseconds-and-log-any-barcodes-that-exceed-limit.cs index 1266d9e..61dfccd 100644 --- a/barcode-recognition-performance/set-recognition-timeout-of-200-milliseconds-and-log-any-barcodes-that-exceed-limit.cs +++ b/barcode-recognition-performance/set-recognition-timeout-of-200-milliseconds-and-log-any-barcodes-that-exceed-limit.cs @@ -1,81 +1,91 @@ -// Title: Barcode recognition with timeout and performance logging -// Description: Demonstrates setting a 200 ms recognition timeout and logging barcodes that exceed this limit. +// Title: Barcode recognition with timeout and logging +// Description: Demonstrates setting a 200 ms recognition timeout and logging barcodes that exceed the limit. +// Category-Description: This example belongs to the Aspose.BarCode recognition category, showing how to configure the BarCodeReader timeout, generate sample barcodes, and handle timeout scenarios. It uses BarcodeGenerator, BarCodeReader, and related parameter classes, which developers commonly use for batch scanning and performance tuning. // Prompt: Set a recognition timeout of 200 milliseconds and log any barcodes that exceed the limit. -// Tags: barcode, timeout, logging, code128, aspose.barcodes, csharp +// Tags: barcode, recognition, timeout, logging, code128, aspose.barcode, generation, reading using System; using System.IO; -using System.Diagnostics; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Example program that generates a barcode, reads it with a timeout, -/// and logs any barcode whose processing time exceeds the specified limit. +/// Generates sample barcode images, then reads them with a 200 ms timeout, +/// logging any barcode that exceeds the timeout limit. /// class Program { /// - /// Entry point. Generates a sample barcode image, then reads it while measuring - /// processing time and enforcing a 200 ms timeout. + /// Entry point of the example. Creates barcodes, scans them with a timeout, + /// and outputs results or timeout notifications to the console. /// static void Main() { - // -------------------------------------------------------------------- - // Create a sample barcode image to read. - // -------------------------------------------------------------------- - const string imagePath = "sample.png"; - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123")) + // ------------------------------------------------------------ + // Prepare a folder for sample barcode images + // ------------------------------------------------------------ + string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(folderPath)) { - // Save the generated barcode to a PNG file. - generator.Save(imagePath); + Directory.CreateDirectory(folderPath); } - // -------------------------------------------------------------------- - // Verify the image exists before attempting recognition. - // -------------------------------------------------------------------- - if (!File.Exists(imagePath)) + // ------------------------------------------------------------ + // Generate a few sample barcode images (Code128) + // ------------------------------------------------------------ + string[] sampleTexts = { "1234567890", "ABCDEF", "9876543210" }; + for (int i = 0; i < sampleTexts.Length; i++) { - Console.WriteLine($"Error: Barcode image '{imagePath}' not found."); - return; + string filePath = Path.Combine(folderPath, $"barcode{i + 1}.png"); + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, sampleTexts[i])) + { + // Optional visual parameters + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; + generator.Save(filePath); + } } - // -------------------------------------------------------------------- - // Initialize the reader with all supported symbologies. - // -------------------------------------------------------------------- - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + // ------------------------------------------------------------ + // Scan each image with a recognition timeout of 200 ms + // ------------------------------------------------------------ + string[] imageFiles = Directory.GetFiles(folderPath, "*.png"); + foreach (string imageFile in imageFiles) { - // Set the recognition timeout to 200 milliseconds. - reader.Timeout = 200; + if (!File.Exists(imageFile)) + { + Console.WriteLine($"File not found: {imageFile}"); + continue; + } - try + using (var reader = new BarCodeReader(imageFile)) { - // Measure processing time for each detected barcode. - var stopwatch = Stopwatch.StartNew(); + // Set the timeout (in milliseconds) + reader.Timeout = 200; - // Iterate through all detected barcodes in the image. - foreach (var result in reader.ReadBarCodes()) + try { - long elapsedMs = stopwatch.ElapsedMilliseconds; - - // Log barcode details. - Console.WriteLine($"Detected barcode: Type = {result.CodeTypeName}, Text = {result.CodeText}"); + bool anyResult = false; - // If processing time exceeds the timeout, log a warning. - if (elapsedMs > 200) + // Attempt to read all barcodes in the image + foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($"Warning: Processing time {elapsedMs} ms exceeds the 200 ms limit for barcode '{result.CodeText}'."); + anyResult = true; + Console.WriteLine($"File: {Path.GetFileName(imageFile)} | Type: {result.CodeTypeName} | Text: {result.CodeText}"); } - // Reset the stopwatch for the next barcode. - stopwatch.Restart(); + // If no results were returned, the timeout was exceeded + if (!anyResult) + { + Console.WriteLine($"Timeout exceeded while reading {Path.GetFileName(imageFile)}"); + } + } + catch (Exception ex) + { + // Log any unexpected errors (including possible timeout aborts) + Console.WriteLine($"Error processing {Path.GetFileName(imageFile)}: {ex.Message}"); } - } - catch (Exception ex) - { - // Log any errors, including possible timeout exceptions. - Console.WriteLine($"Recognition error or timeout: {ex.Message}"); } } } diff --git a/barcode-recognition-performance/switch-qualitysettingspreset-to-maxquality-to-prioritize-accuracy-when-scanning-high-resolution-tiff-files.cs b/barcode-recognition-performance/switch-qualitysettingspreset-to-maxquality-to-prioritize-accuracy-when-scanning-high-resolution-tiff-files.cs index 5dd9a14..7304687 100644 --- a/barcode-recognition-performance/switch-qualitysettingspreset-to-maxquality-to-prioritize-accuracy-when-scanning-high-resolution-tiff-files.cs +++ b/barcode-recognition-performance/switch-qualitysettingspreset-to-maxquality-to-prioritize-accuracy-when-scanning-high-resolution-tiff-files.cs @@ -1,45 +1,43 @@ -// Title: High‑Resolution TIFF Barcode Scanning with MaxQuality -// Description: Demonstrates scanning a high‑resolution TIFF image for barcodes using Aspose.BarCode with the MaxQuality preset to improve accuracy. +// Title: Scanning High‑Resolution TIFF for Barcodes with MaxQuality Setting +// Description: Demonstrates reading barcodes from a high‑resolution TIFF file using Aspose.BarCode, switching to the MaxQuality preset to maximize recognition accuracy. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing how to configure QualitySettings for optimal scanning of high‑resolution images. It uses BarCodeReader, DecodeType, and QualitySettings classes, common in scenarios such as document processing, inventory management, and automated data capture where precise barcode detection is critical. // Prompt: Switch QualitySettings.Preset to MaxQuality to prioritize accuracy when scanning high‑resolution TIFF files. -// Tags: barcode, tiff, maxquality, recognition, aspnet, csharp +// Tags: barcode symbology, recognition, console output, barcodereader, qualitysettings, decodetype using System; using System.IO; using Aspose.BarCode.BarCodeRecognition; /// -/// Example program that reads barcodes from a high‑resolution TIFF file -/// using the Aspose.BarCode library with the MaxQuality setting for -/// optimal recognition accuracy. +/// Entry point for the barcode scanning example. /// class Program { /// - /// Entry point of the application. Scans the specified TIFF image, - /// applies the MaxQuality preset, and prints detected barcode texts. + /// Scans a high‑resolution TIFF image for barcodes using the MaxQuality preset. /// static void Main() { - // Define the path to the high‑resolution TIFF file - string imagePath = "highres.tif"; + // Path to the high‑resolution TIFF file to be scanned + string imagePath = "sample.tiff"; - // Ensure the file exists before attempting to read it + // Verify that the file exists before attempting to read it if (!File.Exists(imagePath)) { Console.WriteLine($"File not found: {imagePath}"); return; } - // Create a barcode reader that attempts to decode all supported symbologies - using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + // Create a BarCodeReader for the image, detecting all supported symbologies + using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) { - // Apply the MaxQuality preset to prioritize recognition accuracy over speed + // Switch to the MaxQuality preset for maximum recognition accuracy reader.QualitySettings = QualitySettings.MaxQuality; - // Iterate through each detected barcode and output its decoded text + // Iterate through all detected barcodes and output their text foreach (BarCodeResult result in reader.ReadBarCodes()) { - Console.WriteLine($"Detected barcode: {result.CodeText}"); + Console.WriteLine($"Detected: {result.CodeText}"); } } } diff --git a/barcode-recognition-performance/test-barcode-detection-on-images-with-added-gaussian-noise-while-using-minimalxdimension-filtering.cs b/barcode-recognition-performance/test-barcode-detection-on-images-with-added-gaussian-noise-while-using-minimalxdimension-filtering.cs index da69650..8fe8e76 100644 --- a/barcode-recognition-performance/test-barcode-detection-on-images-with-added-gaussian-noise-while-using-minimalxdimension-filtering.cs +++ b/barcode-recognition-performance/test-barcode-detection-on-images-with-added-gaussian-noise-while-using-minimalxdimension-filtering.cs @@ -1,7 +1,8 @@ // Title: Barcode detection with Gaussian noise and MinimalXDimension filtering -// Description: Demonstrates generating a Code128 barcode, adding Gaussian noise, and recognizing it using MinimalXDimension filtering to improve detection on noisy images. +// Description: Generates a Code128 barcode, adds Gaussian noise, and detects it using MinimalXDimension settings. +// Category-Description: This example demonstrates Aspose.BarCode generation and recognition workflows. It uses BarcodeGenerator to create barcodes, Aspose.Drawing for image manipulation, and BarCodeReader with QualitySettings to fine‑tune detection of small‑dimension barcodes. Typical scenarios include preprocessing noisy scans and configuring XDimension for robust recognition in industrial or retail applications. // Prompt: Test barcode detection on images with added Gaussian noise while using MinimalXDimension filtering. -// Tags: barcode, code128, gaussian noise, minimalxdimension, qualitysettings, aspose.barcode, csharp +// Tags: code128, gaussian noise, minimalxdimension, barcode detection, aspose.barcode, image processing using System; using System.IO; @@ -12,113 +13,115 @@ using Aspose.Drawing.Imaging; /// -/// Program that generates a barcode, adds Gaussian noise, and attempts to read it using MinimalXDimension filtering. +/// Demonstrates generating a barcode, corrupting it with Gaussian noise, +/// and recognizing it using MinimalXDimension filtering. /// class Program { /// - /// Entry point. Generates a barcode, adds noise, and reads it with configured quality settings. + /// Entry point of the example. Generates a barcode, adds noise, and attempts detection. /// static void Main() { - // Step 1: Create a simple Code128 barcode. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Test12345")) + // Create a Code128 barcode generator with sample data + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Use interpolation mode for flexible sizing. - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; - - // Generate the barcode image into a bitmap. - using (Bitmap barcodeBitmap = generator.GenerateBarCodeImage()) + // Store the generated barcode in a memory stream as PNG + using (var barcodeStream = new MemoryStream()) { - // Step 2: Add Gaussian noise to the bitmap. - AddGaussianNoise(barcodeBitmap, 20.0); // Standard deviation of 20. + generator.Save(barcodeStream, BarCodeImageFormat.Png); + barcodeStream.Position = 0; // Reset stream position for reading - // Step 3: Recognize the noisy barcode with MinimalXDimension filtering. - using (var reader = new BarCodeReader(barcodeBitmap, DecodeType.AllSupportedTypes)) + // Load the barcode image into a bitmap for pixel manipulation + using (var bitmap = new Bitmap(barcodeStream)) { - // Configure quality settings for robust detection. - reader.QualitySettings = QualitySettings.HighQuality; - reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - reader.QualitySettings.MinimalXDimension = 5f; // pixels - reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast; - reader.QualitySettings.AllowIncorrectBarcodes = true; - - // Perform recognition. - BarCodeResult[] results = reader.ReadBarCodes(); - - // Output results. - if (results.Length == 0) + // Apply Gaussian noise (mean=0, sigma=20) to simulate a noisy scan + AddGaussianNoise(bitmap, 0f, 20f); + + // Save the noisy image to a temporary file for recognition + string noisyImagePath = "noisy_barcode.png"; + bitmap.Save(noisyImagePath, ImageFormat.Png); + + // Ensure the file was created before proceeding + if (!File.Exists(noisyImagePath)) { - Console.WriteLine("No barcodes detected."); + Console.WriteLine("Failed to create the noisy image file."); + return; } - else + + // Initialize the barcode reader for Code128 with the noisy image + using (var reader = new BarCodeReader(noisyImagePath, DecodeType.Code128)) { - foreach (var result in results) + // Configure quality settings to improve detection of small XDimension barcodes + reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; + reader.QualitySettings.MinimalXDimension = 5f; // Minimum XDimension in pixels + reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast; + + // Iterate through detected barcodes and output results + foreach (var result in reader.ReadBarCodes()) { Console.WriteLine($"Detected Type: {result.CodeTypeName}"); - Console.WriteLine($"Decoded Text: {result.CodeText}"); - Console.WriteLine($"Confidence: {result.Confidence}"); - Console.WriteLine($"Reading Quality: {result.ReadingQuality}"); - Console.WriteLine($"Region: {result.Region.Rectangle}"); - Console.WriteLine(); + Console.WriteLine($"Detected Text: {result.CodeText}"); } } + + // Attempt to delete the temporary file; ignore any errors + try + { + File.Delete(noisyImagePath); + } + catch + { + // Suppress cleanup exceptions + } } } } } - // Adds Gaussian noise to each pixel of the bitmap. - private static void AddGaussianNoise(Bitmap bitmap, double sigma) + // Adds Gaussian noise to a bitmap. Mean and sigma are expressed in pixel intensity (0‑255). + private static void AddGaussianNoise(Bitmap bitmap, float mean, float sigma) { - Random rand = new Random(); - + var rand = new Random(); int width = bitmap.Width; int height = bitmap.Height; + // Iterate over each pixel and apply noise using the Box‑Muller transform for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { - // Get original pixel color. - Color original = bitmap.GetPixel(x, y); + // Retrieve the original pixel color + var originalColor = bitmap.GetPixel(x, y); - // Generate Gaussian noise for each channel. - int noiseR = (int)Math.Round(NextGaussian(rand) * sigma); - int noiseG = (int)Math.Round(NextGaussian(rand) * sigma); - int noiseB = (int)Math.Round(NextGaussian(rand) * sigma); + // Generate independent Gaussian noise for each color channel + int noiseR = (int)GaussianRandom(rand, mean, sigma); + int noiseG = (int)GaussianRandom(rand, mean, sigma); + int noiseB = (int)GaussianRandom(rand, mean, sigma); - // Apply noise and clamp to [0,255]. - int r = Clamp(original.R + noiseR, 0, 255); - int g = Clamp(original.G + noiseG, 0, 255); - int b = Clamp(original.B + noiseB, 0, 255); + // Apply noise and clamp channel values to the valid range [0,255] + int r = Math.Clamp(originalColor.R + noiseR, 0, 255); + int g = Math.Clamp(originalColor.G + noiseG, 0, 255); + int b = Math.Clamp(originalColor.B + noiseB, 0, 255); - // Set the new pixel color. + // Set the modified pixel back into the bitmap bitmap.SetPixel(x, y, Color.FromArgb(r, g, b)); } } } - // Generates a normally distributed random value using Box-Muller transform. - private static double NextGaussian(Random rand) + // Generates a single Gaussian‑distributed random number using the Box‑Muller method. + private static double GaussianRandom(Random rand, float mean, float sigma) { - // Generate two uniform random numbers in (0,1]. + // Generate two uniform random numbers in (0,1] double u1 = 1.0 - rand.NextDouble(); double u2 = 1.0 - rand.NextDouble(); - // Apply Box-Muller transform. + // Apply the Box‑Muller transform to obtain a standard normal value double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2); - return randStdNormal; - } - // Helper to clamp integer values. - private static int Clamp(int value, int min, int max) - { - if (value < min) return min; - if (value > max) return max; - return value; + // Scale and shift to the desired mean and standard deviation + return mean + sigma * randStdNormal; } } \ No newline at end of file diff --git a/barcode-recognition-performance/test-deconvolution-on-heavily-compressed-jpeg-images-to-determine-optimal-quality-threshold-for-reliable-scanning.cs b/barcode-recognition-performance/test-deconvolution-on-heavily-compressed-jpeg-images-to-determine-optimal-quality-threshold-for-reliable-scanning.cs index 9de9143..dcc0817 100644 --- a/barcode-recognition-performance/test-deconvolution-on-heavily-compressed-jpeg-images-to-determine-optimal-quality-threshold-for-reliable-scanning.cs +++ b/barcode-recognition-performance/test-deconvolution-on-heavily-compressed-jpeg-images-to-determine-optimal-quality-threshold-for-reliable-scanning.cs @@ -1,99 +1,101 @@ // Title: Deconvolution Test on JPEG Barcodes -// Description: Demonstrates testing different deconvolution modes on heavily compressed JPEG images to determine the optimal quality threshold for reliable barcode scanning. +// Description: Generates Code128 barcodes saved as JPEG, then reads them using different deconvolution modes to evaluate scanning reliability on heavily compressed images. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, demonstrating how to create barcode images, apply JPEG compression, and use the Deconvolution quality settings during recognition. It showcases the BarcodeGenerator, BarCodeReader, and DeconvolutionMode classes—common tools for developers who need to optimize barcode scanning under adverse image conditions. // Prompt: Test deconvolution on heavily compressed JPEG images to determine optimal quality threshold for reliable scanning. -// Tags: barcode, deconvolution, jpeg, quality, aspose.barcode, aspose.drawing, recognition +// Tags: code128, deconvolution, jpeg, barcode generation, barcode recognition, quality settings, aspose.barcode using System; using System.IO; -using System.Collections.Generic; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Program that evaluates deconvolution settings on JPEG images containing barcodes to find the best quality configuration. +/// Demonstrates barcode generation, JPEG compression, and deconvolution‑based recognition +/// to find the optimal quality threshold for reliable scanning of heavily compressed images. /// class Program { /// - /// Entry point. Scans each JPEG in the Images folder with various deconvolution modes and reports detection results. + /// Entry point of the example. Generates sample barcodes, saves them as JPEG, + /// and reads them back using various deconvolution modes. /// static void Main() { - // Folder containing JPEG images with barcodes. - string imagesFolder = "Images"; - - // Verify that the folder exists. - if (!Directory.Exists(imagesFolder)) + // -------------------------------------------------------------------- + // Prepare output folder for generated barcode images + // -------------------------------------------------------------------- + string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(folderPath)) { - Console.WriteLine($"Folder not found: {imagesFolder}"); - return; + Directory.CreateDirectory(folderPath); } - // Retrieve all JPEG files in the folder. - string[] jpegFiles = Directory.GetFiles(imagesFolder, "*.jpg"); - if (jpegFiles.Length == 0) + // -------------------------------------------------------------------- + // Generate sample Code128 barcode images (saved as JPEG with default quality) + // -------------------------------------------------------------------- + string[] barcodeTexts = { "CODE128-123", "CODE128-456", "CODE128-789" }; + for (int i = 0; i < barcodeTexts.Length; i++) { - Console.WriteLine($"No JPEG files found in folder: {imagesFolder}"); - return; + string filePath = Path.Combine(folderPath, $"barcode_{i + 1}.jpg"); + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, barcodeTexts[i])) + { + // Save the barcode as a JPEG image + generator.Save(filePath, BarCodeImageFormat.Jpeg); + } } - // Define the deconvolution modes that will be tested. - DeconvolutionMode[] deconvolutionModes = new[] - { - DeconvolutionMode.Fast, - DeconvolutionMode.Normal, - DeconvolutionMode.Slow - }; + // -------------------------------------------------------------------- + // Define deconvolution modes to be tested during recognition + // -------------------------------------------------------------------- + DeconvolutionMode[] modes = { DeconvolutionMode.Fast, DeconvolutionMode.Normal, DeconvolutionMode.Slow }; - // Process each JPEG file individually. - foreach (string filePath in jpegFiles) + // -------------------------------------------------------------------- + // Locate all generated JPEG images for processing + // -------------------------------------------------------------------- + string[] imageFiles = Directory.GetFiles(folderPath, "*.jpg"); + if (imageFiles.Length == 0) { - // Ensure the file still exists before processing. - if (!File.Exists(filePath)) - { - Console.WriteLine($"File not found: {filePath}"); - continue; - } - - Console.WriteLine($"Processing file: {Path.GetFileName(filePath)}"); + Console.WriteLine("No JPEG images found for processing."); + return; + } - // Test each deconvolution mode on the current image. - foreach (DeconvolutionMode mode in deconvolutionModes) + // -------------------------------------------------------------------- + // Process each image with each deconvolution mode and output results + // -------------------------------------------------------------------- + foreach (string imageFile in imageFiles) + { + Console.WriteLine($"Processing image: {Path.GetFileName(imageFile)}"); + foreach (DeconvolutionMode mode in modes) { - // Create a barcode reader for the image, supporting all symbologies. - using (BarCodeReader reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes)) + using (BarCodeReader reader = new BarCodeReader(imageFile, DecodeType.AllSupportedTypes)) { - // Apply a high‑quality preset to improve detection on low‑quality images. - reader.QualitySettings = QualitySettings.HighQuality; - - // Set the current deconvolution mode. + // Apply the current deconvolution mode to the reader's quality settings reader.QualitySettings.Deconvolution = mode; - // Perform barcode recognition. + // Attempt to read barcodes from the image BarCodeResult[] results = reader.ReadBarCodes(); - // Output the results for the current mode. + Console.WriteLine($" Deconvolution: {mode}"); if (results.Length == 0) { - Console.WriteLine($" Deconvolution: {mode} – No barcode detected."); + Console.WriteLine(" No barcode detected."); } else { foreach (BarCodeResult result in results) { - // ReadingQuality is a double representing the confidence percentage. + // ReadingQuality indicates confidence percentage of the detection double quality = result.ReadingQuality; - string codeText = result.CodeText ?? ""; - Console.WriteLine($" Deconvolution: {mode} – Detected: {codeText}, ReadingQuality: {quality:F2}%"); + string text = string.IsNullOrEmpty(result.CodeText) ? "" : result.CodeText; + Console.WriteLine($" CodeText: {text}"); + Console.WriteLine($" ReadingQuality: {quality:F2}%"); } } } } - - Console.WriteLine(); // Blank line between files. + Console.WriteLine(); } - - // Indicate that processing has finished. - Console.WriteLine("Processing completed."); } } \ No newline at end of file diff --git a/barcode-recognition-performance/test-effect-of-setting-minimalxdimension-to-05-pixels-on-detection-of-sub-pixel-barcode-elements.cs b/barcode-recognition-performance/test-effect-of-setting-minimalxdimension-to-05-pixels-on-detection-of-sub-pixel-barcode-elements.cs index 2ca48e8..409f65c 100644 --- a/barcode-recognition-performance/test-effect-of-setting-minimalxdimension-to-05-pixels-on-detection-of-sub-pixel-barcode-elements.cs +++ b/barcode-recognition-performance/test-effect-of-setting-minimalxdimension-to-05-pixels-on-detection-of-sub-pixel-barcode-elements.cs @@ -1,68 +1,87 @@ -// Title: Demonstrate MinimalXDimension effect on sub-pixel barcode detection -// Description: Generates a Code128 barcode with a 0.5‑pixel module size and reads it using MinimalXDimension=0.5 to show detection of sub‑pixel elements. +// Title: Minimal X Dimension Effect on Sub‑Pixel Barcode Detection +// Description: Demonstrates how setting MinimalXDimension to 0.5 pixels influences the detection of barcode elements that are smaller than a pixel. +// Category-Description: This example belongs to the Aspose.BarCode image generation and recognition category. It showcases the use of BarcodeGenerator for creating a Code128 barcode with a tiny XDimension and BarCodeReader with QualitySettings to adjust MinimalXDimension. Developers working with low‑resolution scans or sub‑pixel barcode elements often need to fine‑tune these settings to improve read accuracy. // Prompt: Test the effect of setting MinimalXDimension to 0.5 pixels on detection of sub‑pixel barcode elements. -// Tags: barcode, code128, minimalxdimension, subpixel, generation, recognition, aspose.barcode +// Tags: code128, minimalxdimension, png, barcodegenerator, barcodereader, qualitysettings, imagegeneration, imagerecognition using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.BarCode; +using Aspose.Drawing; /// -/// Example program that generates a sub‑pixel Code128 barcode and reads it using MinimalXDimension settings. +/// Generates a Code128 barcode with a sub‑pixel XDimension and reads it back using +/// MinimalXDimension set to 0.5 pixels to observe detection behavior. /// class Program { /// - /// Entry point. Generates a barcode image, then reads it with MinimalXDimension set to 0.5 pixels. + /// Entry point of the example. Creates a barcode image, then attempts to read it + /// with specific quality settings that target sub‑pixel element detection. /// static void Main() { - // Define the output file path for the generated barcode image - string barcodePath = "barcode.png"; + // Define the output path for the generated barcode image. + string barcodePath = Path.Combine(Directory.GetCurrentDirectory(), "subpixel_barcode.png"); + + // Remove any existing file to ensure a clean run. + if (File.Exists(barcodePath)) + { + File.Delete(barcodePath); + } // ------------------------------------------------------------ - // Generate a simple Code128 barcode with a very small XDimension (sub‑pixel) + // Generate a Code128 barcode with an XDimension of 0.5 points + // (approximately 0.5 pixels at 96 DPI) to create sub‑pixel elements. // ------------------------------------------------------------ - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Set a tiny module size (0.5 points ≈ 0.5 pixels) + // Set the minimal module size. generator.Parameters.Barcode.XDimension.Point = 0.5f; - // Optionally set image dimensions to keep the barcode visible + // Use interpolation mode to control the final image dimensions. + generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; generator.Parameters.ImageWidth.Point = 200f; generator.Parameters.ImageHeight.Point = 100f; - // Save the generated barcode image to the specified path - generator.Save(barcodePath); + // Define foreground and background colors. + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; + + // Save the generated barcode as a PNG file. + generator.Save(barcodePath, BarCodeImageFormat.Png); } - // ------------------------------------------------------------ - // Verify that the barcode image was successfully created - // ------------------------------------------------------------ + // Verify that the image was successfully created. if (!File.Exists(barcodePath)) { - Console.WriteLine($"Error: Barcode image not found at '{barcodePath}'."); + Console.WriteLine("Failed to create barcode image."); return; } // ------------------------------------------------------------ - // Read the barcode using MinimalXDimension set to 0.5 pixels + // Read the barcode using MinimalXDimension set to 0.5 pixels. // ------------------------------------------------------------ - using (var reader = new BarCodeReader(barcodePath, DecodeType.AllSupportedTypes)) + using (var reader = new BarCodeReader(barcodePath, DecodeType.Code128)) { - // Configure recognition to use the minimal XDimension mode + // Apply high‑performance quality settings. + reader.QualitySettings = QualitySettings.HighPerformance; + + // Instruct the reader to use the MinimalXDimension mode. reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - reader.QualitySettings.MinimalXDimension = 0.5f; + reader.QualitySettings.MinimalXDimension = 0.5f; // 0.5 pixels - // Perform recognition and iterate over all detected barcodes + // Speed up processing by using a fast deconvolution mode. + reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast; + + // Iterate through all detected barcodes and output their details. foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($"Detected Type: {result.CodeTypeName}"); - Console.WriteLine($"Detected Text: {result.CodeText}"); - - // Output the region (bounding rectangle) of the detected barcode + Console.WriteLine($"Detected Type: {result.CodeType}"); + Console.WriteLine($"Code Text: {result.CodeText}"); + Console.WriteLine($"Reading Quality: {result.ReadingQuality}"); var bounds = result.Region.Rectangle; Console.WriteLine($"Region: X={bounds.X}, Y={bounds.Y}, Width={bounds.Width}, Height={bounds.Height}"); } diff --git a/barcode-recognition-performance/test-recognition-of-code128-barcodes-with-xdimension-set-to-2-pixels-across-multiple-image-resolutions.cs b/barcode-recognition-performance/test-recognition-of-code128-barcodes-with-xdimension-set-to-2-pixels-across-multiple-image-resolutions.cs index 586bcab..a740f87 100644 --- a/barcode-recognition-performance/test-recognition-of-code128-barcodes-with-xdimension-set-to-2-pixels-across-multiple-image-resolutions.cs +++ b/barcode-recognition-performance/test-recognition-of-code128-barcodes-with-xdimension-set-to-2-pixels-across-multiple-image-resolutions.cs @@ -1,7 +1,8 @@ -// Title: Code128 Barcode Generation and Recognition with Fixed XDimension -// Description: Demonstrates generating Code128 barcodes with a 2‑pixel XDimension at various DPI settings and then recognizing them using minimal XDimension detection. +// Title: Code128 Barcode Generation and Recognition with Variable DPI and XDimension +// Description: Demonstrates generating a Code128 barcode with XDimension set to 2 pixels at several DPI settings, then recognizing it to verify the encoded text. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes and BarCodeReader for decoding them. Developers often need to adjust XDimension and image resolution to meet printing or scanning requirements, making this pattern common in inventory, shipping, and retail applications. // Prompt: Test recognition of Code128 barcodes with XDimension set to 2 pixels across multiple image resolutions. -// Tags: code128, barcode generation, barcode recognition, xdimension, dpi, aspnet.barcode +// Tags: code128, barcode generation, barcode recognition, png, xdimension, resolution, aspnet.barcode, aspnet.barcode.generator, aspnet.barcode.reader using System; using System.IO; @@ -9,100 +10,77 @@ using Aspose.BarCode.BarCodeRecognition; /// -/// Generates Code128 barcodes with a fixed XDimension at multiple resolutions, -/// then reads them back using minimal XDimension detection. +/// Generates Code128 barcodes at multiple DPI settings with a fixed XDimension, +/// saves them as PNG files, and then reads them back to verify successful recognition. /// class Program { /// - /// Entry point of the example. Creates barcode images and validates their recognition. + /// Entry point of the example. Executes barcode creation, saving, and recognition loops. /// static void Main() { - // Sample Code128 text to encode - const string codeText = "Test123"; + // Text to encode in the barcode + const string codeText = "CODE128TEST"; - // Desired XDimension (module width) in pixels - const float xDimensionPixels = 2f; + // Array of DPI values to test (low, medium, high resolution) + int[] resolutions = { 96, 150, 300 }; - // Different image resolutions (DPI) to test - int[] resolutions = { 100, 200, 300 }; - - // Directory to store generated barcode images - string outputDir = "Barcodes"; + // Prepare output directory for generated barcode images + string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); if (!Directory.Exists(outputDir)) { - // Create the output folder if it does not exist Directory.CreateDirectory(outputDir); } - // ------------------------------------------------- - // Generation Phase: create barcodes with same XDimension but different DPI - // ------------------------------------------------- + // Iterate over each DPI setting foreach (int dpi in resolutions) { - // Build file name based on DPI + // Build file name that includes the DPI value string filePath = Path.Combine(outputDir, $"code128_{dpi}dpi.png"); - // Initialize barcode generator for Code128 + // ---------- Barcode Generation ---------- + // Create a generator for Code128 with the specified text using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - // Set XDimension to 2 pixels (point unit) - generator.Parameters.Barcode.XDimension.Point = xDimensionPixels; - - // Set image resolution (dots per inch) + // Set module size to 2 pixels (XDimension) and image resolution + generator.Parameters.Barcode.XDimension.Pixels = 2f; generator.Parameters.Resolution = dpi; - // Save the generated barcode image to file - generator.Save(filePath); - Console.WriteLine($"Generated barcode: {filePath} (Resolution: {dpi} DPI)"); + // Save the generated barcode as a PNG image + generator.Save(filePath, BarCodeImageFormat.Png); } - } - - Console.WriteLine(); - Console.WriteLine("=== Recognition Phase ==="); - - // ------------------------------------------------- - // Recognition Phase: read each generated barcode using minimal XDimension detection - // ------------------------------------------------- - foreach (int dpi in resolutions) - { - // Path to the previously generated image - string filePath = Path.Combine(outputDir, $"code128_{dpi}dpi.png"); + // Verify that the image file was successfully created if (!File.Exists(filePath)) { - Console.WriteLine($"Warning: File not found - {filePath}"); + Console.WriteLine($"Failed to create barcode image at {filePath}"); continue; } - // Initialize barcode reader for Code128 + // ---------- Barcode Recognition ---------- + // Initialize a reader for Code128 barcodes from the saved image using (var reader = new BarCodeReader(filePath, DecodeType.Code128)) { - // Apply normal quality preset - reader.QualitySettings = QualitySettings.NormalQuality; - - // Configure XDimension detection to use the minimal size (2 pixels) - reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - reader.QualitySettings.MinimalXDimension = xDimensionPixels; + // Optional: adjust XDimension handling for low‑resolution images + // reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - bool found = false; + // Perform the recognition + var results = reader.ReadBarCodes(); - // Iterate through all detected barcodes (should be one per image) - foreach (var result in reader.ReadBarCodes()) + // Output recognition results + if (results.Length == 0) { - Console.WriteLine($"Resolution {dpi} DPI: Detected CodeText = '{result.CodeText}'"); - found = true; + Console.WriteLine($"Resolution {dpi} DPI: No barcode detected."); } - - if (!found) + else { - Console.WriteLine($"Resolution {dpi} DPI: No barcode detected."); + foreach (var result in results) + { + Console.WriteLine($"Resolution {dpi} DPI: Detected CodeText = {result.CodeText}"); + } } } } - - Console.WriteLine(); - Console.WriteLine("Processing completed."); } } \ No newline at end of file diff --git a/barcode-recognition-performance/test-recognition-of-very-large-barcodes-10-pixels-xdimension-using-large-mode-configuration.cs b/barcode-recognition-performance/test-recognition-of-very-large-barcodes-10-pixels-xdimension-using-large-mode-configuration.cs index 5c4547f..5dc765d 100644 --- a/barcode-recognition-performance/test-recognition-of-very-large-barcodes-10-pixels-xdimension-using-large-mode-configuration.cs +++ b/barcode-recognition-performance/test-recognition-of-very-large-barcodes-10-pixels-xdimension-using-large-mode-configuration.cs @@ -1,7 +1,8 @@ // Title: Large XDimension Barcode Generation and Recognition // Description: Demonstrates creating a Code128 barcode with an XDimension larger than 10 pixels and recognizing it using Large mode. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, showcasing how to configure XDimension for high‑resolution barcodes. It uses BarcodeGenerator, BarCodeReader, and related quality settings, which developers often need when handling large‑format barcodes in printing or scanning applications. // Prompt: Test recognition of very large barcodes (>10 pixels XDimension) using Large mode configuration. -// Tags: code128, barcode generation, barcode recognition, large xdimension, aspnet barcoderecognition, aspnet barcodelibrary +// Tags: barcode, code128, xdimension, large mode, generation, recognition, aspose.barcode using System; using System.IO; @@ -10,61 +11,71 @@ using Aspose.BarCode.BarCodeRecognition; /// -/// Generates a Code128 barcode with a large XDimension and then reads it using Large mode configuration. +/// Example program that generates a Code128 barcode with a large XDimension +/// and then reads it back using the Large XDimension recognition mode. /// class Program { /// - /// Entry point of the example. Creates a barcode image, verifies its creation, and reads the barcode. + /// Entry point of the example. Generates a barcode image, reads it, + /// outputs detection results, and cleans up temporary files. /// static void Main() { - // Define the file name for the generated barcode image. - const string imagePath = "large_barcode.png"; + // Define temporary file path for the barcode image + string imagePath = Path.Combine(Path.GetTempPath(), "large_xdimension_barcode.png"); - // ------------------------------------------------- - // Generate a Code128 barcode with a large XDimension (>10 pixels). - // ------------------------------------------------- - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "LargeXDimTest")) + // Ensure any existing file is removed before generation + if (File.Exists(imagePath)) { - // Disable auto-sizing so that XDimension directly controls the module size. - generator.Parameters.AutoSizeMode = AutoSizeMode.None; + File.Delete(imagePath); + } - // Set XDimension to 12 pixels (larger than the 10‑pixel threshold). - generator.Parameters.Barcode.XDimension.Point = 12f; + // -------------------- Barcode Generation -------------------- + // Create a Code128 barcode with a sample code text + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "LargeXDimTest123")) + { + // Set a large XDimension (>10 pixels) to simulate a high‑resolution barcode + generator.Parameters.Barcode.XDimension.Pixels = 12f; // 12 pixels per module - // Optionally increase the image canvas to accommodate the larger modules. - generator.Parameters.ImageWidth.Point = 800f; - generator.Parameters.ImageHeight.Point = 200f; + // Disable auto‑size to keep the XDimension effect unchanged + generator.Parameters.AutoSizeMode = AutoSizeMode.None; - // Save the generated barcode image to disk. - generator.Save(imagePath); + // Save the generated barcode image to the temporary path + generator.Save(imagePath, BarCodeImageFormat.Png); } - // ------------------------------------------------- - // Verify that the barcode image file was successfully created. - // ------------------------------------------------- + // Verify that the image was successfully created if (!File.Exists(imagePath)) { - Console.WriteLine($"Error: Barcode image '{imagePath}' was not created."); + Console.WriteLine("Failed to create the barcode image."); return; } - // ------------------------------------------------- - // Read the barcode using Large XDimension mode. - // ------------------------------------------------- + // -------------------- Barcode Recognition -------------------- + // Initialize a reader for the generated image, targeting Code128 symbology using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) { - // Configure the reader to handle large XDimension values. + // Configure the reader to expect large XDimension barcodes reader.QualitySettings.XDimension = XDimensionMode.Large; - // Perform recognition and output the results. + // Perform recognition and output each detected barcode's details foreach (var result in reader.ReadBarCodes()) { Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}"); Console.WriteLine($"Decoded Text: {result.CodeText}"); - Console.WriteLine($"Reading Quality: {result.ReadingQuality}"); + Console.WriteLine($"Recognition XDimension Mode: {reader.QualitySettings.XDimension}"); } } + + // Clean up the temporary image file after processing + try + { + File.Delete(imagePath); + } + catch + { + // Ignored – file may be locked or already removed + } } } \ No newline at end of file diff --git a/barcode-recognition-performance/use-stopwatch-to-measure-time-spent-in-barcode-detection-versus-image-loading.cs b/barcode-recognition-performance/use-stopwatch-to-measure-time-spent-in-barcode-detection-versus-image-loading.cs index d1fb851..70e8dc9 100644 --- a/barcode-recognition-performance/use-stopwatch-to-measure-time-spent-in-barcode-detection-versus-image-loading.cs +++ b/barcode-recognition-performance/use-stopwatch-to-measure-time-spent-in-barcode-detection-versus-image-loading.cs @@ -1,71 +1,78 @@ -// Title: Measure barcode detection vs image loading time -// Description: Demonstrates loading a barcode image, generating it if missing, and using Stopwatch to compare the time spent loading the image versus detecting the barcode. +// Title: Measure Barcode Detection vs Image Loading Time +// Description: Demonstrates how to use Stopwatch to compare the time required to load a barcode image and to detect the barcode within it. +// Category-Description: This example belongs to the Aspose.BarCode performance measurement category, illustrating the use of BarcodeGenerator, BarCodeReader, and System.Diagnostics.Stopwatch. Developers often need to benchmark image loading versus barcode recognition to optimize processing pipelines in scanning applications, inventory systems, and mobile capture scenarios. // Prompt: Use a Stopwatch to measure time spent in barcode detection versus image loading. -// Tags: barcode symbology, detection, timing, stopwatch, aspose.barcode, image loading +// Tags: barcode symbology, detection, performance, stopwatch, aspose.barcode, generation, recognition, png using System; using System.Diagnostics; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Example program that measures and compares the time required to load a barcode image -/// and to detect the barcode within that image using Aspose.BarCode. +/// Example program that generates a barcode image (if missing), measures the time to load the image, +/// and measures the time to detect the barcode using Aspose.BarCode APIs. /// class Program { /// - /// Entry point of the application. Generates a sample barcode image if it does not exist, - /// then measures image loading time and barcode detection time using Stopwatch. + /// Entry point of the application. /// static void Main() { - // ------------------------------------------------------------ - // Define the path for the sample barcode image - // ------------------------------------------------------------ - string imagePath = Path.Combine(Directory.GetCurrentDirectory(), "sample.png"); + // Define the path for the sample barcode image. + string imagePath = "sample.png"; - // ------------------------------------------------------------ - // Ensure the barcode image exists; generate it if missing - // ------------------------------------------------------------ + // Generate a sample barcode image if it does not already exist. if (!File.Exists(imagePath)) { - // Create a Code128 barcode with sample data and save it as PNG - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) { + // Save the generated barcode as a PNG file. generator.Save(imagePath, BarCodeImageFormat.Png); } } - // ------------------------------------------------------------ - // Measure the time taken to load the image from disk into memory - // ------------------------------------------------------------ - var loadTimer = Stopwatch.StartNew(); - using (FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read)) + // ------------------------------ + // Measure image loading time. + // ------------------------------ + var loadStopwatch = new Stopwatch(); + loadStopwatch.Start(); + + // Load the image into a Bitmap object. + using (var bitmap = new Bitmap(imagePath)) { - using (var bitmap = new Bitmap(fs)) - { - // Image is loaded; no additional processing required for timing - } + loadStopwatch.Stop(); + Console.WriteLine($"Image loading time: {loadStopwatch.Elapsed.TotalMilliseconds} ms"); } - loadTimer.Stop(); - Console.WriteLine($"Image loading time: {loadTimer.ElapsedMilliseconds} ms"); - // ------------------------------------------------------------ - // Measure the time taken to detect barcodes in the loaded image - // ------------------------------------------------------------ - var detectTimer = Stopwatch.StartNew(); - using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) + // ------------------------------ + // Measure barcode detection time. + // ------------------------------ + var detectStopwatch = new Stopwatch(); + + // Load the image again for barcode detection. + using (var bitmap = new Bitmap(imagePath)) { - foreach (var result in reader.ReadBarCodes()) + // Initialize the barcode reader for all supported symbologies. + using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes)) { - Console.WriteLine($"Detected barcode: {result.CodeTypeName}, Text: {result.CodeText}"); + detectStopwatch.Start(); + + // Perform barcode detection. + var results = reader.ReadBarCodes(); + + detectStopwatch.Stop(); + Console.WriteLine($"Barcode detection time: {detectStopwatch.Elapsed.TotalMilliseconds} ms"); + + // Output detection results. + foreach (var result in results) + { + Console.WriteLine($"Detected Type: {result.CodeTypeName}, CodeText: {result.CodeText}"); + } } } - detectTimer.Stop(); - Console.WriteLine($"Barcode detection time: {detectTimer.ElapsedMilliseconds} ms"); } } \ No newline at end of file diff --git a/barcode-recognition-performance/validate-that-enabling-allowincorrectbarcodes-does-not-alter-decoded-codetext-of-valid-barcodes.cs b/barcode-recognition-performance/validate-that-enabling-allowincorrectbarcodes-does-not-alter-decoded-codetext-of-valid-barcodes.cs index 5d55350..7418923 100644 --- a/barcode-recognition-performance/validate-that-enabling-allowincorrectbarcodes-does-not-alter-decoded-codetext-of-valid-barcodes.cs +++ b/barcode-recognition-performance/validate-that-enabling-allowincorrectbarcodes-does-not-alter-decoded-codetext-of-valid-barcodes.cs @@ -1,68 +1,79 @@ // Title: Validate AllowIncorrectBarcodes does not affect decoded CodeText -// Description: Demonstrates generating a Code128 barcode, decoding it with default settings and with AllowIncorrectBarcodes enabled, and verifies that the decoded text remains unchanged. +// Description: Demonstrates generating a Code128 barcode, decoding it with and without AllowIncorrectBarcodes, and confirming the decoded text remains unchanged. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the BarcodeGenerator for creating barcodes and BarCodeReader for decoding them. Developers often need to validate quality settings such as AllowIncorrectBarcodes to ensure robust scanning in real‑world applications. The snippet highlights typical use cases involving EncodeTypes, DecodeType, and QualitySettings. // Prompt: Validate that enabling AllowIncorrectBarcodes does not alter the decoded CodeText of valid barcodes. -// Tags: code128, barcode generation, barcode recognition, allowincorrectbarcodes, validation +// Tags: code128, barcode generation, barcode recognition, allowincorrectbarcodes, validation, aspose.barcode using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Example program that validates the effect of AllowIncorrectBarcodes on decoding valid barcodes. +/// Example program that verifies the AllowIncorrectBarcodes quality setting does not change the decoded CodeText for a valid barcode. /// class Program { /// - /// Entry point. Generates a barcode, decodes it with default and altered settings, and compares the results. + /// Entry point. Generates a barcode, reads it twice with different AllowIncorrectBarcodes settings, and validates consistency. /// static void Main() { - // Define the text to encode in the barcode. - const string originalText = "Test12345"; + // Original text to encode into the barcode. + const string originalCodeText = "Test12345"; - // Create a memory stream to hold the generated barcode image. - using (var memoryStream = new MemoryStream()) + // Create a Code128 barcode generator and produce an image in memory. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, originalCodeText)) + using (var bitmap = generator.GenerateBarCodeImage()) + using (var imageStream = new MemoryStream()) { - // Generate a Code128 barcode and save it as PNG into the memory stream. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, originalText)) - { - generator.Save(memoryStream, BarCodeImageFormat.Png); - } - - // Reset the stream position so it can be read from the beginning. - memoryStream.Position = 0; + // Save the generated bitmap as PNG into the memory stream. + bitmap.Save(imageStream, ImageFormat.Png); + imageStream.Position = 0; // Reset stream for reading. - // Decode the barcode using default settings (AllowIncorrectBarcodes = false). - string decodedDefault; - using (var reader = new BarCodeReader(memoryStream, DecodeType.Code128)) + // ---------- First read: default setting (AllowIncorrectBarcodes = false) ---------- + string decodedWithoutAllowance; + using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes)) { - var results = reader.ReadBarCodes(); - decodedDefault = results.Length > 0 ? results[0].CodeText : null; + reader.QualitySettings.AllowIncorrectBarcodes = false; + decodedWithoutAllowance = ReadFirstCodeText(reader); } - // Reset the stream position again for the second decoding pass. - memoryStream.Position = 0; + // Reset stream position before the second read. + imageStream.Position = 0; - // Decode the same barcode with AllowIncorrectBarcodes enabled. - string decodedAllow; - using (var reader = new BarCodeReader(memoryStream, DecodeType.Code128)) + // ---------- Second read: AllowIncorrectBarcodes = true ---------- + string decodedWithAllowance; + using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes)) { reader.QualitySettings.AllowIncorrectBarcodes = true; - var results = reader.ReadBarCodes(); - decodedAllow = results.Length > 0 ? results[0].CodeText : null; + decodedWithAllowance = ReadFirstCodeText(reader); } - // Compare the two decoded values to ensure they are identical. - bool isEqual = string.Equals(decodedDefault, decodedAllow, StringComparison.Ordinal); - Console.WriteLine($"Original CodeText: {originalText}"); - Console.WriteLine($"Decoded (default settings): {decodedDefault ?? "null"}"); - Console.WriteLine($"Decoded (AllowIncorrectBarcodes = true): {decodedAllow ?? "null"}"); - Console.WriteLine(isEqual - ? "Success: AllowIncorrectBarcodes does not alter the decoded CodeText." - : "Failure: Decoded CodeText differs when AllowIncorrectBarcodes is enabled."); + // Validate that both decodings match the original text. + bool isConsistent = decodedWithoutAllowance == decodedWithAllowance && + decodedWithoutAllowance == originalCodeText; + + // Output results. + Console.WriteLine($"Original CodeText: {originalCodeText}"); + Console.WriteLine($"Decoded without AllowIncorrectBarcodes: {decodedWithoutAllowance}"); + Console.WriteLine($"Decoded with AllowIncorrectBarcodes: {decodedWithAllowance}"); + Console.WriteLine(isConsistent + ? "Success: Decoded CodeText is unchanged by AllowIncorrectBarcodes." + : "Failure: Decoded CodeText differs."); + } + } + + // Reads the first barcode result from the reader and returns its CodeText. + private static string ReadFirstCodeText(BarCodeReader reader) + { + foreach (var result in reader.ReadBarCodes()) + { + return result.CodeText; } + return null; } } \ No newline at end of file diff --git a/barcode-recognition-performance/validate-that-resetting-qualitysettings-to-defaults-restores-original-cpu-consumption-patterns-during-processing.cs b/barcode-recognition-performance/validate-that-resetting-qualitysettings-to-defaults-restores-original-cpu-consumption-patterns-during-processing.cs index 2909e47..ab57421 100644 --- a/barcode-recognition-performance/validate-that-resetting-qualitysettings-to-defaults-restores-original-cpu-consumption-patterns-during-processing.cs +++ b/barcode-recognition-performance/validate-that-resetting-qualitysettings-to-defaults-restores-original-cpu-consumption-patterns-during-processing.cs @@ -1,66 +1,102 @@ -// Title: Barcode Quality Settings Reset Demonstration -// Description: Generates a Code128 barcode, reads it with a custom high‑quality setting, then resets to default to show CPU usage restoration. +// Title: Reset QualitySettings to defaults and validate processing time +// Description: Demonstrates measuring barcode reading performance with different QualitySettings and confirms that resetting to defaults restores the original processing time. +// Category-Description: This example belongs to the Aspose.BarCode performance tuning category, illustrating how QualitySettings affect CPU usage during barcode recognition. It showcases the use of BarcodeGenerator, BarCodeReader, and QualitySettings classes to generate a Code128 barcode, read it under various quality presets, and validate that reverting to NormalQuality restores baseline performance. Developers often need such patterns to benchmark and optimize barcode processing in high‑throughput applications. // Prompt: Validate that resetting QualitySettings to defaults restores original CPU consumption patterns during processing. -// Tags: barcode, code128, qualitysettings, reset, generation, recognition, png, aspnet +// Tags: code128, performance, qualitysettings, reading, aspose.barcode, generation, recognition using System; +using System.Diagnostics; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; /// -/// Demonstrates how changing and then resetting the of a -/// affects barcode recognition. The example generates a barcode, reads it with a custom high‑quality setting, -/// resets to the default setting, and reads it again. +/// Demonstrates how resetting to its default (NormalQuality) restores the original CPU consumption pattern during barcode processing. /// class Program { /// - /// Entry point of the example. Generates a barcode, applies custom quality settings, - /// resets them, and performs recognition in both scenarios. + /// Entry point of the example. Generates a sample barcode, measures reading times under different quality settings, + /// resets to defaults, and validates the performance consistency. /// static void Main() { - // Generate a simple Code128 barcode and store it in a memory stream. - using (var memoryStream = new MemoryStream()) + // Define the path for the generated barcode image + string imagePath = "sample_barcode.png"; + + // Generate a Code128 barcode and save it to the specified path + GenerateBarcode(imagePath); + + // Verify that the barcode image was created successfully + if (!File.Exists(imagePath)) { - // Create a barcode generator for Code128 with the text "Test123". - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123")) - { - // Save the barcode image as PNG into the memory stream. - generator.Save(memoryStream, BarCodeImageFormat.Png); - } + Console.WriteLine($"Failed to generate barcode image at '{imagePath}'."); + return; + } - // Prepare the stream for reading by resetting its position. - memoryStream.Position = 0; + // Measure reading time using the default NormalQuality settings + long defaultTime = MeasureReadingTime(imagePath, QualitySettings.NormalQuality); + Console.WriteLine($"Reading with NormalQuality: {defaultTime} ms"); - // Create a barcode reader for the generated image, specifying Code128 as the decode type. - using (var reader = new BarCodeReader(memoryStream, DecodeType.Code128)) - { - // Apply a non‑default quality setting (more CPU intensive). - reader.QualitySettings = QualitySettings.HighQuality; - Console.WriteLine($"Custom Quality - BarcodeQuality: {reader.QualitySettings.BarcodeQuality}"); + // Measure reading time using the HighPerformance preset (lower quality, higher speed) + long highPerfTime = MeasureReadingTime(imagePath, QualitySettings.HighPerformance); + Console.WriteLine($"Reading with HighPerformance: {highPerfTime} ms"); - // Perform recognition with the custom high‑quality settings. - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"Read with custom quality: {result.CodeText}"); - } + // Reset to the default NormalQuality settings and measure again + long resetTime = MeasureReadingTime(imagePath, QualitySettings.NormalQuality); + Console.WriteLine($"Reading after reset to NormalQuality: {resetTime} ms"); - // Reset quality settings to the default preset. - reader.QualitySettings = QualitySettings.NormalQuality; - Console.WriteLine($"After reset - BarcodeQuality: {reader.QualitySettings.BarcodeQuality}"); + // Simple validation: the reset time should be close to the original default time + long diff = Math.Abs(resetTime - defaultTime); + Console.WriteLine($"Difference after reset: {diff} ms"); + } - // Reset the stream position to read the image again. - memoryStream.Position = 0; + /// + /// Generates a Code128 barcode image with the provided text and saves it to the given file path. + /// + /// The file system path where the barcode image will be saved. + static void GenerateBarcode(string path) + { + // Initialize the barcode generator with Code128 symbology and sample data + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + { + // Save the generated barcode image using default parameters + generator.Save(path); + } + } + + /// + /// Measures the time required to read barcodes from an image using a specific preset. + /// + /// Path to the barcode image file. + /// The quality preset to apply during reading. + /// The elapsed time in milliseconds. + static long MeasureReadingTime(string imagePath, QualitySettings settings) + { + var stopwatch = new Stopwatch(); - // Perform recognition with the default quality settings. - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"Read after reset: {result.CodeText}"); - } + // Initialize the barcode reader for Code128 symbology + using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + { + // Apply the specified quality settings to the reader + reader.QualitySettings = settings; + + // Start timing the read operation + stopwatch.Start(); + + // Iterate through all detected barcodes + foreach (var result in reader.ReadBarCodes()) + { + // Output the detected code text to ensure processing occurs + Console.WriteLine($"Detected: {result.CodeText}"); } + + // Stop timing after processing completes + stopwatch.Stop(); } + + // Return the total elapsed time in milliseconds + return stopwatch.ElapsedMilliseconds; } } \ No newline at end of file diff --git a/barcode-recognition-performance/validate-that-setting-allowincorrectbarcodes-to-true-does-not-affect-confidence-of-correctly-decoded-barcodes.cs b/barcode-recognition-performance/validate-that-setting-allowincorrectbarcodes-to-true-does-not-affect-confidence-of-correctly-decoded-barcodes.cs index b0ed3a4..00c5f50 100644 --- a/barcode-recognition-performance/validate-that-setting-allowincorrectbarcodes-to-true-does-not-affect-confidence-of-correctly-decoded-barcodes.cs +++ b/barcode-recognition-performance/validate-that-setting-allowincorrectbarcodes-to-true-does-not-affect-confidence-of-correctly-decoded-barcodes.cs @@ -1,85 +1,97 @@ // Title: Validate AllowIncorrectBarcodes does not affect confidence of correct barcodes -// Description: Demonstrates generating a Code128 barcode, reading it with default settings and with AllowIncorrectBarcodes enabled, and comparing confidence values. +// Description: Demonstrates generating a Code128 barcode, reading it with default settings and with AllowIncorrectBarcodes enabled, and confirming that confidence remains unchanged for a valid barcode. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating how to configure QualitySettings such as AllowIncorrectBarcodes. It shows usage of BarcodeGenerator, BarCodeReader, and BarCodeConfidence to compare recognition results. Developers often need to ensure that enabling tolerance for incorrect barcodes does not degrade confidence for valid codes, a common requirement in batch scanning and validation pipelines. // Prompt: Validate that setting AllowIncorrectBarcodes to true does not affect confidence of correctly decoded barcodes. -// Tags: barcode symbology, operation type, output format, key api classes used +// Tags: code128, barcode generation, barcode recognition, confidence, allowincorrectbarcodes, aspnet, aspnetcore, aspose.barcode using System; using System.IO; +using System.Linq; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates that enabling AllowIncorrectBarcodes does not change the confidence of correctly decoded barcodes. +/// Example program that validates the effect of the AllowIncorrectBarcodes quality setting on confidence values +/// for correctly decoded Code128 barcodes. /// class Program { /// - /// Entry point. Generates a barcode, reads it with default and altered settings, and compares confidence values. + /// Entry point of the example. Generates a barcode, reads it with two different settings, + /// and verifies that the confidence values are identical. /// static void Main() { - // Define the data to encode in the barcode + // Define the barcode text (Code128 with a valid checksum) const string codeText = "1234567890"; - // Use a memory stream to avoid file I/O - using (var ms = new MemoryStream()) + // Generate the barcode image and store it in a byte array + byte[] barcodeBytes; + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - // ------------------------------------------------- - // Generate a Code128 barcode and write it to the stream - // ------------------------------------------------- - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + using (var ms = new MemoryStream()) { - // Save the barcode as a PNG image into the memory stream generator.Save(ms, BarCodeImageFormat.Png); + barcodeBytes = ms.ToArray(); } + } - // Reset the stream position so it can be read from the beginning - ms.Position = 0; - - // ------------------------------------------------- - // Read the barcode with default settings (AllowIncorrectBarcodes = false) - // ------------------------------------------------- - BarCodeConfidence confidenceDefault = BarCodeConfidence.None; + // ----------------------------------------------------------------- + // Read the barcode with default settings (AllowIncorrectBarcodes = false) + // ----------------------------------------------------------------- + BarCodeConfidence confidenceDefault = BarCodeConfidence.None; + using (var ms = new MemoryStream(barcodeBytes)) + { using (var reader = new BarCodeReader(ms, DecodeType.Code128)) { - foreach (BarCodeResult result in reader.ReadBarCodes()) + var result = reader.ReadBarCodes().FirstOrDefault(); + if (result != null) { confidenceDefault = result.Confidence; - Console.WriteLine($"Default AllowIncorrectBarcodes: {confidenceDefault}"); + Console.WriteLine($"Default AllowIncorrectBarcodes = false, Confidence = {confidenceDefault}"); + } + else + { + Console.WriteLine("No barcode detected with default settings."); } } + } - // Reset the stream again for the second read operation - ms.Position = 0; - - // ------------------------------------------------- - // Read the same barcode with AllowIncorrectBarcodes set to true - // ------------------------------------------------- - BarCodeConfidence confidenceAllow = BarCodeConfidence.None; + // ----------------------------------------------------------------- + // Read the same barcode with AllowIncorrectBarcodes set to true + // ----------------------------------------------------------------- + BarCodeConfidence confidenceAllow = BarCodeConfidence.None; + using (var ms = new MemoryStream(barcodeBytes)) + { using (var reader = new BarCodeReader(ms, DecodeType.Code128)) { - // Enable the option that allows reading of incorrect barcodes + // Enable recognition of incorrect barcodes (should not affect a correct one) reader.QualitySettings.AllowIncorrectBarcodes = true; - foreach (BarCodeResult result in reader.ReadBarCodes()) + var result = reader.ReadBarCodes().FirstOrDefault(); + if (result != null) { confidenceAllow = result.Confidence; - Console.WriteLine($"AllowIncorrectBarcodes = true: {confidenceAllow}"); + Console.WriteLine($"AllowIncorrectBarcodes = true, Confidence = {confidenceAllow}"); + } + else + { + Console.WriteLine("No barcode detected with AllowIncorrectBarcodes = true."); } } + } - // ------------------------------------------------- - // Compare the confidence values obtained from both reads - // ------------------------------------------------- - if (confidenceDefault == confidenceAllow) - { - Console.WriteLine("Confidence is unchanged when AllowIncorrectBarcodes is true."); - } - else - { - Console.WriteLine("Confidence differs after setting AllowIncorrectBarcodes to true."); - } + // ----------------------------------------------------------------- + // Validate that the confidence values are equal and non‑zero + // ----------------------------------------------------------------- + if (confidenceDefault == confidenceAllow && confidenceDefault != BarCodeConfidence.None) + { + Console.WriteLine("Validation passed: confidence is unchanged when AllowIncorrectBarcodes is true."); + } + else + { + Console.WriteLine("Validation failed: confidence differs or barcode not recognized."); } } } \ No newline at end of file diff --git a/barcode-recognition-performance/validate-that-setting-both-useminimalxdimension-and-allowincorrectbarcodes-together-does-not-cause-conflicts.cs b/barcode-recognition-performance/validate-that-setting-both-useminimalxdimension-and-allowincorrectbarcodes-together-does-not-cause-conflicts.cs index f2ca6c5..9eecc68 100644 --- a/barcode-recognition-performance/validate-that-setting-both-useminimalxdimension-and-allowincorrectbarcodes-together-does-not-cause-conflicts.cs +++ b/barcode-recognition-performance/validate-that-setting-both-useminimalxdimension-and-allowincorrectbarcodes-together-does-not-cause-conflicts.cs @@ -1,73 +1,72 @@ // Title: Validate UseMinimalXDimension with AllowIncorrectBarcodes -// Description: Demonstrates generating a Code128 barcode and reading it while both UseMinimalXDimension and AllowIncorrectBarcodes settings are enabled, ensuring no conflicts arise. +// Description: Demonstrates generating a Code128 barcode, then reading it while configuring QualitySettings to use minimal X dimension and allow incorrect barcodes, confirming no conflicts. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the interaction between the BarcodeGenerator, BarCodeReader, and QualitySettings classes, which developers commonly use to create barcodes, customize decoding parameters, and handle imperfect scans. Typical use cases include validating decoding options, optimizing scan performance, and ensuring tolerant reading of barcodes in real‑world applications. // Prompt: Validate that setting both UseMinimalXDimension and AllowIncorrectBarcodes together does not cause conflicts. -// Tags: barcode, code128, generation, recognition, minimalxdimension, allowincorrectbarcodes, aspnet +// Tags: code128, barcode generation, barcode recognition, qualitysettings, useminimalxdimension, allowincorrectbarcodes, bitmap using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Demonstrates barcode generation and reading with specific quality settings. +/// Example program that generates a Code128 barcode, then reads it with specific QualitySettings +/// to verify that UseMinimalXDimension and AllowIncorrectBarcodes can be used together without conflict. /// class Program { /// - /// Entry point: generates a Code128 barcode, saves it, and reads it using minimal X dimension and allowing incorrect barcodes. + /// Entry point of the example. Generates a barcode image in memory, configures the reader, + /// and attempts to decode the barcode while reporting the outcome. /// static void Main() { - const string imagePath = "code128.png"; - - // Generate a simple Code128 barcode and save it as PNG + // Create a barcode generator for Code128 with sample data using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - generator.Save(imagePath, BarCodeImageFormat.Png); - } + // Generate the barcode image as a Bitmap object (in memory) + using (Bitmap barcodeImage = generator.GenerateBarCodeImage()) + { + // Initialize a barcode reader for the generated image, specifying the expected decode type + using (var reader = new BarCodeReader(barcodeImage, DecodeType.Code128)) + { + // Configure QualitySettings: + // - UseMinimalXDimension: let the reader choose the smallest possible X dimension + // - AllowIncorrectBarcodes: enable tolerant reading of imperfect barcodes + reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; + reader.QualitySettings.AllowIncorrectBarcodes = true; - // Verify that the barcode image was successfully created - if (!File.Exists(imagePath)) - { - Console.WriteLine($"Failed to create barcode image at '{imagePath}'."); - return; - } + try + { + // Attempt to read all barcodes from the image + BarCodeResult[] results = reader.ReadBarCodes(); - // Read the barcode with both UseMinimalXDimension and AllowIncorrectBarcodes enabled - using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) - { - // Configure recognition quality settings - reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - reader.QualitySettings.MinimalXDimension = 2f; // minimal element size in pixels - reader.QualitySettings.AllowIncorrectBarcodes = true; + // Check if any barcodes were detected + if (results.Length == 0) + { + Console.WriteLine("No barcode detected."); + } + else + { + // Output details of each detected barcode + foreach (var result in results) + { + Console.WriteLine($"Detected Type: {result.CodeType}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + } - try - { - // Perform barcode reading - var results = reader.ReadBarCodes(); - - // Process and display results - if (results.Length == 0) - { - Console.WriteLine("No barcode detected."); - } - else - { - foreach (var result in results) + // Indicate successful reading without conflicts + Console.WriteLine("Reading succeeded without conflicts."); + } + } + catch (Exception ex) { - Console.WriteLine($"Detected Type: {result.CodeType}"); - Console.WriteLine($"CodeText: {result.CodeText}"); - Console.WriteLine($"Confidence: {result.Confidence}"); + // Report any errors that occurred during reading (including potential conflicts) + Console.WriteLine($"Error during barcode reading: {ex.Message}"); } } - - Console.WriteLine("Reading completed without conflicts."); - } - catch (Exception ex) - { - // Handle any errors that occur during reading - Console.WriteLine($"An error occurred during barcode reading: {ex.Message}"); } } } diff --git a/barcode-recognition-performance/validate-that-setting-minimalxdimension-higher-than-xdimension-filters-out-valid-barcodes-unintentionally.cs b/barcode-recognition-performance/validate-that-setting-minimalxdimension-higher-than-xdimension-filters-out-valid-barcodes-unintentionally.cs index 220cf24..2fb4980 100644 --- a/barcode-recognition-performance/validate-that-setting-minimalxdimension-higher-than-xdimension-filters-out-valid-barcodes-unintentionally.cs +++ b/barcode-recognition-performance/validate-that-setting-minimalxdimension-higher-than-xdimension-filters-out-valid-barcodes-unintentionally.cs @@ -1,7 +1,8 @@ // Title: Minimal XDimension Filtering Demo -// Description: Demonstrates how setting MinimalXDimension higher than the barcode's XDimension can prevent detection of otherwise valid barcodes. +// Description: Demonstrates how setting MinimalXDimension higher than the barcode's XDimension can unintentionally filter out a valid Code128 barcode. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes and BarCodeReader with QualitySettings for decoding. Developers often need to adjust XDimension settings to handle low‑resolution scans, and this snippet illustrates the impact of MinimalXDimension on detection results. // Prompt: Validate that setting MinimalXDimension higher than XDimension filters out valid barcodes unintentionally. -// Tags: barcode, code128, xdimension, minimalxdimension, generation, recognition, aspose.barcode +// Tags: code128, generation, recognition, png, minimalxdimension, xdimension using System; using System.IO; @@ -10,87 +11,87 @@ using Aspose.BarCode.BarCodeRecognition; /// -/// Example program that generates a Code128 barcode and shows how MinimalXDimension -/// influences barcode recognition. It first sets MinimalXDimension higher than the -/// actual XDimension (causing the barcode to be missed) and then lower (allowing detection). +/// Example program that generates a Code128 barcode, reads it with default settings, +/// then attempts to read it with a higher MinimalXDimension to demonstrate filtering behavior. /// class Program { /// - /// Entry point of the example. Generates a barcode image, then attempts to read it - /// with different MinimalXDimension settings to illustrate their effect. + /// Entry point of the example. Generates a barcode, performs two reads, and cleans up the temporary file. /// static void Main() { - const string imagePath = "barcode.png"; + // Define a temporary file path for the generated barcode image. + string imagePath = Path.Combine(Path.GetTempPath(), "sample_barcode.png"); - // ------------------------------------------------------------ - // Generate a simple Code128 barcode with a small XDimension (module size) - // ------------------------------------------------------------ - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // ------------------------------------------------- + // Generate a Code128 barcode with a specific XDimension. + // ------------------------------------------------- + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Set module size to 1 point (XDimension) - generator.Parameters.Barcode.XDimension.Point = 1f; - - // Disable automatic sizing so the XDimension value is respected - generator.Parameters.AutoSizeMode = AutoSizeMode.None; - - // Save the generated barcode image to disk - generator.Save(imagePath); + // Set the module size (XDimension) to 2 points. + // AutoSizeMode defaults to None, so this value is applied directly. + generator.Parameters.Barcode.XDimension.Point = 2f; + // Save the barcode image as PNG. + generator.Save(imagePath, BarCodeImageFormat.Png); } - // ------------------------------------------------------------ - // Verify that the barcode image was successfully created - // ------------------------------------------------------------ + // Verify that the image file was created successfully. if (!File.Exists(imagePath)) { Console.WriteLine("Failed to create barcode image."); return; } - // ------------------------------------------------------------ - // Attempt to read the barcode with MinimalXDimension set higher than the actual XDimension - // Expected outcome: barcode is not detected because the minimal requirement is not met - // ------------------------------------------------------------ - Console.WriteLine("Reading with MinimalXDimension = 2 (higher than XDimension 1):"); - using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + // ------------------------------------------------- + // First read: use default reader settings (should detect the barcode). + // ------------------------------------------------- + using (BarCodeReader defaultReader = new BarCodeReader(imagePath, DecodeType.Code128)) { - // Instruct the reader to respect MinimalXDimension during detection - reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - - // Set MinimalXDimension to a value larger than the barcode's XDimension - reader.QualitySettings.MinimalXDimension = 2f; - bool found = false; - foreach (BarCodeResult result in reader.ReadBarCodes()) + foreach (BarCodeResult result in defaultReader.ReadBarCodes()) { - Console.WriteLine($"Detected: {result.CodeText}"); + Console.WriteLine($"[Default] Detected barcode: {result.CodeText}"); found = true; } - if (!found) - Console.WriteLine("No barcode detected (as expected)."); + { + Console.WriteLine("[Default] No barcode detected."); + } } - // ------------------------------------------------------------ - // Now read the same image with a lower MinimalXDimension - // Expected outcome: barcode is detected because the requirement is satisfied - // ------------------------------------------------------------ - Console.WriteLine("\nReading with MinimalXDimension = 0.5 (lower than XDimension 1):"); - using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + // ------------------------------------------------- + // Second read: configure MinimalXDimension higher than the generated XDimension. + // ------------------------------------------------- + using (BarCodeReader minimalReader = new BarCodeReader(imagePath, DecodeType.Code128)) { - reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - reader.QualitySettings.MinimalXDimension = 0.5f; + // Enable MinimalXDimension mode. + minimalReader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; + // Set a threshold of 5 points, which exceeds the generated 2‑point module size. + minimalReader.QualitySettings.MinimalXDimension = 5f; bool found = false; - foreach (BarCodeResult result in reader.ReadBarCodes()) + foreach (BarCodeResult result in minimalReader.ReadBarCodes()) { - Console.WriteLine($"Detected: {result.CodeText}"); + Console.WriteLine($"[MinimalXDimension] Detected barcode: {result.CodeText}"); found = true; } - if (!found) - Console.WriteLine("No barcode detected (unexpected)."); + { + Console.WriteLine("[MinimalXDimension] No barcode detected (filtering out valid barcode)."); + } + } + + // ------------------------------------------------- + // Clean up: delete the temporary barcode image file. + // ------------------------------------------------- + try + { + File.Delete(imagePath); + } + catch + { + // Suppress any exceptions during cleanup. } } } \ No newline at end of file diff --git a/barcode-recognition-performance/verify-that-switching-presets-mid-batch-does-not-corrupt-previously-obtained-results.cs b/barcode-recognition-performance/verify-that-switching-presets-mid-batch-does-not-corrupt-previously-obtained-results.cs index 9295e03..1c3da09 100644 --- a/barcode-recognition-performance/verify-that-switching-presets-mid-batch-does-not-corrupt-previously-obtained-results.cs +++ b/barcode-recognition-performance/verify-that-switching-presets-mid-batch-does-not-corrupt-previously-obtained-results.cs @@ -1,95 +1,106 @@ -// Title: Barcode generation and recognition with mid‑batch preset switching -// Description: Demonstrates creating Code128 barcodes, then reading them while changing quality presets partway through the batch to ensure earlier results remain unaffected. +// Title: Verify barcode preset switching does not affect earlier results +// Description: Demonstrates generating a batch of barcodes, changing generator presets mid‑batch, and confirming that previously generated barcodes remain decodable. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, illustrating how to use BarcodeGenerator, adjust Parameters, and employ BarCodeReader for validation. Developers often need to modify barcode appearance or settings on the fly while processing multiple items; this snippet shows safe preset changes without corrupting earlier outputs. // Prompt: Verify that switching presets mid‑batch does not corrupt previously obtained results. -// Tags: barcode, code128, generation, recognition, qualitysettings, batch, preset +// Tags: barcode generation, barcode recognition, preset switching, batch processing, csharp, aspose.barcode using System; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Example program that generates a set of Code128 barcodes, saves them as PNG files, -/// and then reads them back while switching the quality preset mid‑batch to verify -/// that earlier decoded results are not affected. +/// Demonstrates batch barcode generation with mid‑batch preset changes and validates decoding. /// class Program { /// - /// Entry point of the application. + /// Entry point. Generates barcodes, alters presets after the third item, saves them, and verifies decoding. /// static void Main() { - // Prepare a temporary folder for barcode images - string folder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); - if (!Directory.Exists(folder)) + // Prepare output folder for generated barcode images + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(outputFolder)) { - Directory.CreateDirectory(folder); + Directory.CreateDirectory(outputFolder); } - // Sample code texts to encode - string[] codeTexts = { "123456789012", "ABCDEF", "9876543210", "Test123", "HelloWorld" }; - string[] filePaths = new string[codeTexts.Length]; + // Define a small batch of barcodes with their symbology and data + var batch = new (BaseEncodeType Encode, string CodeText)[] + { + (EncodeTypes.Code128, "ABC123"), + (EncodeTypes.QR, "https://example.com"), + (EncodeTypes.DataMatrix, "DM12345"), + (EncodeTypes.Pdf417, "PDF417_SAMPLE"), + (EncodeTypes.Aztec, "AZTEC_TEXT") + }; - // ------------------------------------------------- - // Generate barcode images and store their file paths - // ------------------------------------------------- - for (int i = 0; i < codeTexts.Length; i++) + // Generate each barcode, switching presets after the third item (index >= 3) + for (int i = 0; i < batch.Length; i++) { - string filePath = Path.Combine(folder, $"barcode_{i}.png"); - filePaths[i] = filePath; + var (encode, text) = batch[i]; + string filePath = Path.Combine(outputFolder, $"barcode_{i}.png"); - // Create a barcode generator for Code128 and save the image - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeTexts[i])) + using (var generator = new BarcodeGenerator(encode, text)) { - generator.Save(filePath); + // Apply custom preset only to the later barcodes + if (i >= 3) + { + // Example preset change: increase X-dimension and set bar color to red + generator.Parameters.Barcode.XDimension.Point = 3f; + generator.Parameters.Barcode.BarColor = Color.Red; + } + + // Save the generated barcode image as PNG + generator.Save(filePath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode {i} to {filePath}"); } } - // ------------------------------------------------- - // Read barcodes back, switching quality presets mid‑batch - // ------------------------------------------------- - for (int i = 0; i < filePaths.Length; i++) + // Verify that each saved barcode decodes back to its original text + bool allMatch = true; + for (int i = 0; i < batch.Length; i++) { - // Initialize a reader for the current file - using (var reader = new BarCodeReader(filePaths[i], DecodeType.Code128)) + var expectedText = batch[i].CodeText; + string filePath = Path.Combine(outputFolder, $"barcode_{i}.png"); + + if (!File.Exists(filePath)) { - // Switch preset after the second barcode (mid‑batch) - if (i >= 2) - { - reader.QualitySettings = QualitySettings.HighQuality; - } - else + Console.WriteLine($"Error: File not found - {filePath}"); + allMatch = false; + continue; + } + + using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes)) + { + var results = reader.ReadBarCodes(); + if (results.Length == 0) { - reader.QualitySettings = QualitySettings.NormalQuality; + Console.WriteLine($"Failed to read barcode {i} from {filePath}"); + allMatch = false; + continue; } - bool matched = false; - - // Iterate through all detected barcodes in the image - foreach (var result in reader.ReadBarCodes()) + // Use the first detected result for comparison + var result = results[0]; + if (result.CodeText != expectedText) { - if (result.CodeText == codeTexts[i]) - { - matched = true; - Console.WriteLine($"File {i}: Success - decoded '{result.CodeText}'."); - } - else - { - Console.WriteLine($"File {i}: Mismatch - expected '{codeTexts[i]}', got '{result.CodeText}'."); - } + Console.WriteLine($"Mismatch for barcode {i}: expected '{expectedText}', got '{result.CodeText}'"); + allMatch = false; } - - // If no barcode was detected, report it - if (!matched) + else { - Console.WriteLine($"File {i}: No barcode detected."); + Console.WriteLine($"Barcode {i} decoded correctly: '{result.CodeText}'"); } } } - // Cleanup (optional) - // foreach (var path in filePaths) { File.Delete(path); } - // Directory.Delete(folder); + // Summarize verification outcome + Console.WriteLine(allMatch + ? "All barcodes decoded correctly. Switching presets did not corrupt results." + : "Some barcodes did not decode as expected. Check the output above."); } } \ No newline at end of file diff --git a/barcode-recognition-performance/write-documentation-examples-demonstrating-how-to-switch-between-highperformance-and-highquality-presets.cs b/barcode-recognition-performance/write-documentation-examples-demonstrating-how-to-switch-between-highperformance-and-highquality-presets.cs index ad0f2ce..bc16e47 100644 --- a/barcode-recognition-performance/write-documentation-examples-demonstrating-how-to-switch-between-highperformance-and-highquality-presets.cs +++ b/barcode-recognition-performance/write-documentation-examples-demonstrating-how-to-switch-between-highperformance-and-highquality-presets.cs @@ -1,7 +1,8 @@ // Title: Switching between HighPerformance and HighQuality barcode reading presets -// Description: Demonstrates generating a Code128 barcode, then reading it twice using Aspose.BarCode's HighPerformance and HighQuality quality settings. +// Description: Demonstrates how to read a barcode using Aspose.BarCode's QualitySettings presets for performance versus quality. +// Category-Description: This example belongs to the Aspose.BarCode reading configuration category, illustrating the use of BarCodeReader with different QualitySettings (HighPerformance and HighQuality). Developers often need to balance speed and accuracy when scanning barcodes; this snippet shows how to toggle presets, a common requirement in batch processing or real‑time scanning scenarios. // Prompt: Write documentation examples demonstrating how to switch between HighPerformance and HighQuality presets. -// Tags: barcode symbology, generation, recognition, highperformance, highquality, aspnet, csharp +// Tags: barcode symbology, reading preset, qualitysettings, highperformance, highquality, aspose.barcode, png using System; using System.IO; @@ -10,55 +11,74 @@ using Aspose.BarCode.BarCodeRecognition; /// -/// Example program that shows how to generate a barcode and read it using different quality presets. +/// Example program that creates a Code128 barcode, then reads it twice using +/// different presets (HighPerformance and HighQuality). /// class Program { /// - /// Entry point. Generates a Code128 barcode image, then reads it with HighPerformance and HighQuality settings. + /// Entry point of the example. Generates a barcode image, reads it with two + /// different quality presets, and cleans up the temporary file. /// static void Main() { - // Define the full path for the generated barcode image - string imagePath = Path.Combine(Directory.GetCurrentDirectory(), "sample.png"); + // Define the output directory and full path for the temporary barcode image. + string outputDir = Directory.GetCurrentDirectory(); + string barcodePath = Path.Combine(outputDir, "sample.png"); - // ------------------------------------------------- - // Generate a Code128 barcode and save it to a PNG file - // ------------------------------------------------- - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Generate a simple Code128 barcode and save it as PNG. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC")) { - // Save the barcode image to the specified path - generator.Save(imagePath); + generator.Save(barcodePath, BarCodeImageFormat.Png); } - // ------------------------------------------------- - // Read the barcode using the HighPerformance preset - // ------------------------------------------------- - using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + // Verify that the barcode image was successfully created. + if (!File.Exists(barcodePath)) { - // Set the reader to prioritize speed over accuracy + Console.WriteLine("Failed to create barcode image."); + return; + } + + // -------------------------------------------------------------------- + // Read the barcode using the HighPerformance preset (faster, lower accuracy). + // -------------------------------------------------------------------- + Console.WriteLine("Reading with QualitySettings.HighPerformance:"); + using (var reader = new BarCodeReader(barcodePath, DecodeType.Code128)) + { + // Apply the HighPerformance preset. reader.QualitySettings = QualitySettings.HighPerformance; - // Iterate through all detected barcodes and output their text - foreach (var result in reader.ReadBarCodes()) + // Iterate through all detected barcodes and output their type and text. + foreach (BarCodeResult result in reader.ReadBarCodes()) { - Console.WriteLine("HighPerformance: " + result.CodeText); + Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}"); } } - // ------------------------------------------------- - // Read the same barcode using the HighQuality preset - // ------------------------------------------------- - using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + // -------------------------------------------------------------------- + // Read the same barcode using the HighQuality preset (slower, higher accuracy). + // -------------------------------------------------------------------- + Console.WriteLine("Reading with QualitySettings.HighQuality:"); + using (var reader = new BarCodeReader(barcodePath, DecodeType.Code128)) { - // Set the reader to prioritize accuracy over speed + // Apply the HighQuality preset. reader.QualitySettings = QualitySettings.HighQuality; - // Iterate through all detected barcodes and output their text - foreach (var result in reader.ReadBarCodes()) + // Iterate through all detected barcodes and output their type and text. + foreach (BarCodeResult result in reader.ReadBarCodes()) { - Console.WriteLine("HighQuality: " + result.CodeText); + Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}"); } } + + // Optional clean‑up: delete the temporary barcode image. + try + { + File.Delete(barcodePath); + } + catch + { + // Ignored – file may be in use or deletion may fail on some platforms. + } } } \ No newline at end of file diff --git a/barcode-recognition-performance/write-integration-tests-confirming-barcode-recognition-succeeds-after-toggling-useminimalxdimension-correctly.cs b/barcode-recognition-performance/write-integration-tests-confirming-barcode-recognition-succeeds-after-toggling-useminimalxdimension-correctly.cs index b31f70a..2eb4fca 100644 --- a/barcode-recognition-performance/write-integration-tests-confirming-barcode-recognition-succeeds-after-toggling-useminimalxdimension-correctly.cs +++ b/barcode-recognition-performance/write-integration-tests-confirming-barcode-recognition-succeeds-after-toggling-useminimalxdimension-correctly.cs @@ -1,85 +1,87 @@ -// Title: Barcode recognition with and without UseMinimalXDimension -// Description: Demonstrates generating a Code128 barcode and testing recognition using default quality settings versus minimal X dimension mode. +// Title: Barcode generation and recognition with UseMinimalXDimension +// Description: Demonstrates generating a Code128 barcode with a small XDimension and recognizing it using default settings and the UseMinimalXDimension mode. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showcasing the BarcodeGenerator, BarCodeReader, and QualitySettings classes. It illustrates typical scenarios where developers need to create barcodes with fine module sizes and reliably decode them, especially when minimal XDimension detection is required. Useful for integration testing of barcode pipelines. // Prompt: Write integration tests confirming barcode recognition succeeds after toggling UseMinimalXDimension correctly. -// Tags: barcode, code128, recognition, minimalxdimension, qualitysettings, integration-test +// Tags: code128, barcode, generation, recognition, minimalxdimension, aspose.barcode, csharp using System; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; /// -/// Example program that generates a Code128 barcode and runs two integration tests: -/// 1) Recognition with default quality settings. -/// 2) Recognition with UseMinimalXDimension enabled. +/// Demonstrates barcode generation and recognition using Aspose.BarCode, focusing on the UseMinimalXDimension setting. /// class Program { /// - /// Entry point. Generates a barcode image in memory and validates recognition under different quality configurations. + /// Entry point of the example. Generates a barcode, saves it, and reads it back with default and minimal XDimension settings. /// static void Main() { - // Create a Code128 barcode with sample text. - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123")) - { - // Generate the barcode image in memory. - using (Bitmap barcodeImage = generator.GenerateBarCodeImage()) - { - // ---------- Test 1: Default recognition settings ---------- - using (BarCodeReader defaultReader = new BarCodeReader(barcodeImage, DecodeType.Code128)) - { - // Apply the default QualitySettings (NormalQuality). - defaultReader.QualitySettings = QualitySettings.NormalQuality; + const string barcodeText = "Test123"; + const string filePath = "barcode.png"; - Console.WriteLine("Reading with default QualitySettings..."); - bool defaultSuccess = false; + // Clean up any previous file to ensure a fresh start. + if (File.Exists(filePath)) + { + File.Delete(filePath); + } - // Iterate through all detected barcodes. - foreach (BarCodeResult result in defaultReader.ReadBarCodes()) - { - Console.WriteLine($"Detected Type: {result.CodeTypeName}, CodeText: {result.CodeText}"); - defaultSuccess = true; - } + // ---------- Barcode Generation ---------- + // Create a Code128 barcode with a very small XDimension (module size). + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, barcodeText)) + { + // Set the XDimension to 1 point to make minimal XDimension detection relevant. + generator.Parameters.Barcode.XDimension.Point = 1f; + // Save the generated barcode as a PNG image. + generator.Save(filePath, BarCodeImageFormat.Png); + } - // Warn if no barcode was detected. - if (!defaultSuccess) - { - Console.WriteLine("Warning: No barcode detected with default settings."); - } - } + // Verify that the image file was successfully created. + if (!File.Exists(filePath)) + { + Console.WriteLine("Failed to create barcode image."); + return; + } - // ---------- Test 2: UseMinimalXDimension mode ---------- - using (BarCodeReader minimalReader = new BarCodeReader(barcodeImage, DecodeType.Code128)) + // ---------- Default Recognition (no XDimension mode set) ---------- + using (var readerDefault = new BarCodeReader(filePath, DecodeType.Code128)) + { + // Read all barcodes from the image using default settings. + var results = readerDefault.ReadBarCodes(); + foreach (var result in results) + { + Console.WriteLine($"Default recognition: CodeText = '{result.CodeText}'"); + if (result.CodeText != barcodeText) { - // Start with normal quality settings. - minimalReader.QualitySettings = QualitySettings.NormalQuality; - - // Configure QualitySettings to use minimal X dimension. - minimalReader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; - minimalReader.QualitySettings.MinimalXDimension = 2f; // minimal element size in pixels - - Console.WriteLine("\nReading with UseMinimalXDimension mode (MinimalXDimension = 2)..."); - bool minimalSuccess = false; + Console.WriteLine("Default recognition failed: decoded text does not match original."); + } + } + } - // Iterate through all detected barcodes. - foreach (BarCodeResult result in minimalReader.ReadBarCodes()) - { - Console.WriteLine($"Detected Type: {result.CodeTypeName}, CodeText: {result.CodeText}"); - minimalSuccess = true; - } + // ---------- Recognition with UseMinimalXDimension ---------- + using (var readerMinimal = new BarCodeReader(filePath, DecodeType.Code128)) + { + // Enable the UseMinimalXDimension mode to improve detection of small modules. + readerMinimal.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension; + // Optionally specify the minimal XDimension size (in pixels) expected. + readerMinimal.QualitySettings.MinimalXDimension = 1f; - // Warn if no barcode was detected. - if (!minimalSuccess) - { - Console.WriteLine("Warning: No barcode detected with UseMinimalXDimension settings."); - } + // Read all barcodes from the image using the minimal XDimension settings. + var results = readerMinimal.ReadBarCodes(); + foreach (var result in results) + { + Console.WriteLine($"UseMinimalXDimension recognition: CodeText = '{result.CodeText}'"); + if (result.CodeText != barcodeText) + { + Console.WriteLine("UseMinimalXDimension recognition failed: decoded text does not match original."); } } } - // Indicate that the program completed successfully. - Console.WriteLine("\nIntegration test completed."); + // Optional clean-up: delete the generated barcode image. + // File.Delete(filePath); } } \ No newline at end of file diff --git a/barcode-recognition-performance/write-unit-tests-verifying-that-allowincorrectbarcodes-returns-barcoderesultconfidence-as-null.cs b/barcode-recognition-performance/write-unit-tests-verifying-that-allowincorrectbarcodes-returns-barcoderesultconfidence-as-null.cs index ffa00ba..2e6141e 100644 --- a/barcode-recognition-performance/write-unit-tests-verifying-that-allowincorrectbarcodes-returns-barcoderesultconfidence-as-null.cs +++ b/barcode-recognition-performance/write-unit-tests-verifying-that-allowincorrectbarcodes-returns-barcoderesultconfidence-as-null.cs @@ -1,95 +1,70 @@ // Title: Demonstrate AllowIncorrectBarcodes effect on barcode confidence -// Description: Generates an EAN13 barcode with an incorrect checksum and shows how the AllowIncorrectBarcodes setting influences the Confidence property of BarCodeResult. +// Description: Generates an EAN13 barcode with an incorrect checksum and reads it with AllowIncorrectBarcodes enabled, showing that the confidence value is null (None). +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, illustrating how to use BarcodeGenerator, BarCodeReader, and QualitySettings to handle barcodes with invalid checksums. Developers often need to process imperfect barcodes in bulk scanning scenarios, and this snippet shows the typical API usage for allowing incorrect barcodes while checking the confidence result. // Prompt: Write unit tests verifying that AllowIncorrectBarcodes returns BarCodeResult.Confidence as null. -// Tags: barcode symbology, ean13, allowincorrectbarcodes, confidence, unit testing, aspose.barcode +// Tags: ean13, incorrect checksum, allowincorrectbarcodes, confidence, barcodereader, barcodegenerator, aspnet, csharp using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Example program that creates an EAN13 barcode with an invalid checksum -/// and demonstrates the impact of the AllowIncorrectBarcodes quality setting -/// on the BarCodeResult.Confidence value returned by the reader. +/// Demonstrates reading a barcode with AllowIncorrectBarcodes enabled and verifies that the confidence is null. /// class Program { /// - /// Entry point of the example. Generates a temporary barcode image, - /// runs two recognition scenarios (allowing and disallowing incorrect barcodes), - /// and outputs the results to the console. + /// Entry point. Generates an EAN13 barcode with an invalid checksum, reads it with AllowIncorrectBarcodes set to true, and checks the confidence value. /// static void Main() { - // Prepare a temporary PNG file for the barcode image - string tempPath = Path.Combine(Path.GetTempPath(), "temp_ean13.png"); - - // Create an EAN13 barcode with an incorrect checksum (last digit is wrong) + // Generate a barcode with an intentionally incorrect checksum (EAN13) using (var generator = new BarcodeGenerator(EncodeTypes.EAN13, "1234567890123")) { - generator.Save(tempPath); - } - - // Verify that the file was created - if (!File.Exists(tempPath)) - { - Console.WriteLine("Failed to create barcode image."); - return; - } - - // ------------------------------------------------------------ - // Test 1: AllowIncorrectBarcodes = true - // ------------------------------------------------------------ - using (var reader = new BarCodeReader(tempPath, DecodeType.EAN13)) - { - // Enable recognition of incorrect barcodes - reader.QualitySettings.AllowIncorrectBarcodes = true; - - bool confidenceIsNone = false; - foreach (BarCodeResult result in reader.ReadBarCodes()) + // Create the barcode image in memory + using (var bitmap = generator.GenerateBarCodeImage()) { - // When AllowIncorrectBarcodes is true, the engine should return a result - // with Confidence set to BarCodeConfidence.None (value 0) - confidenceIsNone = result.Confidence == BarCodeConfidence.None; - Console.WriteLine($"Test1 - Confidence: {result.Confidence}"); - } + // Store the image in a memory stream for reading + using (var ms = new MemoryStream()) + { + bitmap.Save(ms, ImageFormat.Png); + ms.Position = 0; // Reset stream position for reading - Console.WriteLine(confidenceIsNone - ? "Test1 passed: Confidence is None as expected." - : "Test1 failed: Confidence is not None."); - } + // Initialize the barcode reader for EAN13 type + using (var reader = new BarCodeReader(ms, DecodeType.EAN13)) + { + // Enable recognition of incorrect barcodes + reader.QualitySettings.AllowIncorrectBarcodes = true; - // ------------------------------------------------------------ - // Test 2: AllowIncorrectBarcodes = false - // ------------------------------------------------------------ - using (var reader = new BarCodeReader(tempPath, DecodeType.EAN13)) - { - // Disable recognition of incorrect barcodes (default behavior) - reader.QualitySettings.AllowIncorrectBarcodes = false; + bool testPassed = false; - bool noResult = true; - foreach (BarCodeResult result in reader.ReadBarCodes()) - { - // With AllowIncorrectBarcodes disabled, the reader should not return any result - noResult = false; - Console.WriteLine($"Test2 - Unexpected result with Confidence: {result.Confidence}"); - } - - Console.WriteLine(noResult - ? "Test2 passed: No result returned as expected." - : "Test2 failed: Result was returned despite AllowIncorrectBarcodes being false."); - } + // Iterate through all detected barcodes + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // When AllowIncorrectBarcodes is true, Confidence should be None (value 0) + if (result.Confidence == BarCodeConfidence.None) + { + testPassed = true; + Console.WriteLine("Test Passed: Confidence is None as expected."); + } + else + { + Console.WriteLine($"Test Failed: Unexpected Confidence value {result.Confidence}."); + } + } - // Clean up temporary file - try - { - File.Delete(tempPath); - } - catch - { - // Ignore any cleanup errors + // If no results were returned, the test fails + if (!testPassed) + { + Console.WriteLine("Test Failed: No barcode result was returned."); + } + } + } + } } } } \ No newline at end of file diff --git a/barcode-recognition-performance/write-wrapper-that-logs-both-recognition-time-and-cpu-usage-for-each-processed-image.cs b/barcode-recognition-performance/write-wrapper-that-logs-both-recognition-time-and-cpu-usage-for-each-processed-image.cs index 8eaf617..0139f7c 100644 --- a/barcode-recognition-performance/write-wrapper-that-logs-both-recognition-time-and-cpu-usage-for-each-processed-image.cs +++ b/barcode-recognition-performance/write-wrapper-that-logs-both-recognition-time-and-cpu-usage-for-each-processed-image.cs @@ -1,94 +1,103 @@ -// Title: Barcode generation and recognition with timing and CPU usage logging -// Description: Demonstrates generating sample barcodes, then recognizing them while logging the elapsed time and CPU consumption for each image. +// Title: Barcode Generation and Recognition with Performance Logging +// Description: Generates Code128 barcodes, saves them as PNG files, then recognizes each image while logging recognition time and CPU usage. +// Category-Description: This example demonstrates core Aspose.BarCode operations: barcode generation using BarcodeGenerator and barcode recognition using BarCodeReader. It showcases typical use cases such as creating visual barcode assets and processing them in batch while measuring performance metrics—useful for developers needing to benchmark or monitor resource consumption in high‑throughput scanning scenarios. // Prompt: Write a wrapper that logs both recognition time and CPU usage for each processed image. -// Tags: barcode, generation, recognition, timing, cpu usage, aspose.barcode +// Tags: barcode, code128, generation, recognition, performance, logging, aspose.barcode, png using System; -using System.Collections.Generic; -using System.Diagnostics; using System.IO; +using System.Diagnostics; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Example program that creates barcode images, reads them back, and logs -/// both the recognition duration and the CPU time consumed for each image. +/// Demonstrates barcode generation, recognition, and performance logging using Aspose.BarCode. /// class Program { /// - /// Entry point of the application. Generates sample barcodes, then - /// processes each image while measuring performance metrics. + /// Entry point of the example. Generates barcode images, recognizes them, and logs timing metrics. /// static void Main() { - // Define sample barcodes to generate and process - var samples = new List<(BaseEncodeType EncodeType, string CodeText, string FileName)> + // ---------------------------------------------------------------------- + // Setup: create output directory for generated barcode images + // ---------------------------------------------------------------------- + string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + if (!Directory.Exists(outputDir)) { - (EncodeTypes.Code128, "Sample123", "barcode1.png"), - (EncodeTypes.QR, "https://example.com", "barcode2.png"), - (EncodeTypes.DataMatrix, "DataMatrixTest", "barcode3.png") + Directory.CreateDirectory(outputDir); + } + + // ---------------------------------------------------------------------- + // Sample data: list of texts to encode into Code128 barcodes + // ---------------------------------------------------------------------- + string[] sampleTexts = new string[] + { + "Sample001", + "Sample002", + "Sample003", + "Sample004", + "Sample005" }; - // ------------------------------------------------------------ - // Generate barcode images - // ------------------------------------------------------------ - foreach (var sample in samples) + // ---------------------------------------------------------------------- + // Generation: create a PNG barcode image for each sample text + // ---------------------------------------------------------------------- + for (int i = 0; i < sampleTexts.Length; i++) { - // Ensure any existing file is overwritten - if (File.Exists(sample.FileName)) + string filePath = Path.Combine(outputDir, $"barcode_{i + 1}.png"); + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, sampleTexts[i])) { - File.Delete(sample.FileName); - } + // Optional visual parameters for better readability + generator.Parameters.Barcode.XDimension.Point = 2f; + generator.Parameters.Barcode.BarHeight.Point = 40f; - // Create a generator for the specified type and text - using (var generator = new BarcodeGenerator(sample.EncodeType, sample.CodeText)) - { - // Save the generated barcode as a PNG image - generator.Save(sample.FileName, BarCodeImageFormat.Png); + // Save the generated barcode as a PNG file + generator.Save(filePath, BarCodeImageFormat.Png); } } - // ------------------------------------------------------------ - // Process each image: measure recognition time and CPU usage - // ------------------------------------------------------------ - foreach (var sample in samples) + // ---------------------------------------------------------------------- + // Recognition & Logging: process each generated image, measuring time and CPU usage + // ---------------------------------------------------------------------- + foreach (string file in Directory.GetFiles(outputDir, "*.png")) { - // Verify that the image file exists before attempting to read it - if (!File.Exists(sample.FileName)) + if (!File.Exists(file)) { - Console.WriteLine($"File not found: {sample.FileName}"); + Console.WriteLine($"File not found: {file}"); continue; } - // Create a BarCodeReader that attempts to decode all supported types - using (var reader = new BarCodeReader(sample.FileName, DecodeType.AllSupportedTypes)) - { - // Start timing and capture initial CPU usage - var stopwatch = Stopwatch.StartNew(); - var process = Process.GetCurrentProcess(); - var cpuStart = process.TotalProcessorTime; - - // Perform barcode recognition - var results = reader.ReadBarCodes(); + // Capture CPU time before recognition starts + Process currentProcess = Process.GetCurrentProcess(); + TimeSpan cpuStart = currentProcess.TotalProcessorTime; - // Stop timing and capture final CPU usage - stopwatch.Stop(); - var cpuEnd = process.TotalProcessorTime; - var cpuUsed = cpuEnd - cpuStart; + // Capture wall‑clock time before recognition starts + Stopwatch sw = Stopwatch.StartNew(); - // Log the performance metrics and recognition results - Console.WriteLine($"Processing file: {sample.FileName}"); - Console.WriteLine($"Recognition time: {stopwatch.Elapsed.TotalMilliseconds} ms"); - Console.WriteLine($"CPU time used: {cpuUsed.TotalMilliseconds} ms"); - foreach (var result in results) + // Perform barcode recognition using all supported decode types + using (BarCodeReader reader = new BarCodeReader(file, DecodeType.AllSupportedTypes)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) { - Console.WriteLine($" Detected Type: {result.CodeTypeName}"); - Console.WriteLine($" CodeText: {result.CodeText}"); + Console.WriteLine($"File: {Path.GetFileName(file)} | Detected Type: {result.CodeTypeName} | CodeText: {result.CodeText}"); } - Console.WriteLine(); // Blank line for readability } + + // Stop timing measurements + sw.Stop(); + TimeSpan cpuEnd = currentProcess.TotalProcessorTime; + + // Compute elapsed wall‑clock and CPU times in milliseconds + double elapsedMs = sw.Elapsed.TotalMilliseconds; + double cpuMs = (cpuEnd - cpuStart).TotalMilliseconds; + + // Output performance metrics for the current file + Console.WriteLine($"File: {Path.GetFileName(file)} | Recognition Time: {elapsedMs:F2} ms | CPU Time: {cpuMs:F2} ms"); + Console.WriteLine(new string('-', 80)); } } } \ No newline at end of file