diff --git a/barcode-recognition-basics/access-barcoderesultreadingquality-for-each-datamatrix-barcode-and-store-numeric-value-in-database.cs b/barcode-recognition-basics/access-barcoderesultreadingquality-for-each-datamatrix-barcode-and-store-numeric-value-in-database.cs
index 2cec4b8..8b2de57 100644
--- a/barcode-recognition-basics/access-barcoderesultreadingquality-for-each-datamatrix-barcode-and-store-numeric-value-in-database.cs
+++ b/barcode-recognition-basics/access-barcoderesultreadingquality-for-each-datamatrix-barcode-and-store-numeric-value-in-database.cs
@@ -1,78 +1,88 @@
-// Title: DataMatrix ReadingQuality extraction and CSV storage
-// Description: Demonstrates how to read the ReadingQuality property of each DataMatrix barcode and store the values in a CSV file (as a placeholder for a database).
+// Title: Access DataMatrix ReadingQuality and store results
+// Description: Demonstrates generating DataMatrix barcodes, reading their ReadingQuality property, and persisting the values.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showing how to use BarcodeGenerator, BarCodeReader, and BarCodeResult to evaluate barcode quality. Typical use cases include quality assessment for scanning devices, database logging, and automated testing. Developers often need to extract metrics like ReadingQuality for each barcode and store them for analysis.
// Prompt: Access BarCodeResult.ReadingQuality for each DataMatrix barcode and store the numeric value in a database.
-// Tags: datamatrix, readingquality, csv, aspose.barcode, barcode, data extraction, database
+// Tags: datamatrix, readingquality, barcode, generation, recognition, csv, database
using System;
-using System.Collections.Generic;
using System.IO;
-using Aspose.BarCode;
+using System.Collections.Generic;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates extracting ReadingQuality from DataMatrix barcodes and persisting the values.
+/// Generates sample DataMatrix barcodes, reads their ReadingQuality values,
+/// and writes the results to a CSV file (placeholder for database storage).
///
class Program
{
///
- /// Generates a sample DataMatrix barcode, reads its ReadingQuality, and writes the results to a CSV file.
+ /// Entry point of the example. Executes barcode generation, quality extraction,
+ /// and result persistence.
///
static void Main()
{
- // Path for the temporary barcode image
- const string imagePath = "datamatrix.png";
- // Path for the CSV file that will store the reading quality values
- const string csvPath = "reading_quality.csv";
+ // Define sample data for barcode generation.
+ var samples = new List<(string Text, string FileName)>
+ {
+ ("Hello", "datamatrix1.png"),
+ ("1234567890", "datamatrix2.png")
+ };
- // Generate a sample DataMatrix barcode image
- using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "SampleDataMatrix123"))
+ // --------------------------------------------------------------------
+ // Generate DataMatrix barcode images and save them as PNG files.
+ // --------------------------------------------------------------------
+ foreach (var sample in samples)
{
- // Save the generated barcode to a PNG file
- generator.Save(imagePath, BarCodeImageFormat.Png);
+ using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, sample.Text))
+ {
+ // Save the generated barcode image.
+ generator.Save(sample.FileName);
+ }
}
- // List to hold reading quality information for each detected barcode
- var qualities = new List<(int Index, string CodeText, double ReadingQuality)>();
+ // Prepare a collection to hold filename and reading quality pairs.
+ var results = new List<(string FileName, double ReadingQuality)>();
- // Read the barcode(s) from the image using a DataMatrix decoder
- using (var reader = new BarCodeReader(imagePath, DecodeType.DataMatrix))
+ // --------------------------------------------------------------------
+ // Read each generated image, decode DataMatrix barcodes, and capture
+ // the ReadingQuality metric from the BarCodeResult.
+ // --------------------------------------------------------------------
+ foreach (var sample in samples)
{
- int index = 0;
- foreach (var result in reader.ReadBarCodes())
+ if (!File.Exists(sample.FileName))
{
- // Process only DataMatrix barcodes (additional safety check)
- if (result.CodeTypeName.Equals("DataMatrix", StringComparison.OrdinalIgnoreCase))
+ Console.WriteLine($"File not found: {sample.FileName}");
+ continue;
+ }
+
+ using (var reader = new BarCodeReader(sample.FileName, DecodeType.DataMatrix))
+ {
+ foreach (var result in reader.ReadBarCodes())
{
- // Retrieve the ReadingQuality value (double) from the result
- double readingQuality = result.ReadingQuality;
- // Store the index, decoded text, and quality in the list
- qualities.Add((index, result.CodeText, readingQuality));
- // Output the information to the console for verification
- Console.WriteLine($"Detected DataMatrix #{index}: CodeText=\"{result.CodeText}\", ReadingQuality={readingQuality}");
- index++;
+ // Verify that the detected barcode is a DataMatrix type.
+ if (result.CodeTypeName.Equals("DataMatrix", StringComparison.OrdinalIgnoreCase))
+ {
+ results.Add((sample.FileName, result.ReadingQuality));
+ }
}
}
}
- // Store the results in a CSV file (as a stand‑in for a real database)
- using (var writer = new StreamWriter(csvPath))
+ // --------------------------------------------------------------------
+ // Persist the collected reading quality data.
+ // In a production scenario, replace this CSV write with database insertion.
+ // --------------------------------------------------------------------
+ const string csvPath = "datamatrix_reading_quality.csv";
+ using (var writer = new StreamWriter(csvPath, false))
{
- // Write CSV header
- writer.WriteLine("Index,CodeText,ReadingQuality");
- // Write each record
- foreach (var item in qualities)
+ writer.WriteLine("FileName,ReadingQuality");
+ foreach (var entry in results)
{
- writer.WriteLine($"{item.Index},\"{item.CodeText}\",{item.ReadingQuality}");
+ writer.WriteLine($"{entry.FileName},{entry.ReadingQuality}");
}
}
- Console.WriteLine($"Reading quality data saved to \"{csvPath}\".");
-
- // NOTE:
- // In a production scenario you would insert the values into a database
- // (e.g., using ADO.NET, Entity Framework, Dapper, etc.). The database
- // code is omitted here because the required NuGet packages are not
- // available in the snippet runner environment.
+ Console.WriteLine($"Reading quality data saved to '{csvPath}'.");
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/access-foundbarcodes-collection-after-recognition-to-count-unique-barcodes-and-display-their-positions.cs b/barcode-recognition-basics/access-foundbarcodes-collection-after-recognition-to-count-unique-barcodes-and-display-their-positions.cs
index cff2989..b6fb092 100644
--- a/barcode-recognition-basics/access-foundbarcodes-collection-after-recognition-to-count-unique-barcodes-and-display-their-positions.cs
+++ b/barcode-recognition-basics/access-foundbarcodes-collection-after-recognition-to-count-unique-barcodes-and-display-their-positions.cs
@@ -1,81 +1,84 @@
-// Title: Barcode Generation, Recognition, and Position Reporting
-// Description: Generates a Code128 barcode image, reads it back, counts unique barcodes, and prints their positions.
+// Title: Count Unique Barcodes and Display Their Positions
+// Description: Generates a Code128 barcode image, recognizes all barcodes in the image, counts unique entries, and prints each barcode's text with its location.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It demonstrates how to use BarcodeGenerator to create barcodes and BarCodeReader to detect them, covering typical use cases such as inventory scanning, document processing, and quality control where developers need to extract barcode data and spatial information from images.
// Prompt: Access FoundBarCodes collection after recognition to count unique barcodes and display their positions.
-// Tags: code128, barcode generation, barcode recognition, unique count, position output, aspose.barcode
+// Tags: code128, barcode recognition, console output, barcodelibrary, barcodelgeneration, barcoderecognition
using System;
-using System.Collections.Generic;
using System.IO;
-using Aspose.BarCode;
+using System.Linq;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates how to generate a barcode, recognize it, count unique values,
-/// and display the position of each detected barcode using Aspose.BarCode.
+/// Demonstrates barcode generation, recognition, unique count, and position reporting using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the example. Generates a barcode image, reads it,
- /// and outputs detection details to the console.
+ /// Entry point. Generates a barcode, reads it, counts unique codes, and prints their positions.
///
static void Main()
{
- // ------------------------------------------------------------
- // Step 1: Generate a sample barcode image (Code128, text "ABC123")
- // ------------------------------------------------------------
+ // Define a temporary file path for the generated barcode image.
string imagePath = "sample_barcode.png";
+
+ // Generate a Code128 barcode image with the text "ABC123".
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "ABC123"))
{
- // Save the generated barcode as a PNG file
- generator.Save(imagePath, BarCodeImageFormat.Png);
+ generator.Save(imagePath);
}
- // ------------------------------------------------------------
- // Step 2: Verify that the image file was created successfully
- // ------------------------------------------------------------
+ // Verify that the image file was successfully created.
if (!File.Exists(imagePath))
{
Console.WriteLine("Failed to create barcode image.");
return;
}
- // ------------------------------------------------------------
- // Step 3: Read barcodes from the generated image
- // ------------------------------------------------------------
+ // Initialize a barcode reader to detect all supported barcode types in the image.
using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
- // Perform recognition of all supported barcode types
+ // Perform the recognition process.
reader.ReadBarCodes();
- // --------------------------------------------------------
- // Step 4: Access the FoundBarCodes collection
- // --------------------------------------------------------
- BarCodeResult[] results = reader.FoundBarCodes;
- int totalCount = results.Length;
- Console.WriteLine($"Total barcodes detected: {totalCount}");
+ // Retrieve the collection of detected barcodes.
+ var foundBarCodes = reader.FoundBarCodes;
+ int totalDetected = foundBarCodes?.Length ?? 0;
+ Console.WriteLine($"Total barcodes detected: {totalDetected}");
- // --------------------------------------------------------
- // Step 5: Count unique barcodes based on their CodeText
- // --------------------------------------------------------
- var uniqueSet = new HashSet();
- foreach (var result in results)
+ // Exit early if no barcodes were found.
+ if (totalDetected == 0)
{
- uniqueSet.Add(result.CodeText);
+ return;
}
- Console.WriteLine($"Unique barcodes count: {uniqueSet.Count}");
- // --------------------------------------------------------
- // Step 6: Display positions (region) of each detected barcode
- // --------------------------------------------------------
- for (int i = 0; i < totalCount; i++)
+ // Determine the number of unique barcodes based on their CodeText values.
+ var uniqueBarCodes = foundBarCodes
+ .GroupBy(r => r.CodeText)
+ .Select(g => g.First())
+ .ToArray();
+
+ Console.WriteLine($"Unique barcodes count: {uniqueBarCodes.Length}");
+
+ // Iterate through all detected barcodes and display their text and bounding rectangle.
+ foreach (var result in foundBarCodes)
{
- var result = results[i];
var rect = result.Region.Rectangle;
- Console.WriteLine(
- $"Barcode {i + 1}: Text = '{result.CodeText}', Position = (X={rect.X}, Y={rect.Y}, Width={rect.Width}, Height={rect.Height})");
+ Console.WriteLine($"CodeText: {result.CodeText}");
+ Console.WriteLine($"Position - X:{rect.X}, Y:{rect.Y}, Width:{rect.Width}, Height:{rect.Height}");
+ Console.WriteLine();
}
}
+
+ // Clean up the temporary image file.
+ try
+ {
+ File.Delete(imagePath);
+ }
+ catch
+ {
+ // Suppress any exceptions that occur during cleanup.
+ }
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/apply-checksumvalidationdefault-to-enforce-default-checksum-handling-when-reading-mixed-symbology-images.cs b/barcode-recognition-basics/apply-checksumvalidationdefault-to-enforce-default-checksum-handling-when-reading-mixed-symbology-images.cs
index c243f0a..2c7d664 100644
--- a/barcode-recognition-basics/apply-checksumvalidationdefault-to-enforce-default-checksum-handling-when-reading-mixed-symbology-images.cs
+++ b/barcode-recognition-basics/apply-checksumvalidationdefault-to-enforce-default-checksum-handling-when-reading-mixed-symbology-images.cs
@@ -1,96 +1,58 @@
-// Title: Demonstrate checksum validation on mixed-symbology barcode image
-// Description: Generates Code128 and EAN13 barcodes, combines them, and reads them using default checksum validation.
+// Title: Enforce default checksum validation when reading mixed‑symbology barcodes
+// Description: Demonstrates generating Code128 and EAN13 barcodes, then reading them with ChecksumValidation.Default to ensure proper checksum handling.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing how to configure checksum validation using the BarCodeReader and BarcodeSettings classes. Developers often need to read mixed‑symbology images while applying default checksum rules to filter out invalid codes. Typical use cases include inventory systems, point‑of‑sale scanners, and batch processing of barcode images.
// Prompt: Apply ChecksumValidation.Default to enforce default checksum handling when reading mixed‑symbology images.
-// Tags: barcode symbology, checksum validation, mixed symbology, aspnet barcoderecognition, aspnet barcodelibrary
+// Tags: barcode, checksumvalidation, default, mixed-symbology, generation, recognition, 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;
///
-/// Example program that generates barcodes, combines them, and reads them with default checksum validation.
+/// Provides an example of generating barcodes and reading them with default checksum validation.
///
class Program
{
///
- /// Entry point. Generates barcode images, merges them, and reads the combined image while applying default checksum validation.
+ /// Entry point that creates sample barcodes, saves them, and reads them applying default checksum validation.
///
static void Main()
{
- // Define output directory and ensure it exists
- string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "output");
+ // Prepare the output directory for generated barcode images
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
Directory.CreateDirectory(outputDir);
- // Paths for individual and combined barcode images
- string code128Path = Path.Combine(outputDir, "code128.png");
- string ean13Path = Path.Combine(outputDir, "ean13.png");
- string mixedPath = Path.Combine(outputDir, "mixed.png");
-
// Generate a Code128 barcode and save it as PNG
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "ABC123456"))
+ string code128Path = Path.Combine(outputDir, "code128.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- generator.Save(code128Path, BarCodeImageFormat.Png);
+ generator.Save(code128Path);
}
- // Generate an EAN13 barcode with a valid checksum and save it as PNG
+ // Generate an EAN13 barcode (including checksum digit) and save it as PNG
+ string ean13Path = Path.Combine(outputDir, "ean13.png");
using (var generator = new BarcodeGenerator(EncodeTypes.EAN13, "1234567890128"))
{
- generator.Save(ean13Path, BarCodeImageFormat.Png);
+ generator.Save(ean13Path);
}
- // Combine the two barcode images into a single image with spacing
- using (var img1 = (Bitmap)Image.FromFile(code128Path))
- using (var img2 = (Bitmap)Image.FromFile(ean13Path))
+ // Iterate over all generated PNG files and read them with default checksum validation
+ foreach (string filePath in Directory.GetFiles(outputDir, "*.png"))
{
- int width = Math.Max(img1.Width, img2.Width);
- int height = img1.Height + img2.Height + 20; // extra spacing between images
-
- using (var combined = new Bitmap(width, height))
+ using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
{
- using (var graphics = Graphics.FromImage(combined))
- {
- // Fill background with white
- graphics.Clear(Aspose.Drawing.Color.White);
- // Draw the first barcode at the top
- graphics.DrawImage(img1, 0, 0);
- // Draw the second barcode below the first, with spacing
- graphics.DrawImage(img2, 0, img1.Height + 20);
- }
+ // Enforce default checksum handling for each read operation
+ reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.Default;
- // Save the combined image
- combined.Save(mixedPath, ImageFormat.Png);
- }
- }
-
- // Verify that the combined image was created successfully
- if (!File.Exists(mixedPath))
- {
- Console.WriteLine("Combined image not found.");
- return;
- }
-
- // Read all supported barcodes from the combined image using default checksum validation
- using (var reader = new BarCodeReader(mixedPath, DecodeType.AllSupportedTypes))
- {
- // Apply default checksum handling
- reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.Default;
-
- // Iterate through detected barcodes and output details
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"Detected Type: {result.CodeTypeName}");
- Console.WriteLine($"CodeText: {result.CodeText}");
-
- // For 1D barcodes, display the checksum if it is available
- if (result.Extended?.OneD?.CheckSum != null)
+ // Output each detected barcode's type and text
+ foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"Checksum: {result.Extended.OneD.CheckSum}");
+ Console.WriteLine($"File: {Path.GetFileName(filePath)}");
+ Console.WriteLine($" Type: {result.CodeTypeName}");
+ Console.WriteLine($" CodeText: {result.CodeText}");
}
-
- Console.WriteLine();
}
}
}
diff --git a/barcode-recognition-basics/apply-custom-threshold-treating-readingquality-below-50-as-unacceptable-and-flag-those-barcodes-for-manual-review.cs b/barcode-recognition-basics/apply-custom-threshold-treating-readingquality-below-50-as-unacceptable-and-flag-those-barcodes-for-manual-review.cs
index ead6fd6..373364d 100644
--- a/barcode-recognition-basics/apply-custom-threshold-treating-readingquality-below-50-as-unacceptable-and-flag-those-barcodes-for-manual-review.cs
+++ b/barcode-recognition-basics/apply-custom-threshold-treating-readingquality-below-50-as-unacceptable-and-flag-those-barcodes-for-manual-review.cs
@@ -1,85 +1,66 @@
-// Title: Barcode Generation, Recognition, and Quality Threshold Evaluation
-// Description: Generates a Code128 barcode, saves it as PNG, reads it back, and flags barcodes with reading quality below 50% for manual review.
+// Title: Barcode Generation, Recognition, and Quality Evaluation
+// Description: Generates Code128 barcodes, reads them, and evaluates reading quality, flagging low-quality scans for manual review.
+// Category-Description: This example demonstrates core Aspose.BarCode operations: barcode generation (BarcodeGenerator) and recognition (BarCodeReader). It shows how to configure barcode parameters, save to a stream, decode, and assess the ReadingQuality metric. Developers often need to automate barcode validation pipelines and identify scans that fall below acceptable quality thresholds.
// Prompt: Apply a custom threshold treating ReadingQuality below 50 as unacceptable and flag those barcodes for manual review.
-// Tags: barcode symbology, generation, recognition, quality threshold, manual review, aspnet barcoderecognition, png
+// Tags: code128, barcode, generation, recognition, quality, readingquality, aspose.barcode
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Demonstrates creating a barcode, saving it as an image, reading it back,
-/// and applying a custom quality threshold to flag low‑quality scans for manual review.
+/// Demonstrates generating Code128 barcodes, reading them from memory,
+/// and evaluating their ReadingQuality to flag low‑quality results.
///
class Program
{
///
- /// Entry point of the example. Executes barcode generation, verification, recognition,
- /// and quality assessment logic.
+ /// Entry point of the example. Generates sample barcodes, reads them,
+ /// and outputs quality assessment messages.
///
static void Main()
{
- // --------------------------------------------------------------------
- // Define the output path for the generated barcode image.
- // --------------------------------------------------------------------
- const string imagePath = "sample_barcode.png";
+ // Sample barcode texts to process
+ string[] codeTexts = { "12345", "ABCDE", "LOWQ" };
- // --------------------------------------------------------------------
- // Generate a simple Code128 barcode and persist it as a PNG file.
- // --------------------------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
+ // Iterate over each sample text
+ foreach (string code in codeTexts)
{
- // Save the barcode image in PNG format.
- generator.Save(imagePath, BarCodeImageFormat.Png);
- }
-
- // --------------------------------------------------------------------
- // Verify that the barcode image was successfully created.
- // --------------------------------------------------------------------
- if (!File.Exists(imagePath))
- {
- Console.WriteLine($"Error: Barcode image not found at '{imagePath}'.");
- return;
- }
-
- // --------------------------------------------------------------------
- // Initialize a reader to decode all supported barcode types from the image.
- // --------------------------------------------------------------------
- using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
- {
- // Perform the recognition operation.
- var results = reader.ReadBarCodes();
-
- // Handle the case where no barcodes were detected.
- if (results.Length == 0)
+ // Create a barcode generator for Code128 with the current text
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, code))
{
- Console.WriteLine("No barcodes detected in the image.");
- return;
- }
+ // Optional: adjust the module (X) size for better readability
+ generator.Parameters.Barcode.XDimension.Point = 2f;
- // ----------------------------------------------------------------
- // Iterate through each detected barcode and evaluate its reading quality.
- // ----------------------------------------------------------------
- int count = 0;
- foreach (var result in results)
- {
- count++;
- double quality = result.ReadingQuality; // ReadingQuality is a double representing a percentage.
+ // Store the generated barcode image in a memory stream
+ using (var ms = new MemoryStream())
+ {
+ // Save the barcode as a PNG image into the stream
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0; // Reset stream position for reading
- // Apply custom threshold: treat quality below 50% as unacceptable.
- bool isUnacceptable = quality < 50.0;
- string status = isUnacceptable
- ? "UNACCEPTABLE – Flagged for manual review"
- : "Acceptable";
+ // Initialize a barcode reader for Code128 using the same stream
+ using (var reader = new BarCodeReader(ms, DecodeType.Code128))
+ {
+ // Read all barcodes found in the image (should be one)
+ foreach (var result in reader.ReadBarCodes())
+ {
+ double quality = result.ReadingQuality;
- // Output detailed information for each barcode.
- Console.WriteLine($"Barcode #{count}:");
- Console.WriteLine($" CodeText : {result.CodeText}");
- Console.WriteLine($" ReadingQuality : {quality:F2}%");
- Console.WriteLine($" Status : {status}");
- Console.WriteLine();
+ // Apply custom quality threshold: flag if below 50
+ if (quality < 50.0)
+ {
+ Console.WriteLine($"[FLAGGED] Code '{code}' requires manual review. ReadingQuality: {quality}");
+ }
+ else
+ {
+ Console.WriteLine($"[OK] Code '{code}' recognized successfully. ReadingQuality: {quality}");
+ }
+ }
+ }
+ }
}
}
}
diff --git a/barcode-recognition-basics/apply-high-resolution-bitmap-source-to-improve-detection-accuracy-of-small-sized-datamatrix-codes.cs b/barcode-recognition-basics/apply-high-resolution-bitmap-source-to-improve-detection-accuracy-of-small-sized-datamatrix-codes.cs
index ca0cb15..fc28b4e 100644
--- a/barcode-recognition-basics/apply-high-resolution-bitmap-source-to-improve-detection-accuracy-of-small-sized-datamatrix-codes.cs
+++ b/barcode-recognition-basics/apply-high-resolution-bitmap-source-to-improve-detection-accuracy-of-small-sized-datamatrix-codes.cs
@@ -1,7 +1,8 @@
-// Title: High‑Resolution DataMatrix Barcode Generation and Recognition
-// Description: Demonstrates generating a DataMatrix barcode with increased DPI and then recognizing it using high‑quality settings to improve detection of small‑sized codes.
+// Title: High‑Resolution Bitmap Source for Accurate Small DataMatrix Detection
+// Description: Demonstrates how to upscale a low‑resolution DataMatrix barcode image to improve recognition of tiny symbols.
+// Category-Description: This example belongs to the Aspose.BarCode image processing and recognition category. It showcases the use of BarcodeGenerator to create a DataMatrix, Aspose.Drawing to manipulate bitmap resolution, and BarCodeReader with QualitySettings to enhance detection. Developers working with low‑resolution barcodes or needing higher detection reliability will find this pattern useful for preprocessing images before recognition.
// Prompt: Apply a high‑resolution bitmap source to improve detection accuracy of small‑sized DataMatrix codes.
-// Tags: datamatrix, generation, recognition, highresolution, qualitysettings, barcode
+// Tags: datamatrix, detection, png, barcodegenerator, barcodereader, imaging, qualitysettings, upscaling
using System;
using System.IO;
@@ -9,66 +10,70 @@
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Example program that creates a high‑resolution DataMatrix barcode image
-/// and reads it back using high‑quality recognition settings.
+/// Generates a low‑resolution DataMatrix barcode, upscales it, and reads it using high‑performance settings.
///
class Program
{
///
- /// Entry point. Generates a DataMatrix barcode with high DPI,
- /// saves it to a file, and then reads it using enhanced quality settings.
+ /// Entry point of the example. Creates, upscales, and recognizes a small DataMatrix barcode.
///
static void Main()
{
- // Define the text to encode in the DataMatrix barcode.
- string codeText = "ABC123";
+ // Sample data for a small DataMatrix barcode
+ const string data = "SmallDM";
- // Specify the output file path for the generated barcode image.
- string imagePath = "datamatrix.png";
-
- // ------------------------------------------------------------
- // Generate a high‑resolution DataMatrix barcode image.
- // ------------------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, codeText))
+ // Generate a low‑resolution DataMatrix barcode and keep it in memory
+ using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, data))
{
- // Set image resolution to 300 DPI for better quality.
- generator.Parameters.Resolution = 300; // 300 DPI
-
- // Enable automatic sizing using interpolation to preserve detail.
+ // Enable automatic sizing using interpolation (no explicit BarHeight needed)
generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- // Define a larger image size (in points) to obtain a high‑resolution bitmap.
- generator.Parameters.ImageWidth.Point = 200f;
- generator.Parameters.ImageHeight.Point = 200f;
+ // Set a small XDimension to keep the barcode compact
+ generator.Parameters.Barcode.XDimension.Point = 0.5f;
- // Save the generated barcode image to the specified path.
- generator.Save(imagePath);
- }
+ // Save the generated barcode to a memory stream in PNG format
+ using (var originalStream = new MemoryStream())
+ {
+ generator.Save(originalStream, BarCodeImageFormat.Png);
+ originalStream.Position = 0; // Reset stream position for reading
- // Verify that the barcode image was successfully created.
- if (!File.Exists(imagePath))
- {
- Console.WriteLine($"Failed to create barcode image at '{imagePath}'.");
- return;
- }
+ // Load the generated image into a bitmap for manipulation
+ using (var originalBitmap = new Bitmap(originalStream))
+ {
+ // Define upscale factor (e.g., 4×) to increase resolution
+ int scale = 4;
+ int highResWidth = originalBitmap.Width * scale;
+ int highResHeight = originalBitmap.Height * scale;
- // ------------------------------------------------------------
- // Read the barcode using high‑quality recognition settings.
- // ------------------------------------------------------------
- using (var reader = new BarCodeReader(imagePath, DecodeType.DataMatrix))
- {
- // Apply high‑quality settings and enable detection of small XDimension.
- reader.QualitySettings = QualitySettings.HighQuality;
- reader.QualitySettings.XDimension = XDimensionMode.Small;
+ // Create a new bitmap with the higher resolution dimensions
+ using (var highResBitmap = new Bitmap(highResWidth, highResHeight))
+ {
+ // Draw the original low‑resolution bitmap onto the larger canvas
+ using (var graphics = Graphics.FromImage(highResBitmap))
+ {
+ graphics.DrawImage(originalBitmap, 0, 0, highResWidth, highResHeight);
+ }
- // Iterate through all detected barcodes and output their details.
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"Detected CodeText: {result.CodeText}");
- Console.WriteLine($"Barcode Type: {result.CodeTypeName}");
- Console.WriteLine($"Reading Quality: {result.ReadingQuality}");
+ // Recognize the DataMatrix from the upscaled bitmap
+ using (var reader = new BarCodeReader(highResBitmap, DecodeType.DataMatrix))
+ {
+ // Configure quality settings to improve detection of small symbols
+ reader.QualitySettings = QualitySettings.HighPerformance;
+ reader.QualitySettings.XDimension = XDimensionMode.UseMinimalXDimension;
+ reader.QualitySettings.MinimalXDimension = 2f; // Minimum element size in pixels
+
+ // Iterate through detected barcodes and output their details
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Detected CodeType: {result.CodeType}");
+ Console.WriteLine($"Detected CodeText: {result.CodeText}");
+ }
+ }
+ }
+ }
}
}
}
diff --git a/barcode-recognition-basics/apply-predefined-types2d-set-to-barcodereader-to-automatically-detect-common-two-dimensional-barcodes.cs b/barcode-recognition-basics/apply-predefined-types2d-set-to-barcodereader-to-automatically-detect-common-two-dimensional-barcodes.cs
index 00edb81..1d0abea 100644
--- a/barcode-recognition-basics/apply-predefined-types2d-set-to-barcodereader-to-automatically-detect-common-two-dimensional-barcodes.cs
+++ b/barcode-recognition-basics/apply-predefined-types2d-set-to-barcodereader-to-automatically-detect-common-two-dimensional-barcodes.cs
@@ -1,7 +1,8 @@
// Title: Detect common 2D barcodes using Types2D preset
-// Description: Demonstrates applying the predefined Types2D set to BarCodeReader to automatically detect common two‑dimensional barcodes in an image.
+// Description: This example generates a QR code, then uses BarCodeReader with the Types2D preset to automatically detect common two‑dimensional barcodes.
+// Category-Description: Demonstrates Aspose.BarCode barcode generation and recognition within the 2D symbology category. It showcases the BarcodeGenerator for creating QR codes and the BarCodeReader with DecodeType.Types2D to recognize QR, DataMatrix, PDF417, and other 2D barcodes. Developers use these APIs to embed barcode creation and scanning functionality in .NET applications, such as inventory systems, ticketing, and mobile scanning solutions.
// Prompt: Apply the predefined Types2D set to BarCodeReader to automatically detect common two‑dimensional barcodes.
-// Tags: barcode symbology, detection, 2d, types2d, aspose, csharp
+// Tags: barcode, 2d, types2d, generation, recognition, aspose.barcode, csharp
using System;
using System.IO;
@@ -10,44 +11,51 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that generates a QR code (if missing) and reads it using the Types2D preset.
+/// Demonstrates generating a QR code and detecting it using BarCodeReader with the Types2D preset.
///
class Program
{
///
- /// Entry point. Generates a QR code image if needed and reads it with BarCodeReader using DecodeType.Types2D.
+ /// Entry point of the example. Generates a QR code image, reads it with Types2D detection, and outputs results.
///
static void Main()
{
- // Define the path for the sample barcode image
- string imagePath = "sample_qr.png";
+ // Define a temporary file path for the generated QR code image
+ string imagePath = "qr.png";
- // Generate a QR code image if it does not already exist
- if (!File.Exists(imagePath))
+ // Generate a QR code image with sample text
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Hello Aspose"))
{
- // Initialize a QR code generator with the desired text
- using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Hello Aspose"))
- {
- // Set a moderate error correction level (Level M)
- generator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelM;
+ // Save the barcode as PNG
+ generator.Save(imagePath, BarCodeImageFormat.Png);
+ }
- // Save the generated QR code to the specified file
- generator.Save(imagePath);
- }
+ // Verify that the image was created
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine("Failed to create the barcode image.");
+ return;
}
- // Create a BarCodeReader that uses the predefined Types2D set to detect common 2D barcodes
+ // Create a BarCodeReader configured to detect all common 2D barcodes (Types2D)
using (var reader = new BarCodeReader(imagePath, DecodeType.Types2D))
{
- // Iterate through all detected barcodes in the image
+ // Read all detected barcodes
foreach (var result in reader.ReadBarCodes())
{
- // Output the type of the detected barcode
Console.WriteLine($"Detected Type: {result.CodeTypeName}");
-
- // Output the decoded text of the barcode
Console.WriteLine($"Code Text: {result.CodeText}");
}
}
+
+ // 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-basics/batch-read-multiple-barcode-images-from-network-share-capturing-confidence-and-readingquality-for-each-file.cs b/barcode-recognition-basics/batch-read-multiple-barcode-images-from-network-share-capturing-confidence-and-readingquality-for-each-file.cs
index b5214d5..9fdd8c9 100644
--- a/barcode-recognition-basics/batch-read-multiple-barcode-images-from-network-share-capturing-confidence-and-readingquality-for-each-file.cs
+++ b/barcode-recognition-basics/batch-read-multiple-barcode-images-from-network-share-capturing-confidence-and-readingquality-for-each-file.cs
@@ -1,87 +1,108 @@
-// Title: Batch Barcode Reader with Confidence and ReadingQuality
-// Description: Demonstrates reading multiple barcode images from a network share and retrieving confidence and reading quality metrics for each detected barcode.
+// Title: Batch barcode reading with confidence and quality metrics
+// Description: Demonstrates how to read multiple barcode images from a folder (or network share) and capture each barcode's confidence and reading quality.
+// Category-Description: This example belongs to the Aspose.BarCode reading category, showcasing the use of BarCodeReader, DecodeType, and related result properties. Typical scenarios include bulk processing of scanned documents, inventory verification, and quality assessment of barcode captures. Developers often need to iterate over image collections, extract barcode data, and evaluate confidence and reading quality to ensure reliable downstream processing.
// Prompt: Batch read multiple barcode images from a network share, capturing Confidence and ReadingQuality for each file.
-// Tags: barcode, batch, confidence, readingquality, aspose, csharp, network-share
+// Tags: code128, qr, datamatrix, batch-read, confidence, readingquality, console-output, barcodereader, barcodegenerator, decodetype, encodetypes
using System;
using System.IO;
-using System.Linq;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-namespace BarcodeBatchReader
+///
+/// Example program that batch‑reads barcode images from a folder (or network share),
+/// printing each barcode's type, text, confidence, and reading quality.
+///
+class Program
{
///
- /// Entry point for the batch barcode reading example.
+ /// Entry point. Accepts an optional folder path argument; otherwise uses a default "Barcodes" folder.
+ /// Generates sample barcodes if none are found, then reads all supported images.
///
- class Program
+ /// Command‑line arguments; first argument may specify the barcode folder path.
+ static void Main(string[] args)
{
- ///
- /// Scans a network share for up to five barcode images, reads each barcode,
- /// and prints its type, text, confidence, and reading quality.
- ///
- static void Main()
+ // Determine the folder containing barcode images.
+ // In production replace this with a UNC path, e.g. @"\\Server\Share\Barcodes".
+ string folderPath = args.Length > 0 ? args[0] : "Barcodes";
+
+ // Ensure the target folder exists.
+ if (!Directory.Exists(folderPath))
{
- // Path to the network share containing barcode images.
- // Adjust the UNC path as needed for your environment.
- string folderPath = @"\\networkshare\barcodes";
+ Directory.CreateDirectory(folderPath);
+ }
- // Verify that the folder exists before proceeding.
- if (!Directory.Exists(folderPath))
- {
- Console.WriteLine($"Folder not found: {folderPath}");
- return;
- }
+ // Check whether the folder already contains supported image files.
+ bool hasImages = Directory.GetFiles(folderPath, "*.png").Length > 0 ||
+ Directory.GetFiles(folderPath, "*.jpg").Length > 0 ||
+ Directory.GetFiles(folderPath, "*.bmp").Length > 0;
- // Define the set of image file extensions that will be processed.
- string[] supportedExtensions = { ".png", ".jpg", ".jpeg", ".bmp", ".gif" };
+ // If no images are present, generate a few sample barcode files.
+ if (!hasImages)
+ {
+ GenerateSampleBarcodes(folderPath);
+ }
- // Retrieve up to 5 image files that match the supported extensions.
- string[] files = Directory.GetFiles(folderPath)
- .Where(f => supportedExtensions.Contains(Path.GetExtension(f), StringComparer.OrdinalIgnoreCase))
- .Take(5)
- .ToArray();
+ // Gather all supported image files (PNG, JPG, BMP) into a single array.
+ string[] pngFiles = Directory.GetFiles(folderPath, "*.png");
+ string[] jpgFiles = Directory.GetFiles(folderPath, "*.jpg");
+ string[] bmpFiles = Directory.GetFiles(folderPath, "*.bmp");
- // If no matching files are found, inform the user and exit.
- if (files.Length == 0)
+ string[] allFiles = new string[pngFiles.Length + jpgFiles.Length + bmpFiles.Length];
+ pngFiles.CopyTo(allFiles, 0);
+ jpgFiles.CopyTo(allFiles, pngFiles.Length);
+ bmpFiles.CopyTo(allFiles, pngFiles.Length + jpgFiles.Length);
+
+ // Iterate over each image file and attempt to read any barcodes it contains.
+ foreach (string filePath in allFiles)
+ {
+ if (!File.Exists(filePath))
{
- Console.WriteLine("No barcode image files found in the specified folder.");
- return;
+ Console.WriteLine($"File not found: {filePath}");
+ continue;
}
- // Process each discovered image file.
- foreach (string filePath in files)
+ // Use BarCodeReader with AllSupportedTypes to detect any barcode format.
+ using (BarCodeReader reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
{
- // Double‑check that the file still exists (it could have been removed).
- if (!File.Exists(filePath))
+ // ReadBarCodes returns an enumerable of detection results.
+ foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"File not found: {filePath}");
- continue;
+ Console.WriteLine($"File: {Path.GetFileName(filePath)}");
+ Console.WriteLine($" Type: {result.CodeTypeName}");
+ Console.WriteLine($" CodeText: {result.CodeText}");
+ Console.WriteLine($" Confidence: {result.Confidence}");
+ Console.WriteLine($" ReadingQuality: {result.ReadingQuality}");
}
+ }
+ }
+ }
- // Create a BarCodeReader for the current file, using all supported symbologies.
- using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
- {
- // Perform the barcode recognition operation.
- BarCodeResult[] results = reader.ReadBarCodes();
+ ///
+ /// Generates a set of sample barcode images (Code128, QR, DataMatrix) in the specified folder.
+ ///
+ /// The directory where sample images will be saved.
+ private static void GenerateSampleBarcodes(string folderPath)
+ {
+ // Sample 1: Code128 barcode.
+ string code128Path = Path.Combine(folderPath, "sample_code128.png");
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ {
+ generator.Save(code128Path);
+ }
- // If no barcodes were detected, report and move to the next file.
- if (results.Length == 0)
- {
- Console.WriteLine($"No barcode detected in file: {Path.GetFileName(filePath)}");
- continue;
- }
+ // Sample 2: QR Code.
+ string qrPath = Path.Combine(folderPath, "sample_qr.png");
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"))
+ {
+ generator.Save(qrPath);
+ }
- // Output details for each detected barcode.
- foreach (var result in results)
- {
- Console.WriteLine($"File: {Path.GetFileName(filePath)}");
- Console.WriteLine($" Type: {result.CodeTypeName}");
- Console.WriteLine($" Text: {result.CodeText}");
- Console.WriteLine($" Confidence: {result.Confidence}");
- Console.WriteLine($" ReadingQuality: {result.ReadingQuality}");
- }
- }
- }
+ // Sample 3: DataMatrix barcode.
+ string dmPath = Path.Combine(folderPath, "sample_datamatrix.png");
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "DM123456"))
+ {
+ generator.Save(dmPath);
}
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/call-abort-method-from-separate-thread-while-recognition-is-running-to-stop-operation-immediately.cs b/barcode-recognition-basics/call-abort-method-from-separate-thread-while-recognition-is-running-to-stop-operation-immediately.cs
index ba8fc51..3d3ed2c 100644
--- a/barcode-recognition-basics/call-abort-method-from-separate-thread-while-recognition-is-running-to-stop-operation-immediately.cs
+++ b/barcode-recognition-basics/call-abort-method-from-separate-thread-while-recognition-is-running-to-stop-operation-immediately.cs
@@ -1,73 +1,86 @@
// Title: Abort barcode recognition from another thread
-// Description: Demonstrates calling Abort on a BarCodeReader while recognition runs in a separate thread to stop processing immediately.
+// Description: Demonstrates aborting an ongoing barcode recognition operation using BarCodeReader.Abort from a separate thread.
+// Category-Description: This example belongs to the Aspose.BarCode recognition category, showcasing how to control long‑running barcode scanning tasks. It uses the BarCodeReader class to decode QR codes and the Abort method to stop processing instantly. Developers often need to cancel recognition in responsive UI scenarios or when a timeout occurs, making this pattern essential for robust multithreaded applications.
// Prompt: Call Abort method from a separate thread while recognition is running to stop the operation immediately.
-// Tags: barcode, abort, multithreading, recognition, aspose.barcoderecognition
+// Tags: barcode recognition, abort, multithreading, aspose.barcode, qr, c#
using System;
using System.IO;
using System.Threading;
+using System.Threading.Tasks;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Example program showing how to abort barcode recognition from another thread.
+/// Example program that generates a QR barcode, starts recognition on a separate thread,
+/// and aborts the operation from the main thread using .
///
class Program
{
///
- /// Runs barcode recognition in a separate thread.
- /// The method will be interrupted if is called from another thread.
+ /// Method executed on a background thread to perform barcode recognition.
+ /// It iterates through detected barcodes until the operation is aborted.
///
/// An instance of passed as an object.
private static void ThreadRecognize(object readerObj)
{
- // Cast the passed object back to BarCodeReader
- BarCodeReader reader = (BarCodeReader)readerObj;
-
- // Iterate through all detected barcodes; this loop will exit early if Abort() is invoked
- foreach (BarCodeResult result in reader.ReadBarCodes())
+ var reader = (BarCodeReader)readerObj;
+ try
{
- Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
- Console.WriteLine($"BarCode Text: {result.CodeText}");
+ // Enumerate all detected barcodes; this loop runs until Abort is called.
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Detected: {result.CodeTypeName} - {result.CodeText}");
+ }
+ }
+ catch (Exception ex)
+ {
+ // Abort throws an exception; capture it to indicate the operation was stopped.
+ Console.WriteLine($"Recognition stopped: {ex.Message}");
}
}
///
- /// Entry point that generates a barcode, starts recognition on a separate thread,
- /// aborts it, and waits for completion.
+ /// Entry point of the program. Generates a QR code image, starts recognition on a separate thread,
+ /// aborts the recognition after a short delay, and cleans up resources.
///
static void Main()
{
- // Generate a sample barcode image in memory (Code128 with value "123456789")
- using (MemoryStream ms = new MemoryStream())
+ // Generate a temporary QR barcode image.
+ string tempDir = Path.GetTempPath();
+ string imagePath = Path.Combine(tempDir, "sample_qr.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Hello Aspose"))
{
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789"))
- {
- generator.Save(ms, BarCodeImageFormat.Png);
- }
+ generator.Save(imagePath);
+ }
- // Reset stream position so the reader can read from the beginning
- ms.Position = 0;
+ // Verify that the image was created successfully.
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine("Failed to create barcode image.");
+ return;
+ }
- // Create a BarCodeReader for the image stream and enable all supported symbologies
- using (BarCodeReader reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes))
- {
- // Set a generous timeout to give Abort() enough time to take effect
- reader.Timeout = 10000; // 10 seconds
+ // Initialize a BarCodeReader for the generated QR image.
+ using (var reader = new BarCodeReader(imagePath, DecodeType.QR))
+ {
+ // Launch the recognition process on a separate thread.
+ Thread recognizeThread = new Thread(ThreadRecognize);
+ recognizeThread.Start(reader);
- // Start the recognition process on a separate thread
- Thread recognizeThread = new Thread(ThreadRecognize);
- recognizeThread.Start(reader);
+ // Allow the recognition to run briefly before aborting.
+ Task.Delay(200).Wait();
- // Request immediate abort from the main thread
- reader.Abort();
+ Console.WriteLine("Calling Abort...");
+ // Abort the ongoing recognition operation.
+ reader.Abort();
- // Wait for the recognition thread to finish cleanly
- recognizeThread.Join();
- }
+ // Wait for the background thread to finish handling the abort.
+ recognizeThread.Join();
+ Console.WriteLine("Recognition thread finished.");
}
- Console.WriteLine("Recognition aborted and program completed.");
+ Console.WriteLine("Program completed.");
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/catch-recognitionabortedexception-to-handle-cases-where-barcode-detection-is-interrupted-by-timeout-or-abort.cs b/barcode-recognition-basics/catch-recognitionabortedexception-to-handle-cases-where-barcode-detection-is-interrupted-by-timeout-or-abort.cs
index 740a8a2..13186e8 100644
--- a/barcode-recognition-basics/catch-recognitionabortedexception-to-handle-cases-where-barcode-detection-is-interrupted-by-timeout-or-abort.cs
+++ b/barcode-recognition-basics/catch-recognitionabortedexception-to-handle-cases-where-barcode-detection-is-interrupted-by-timeout-or-abort.cs
@@ -1,59 +1,61 @@
-// Title: Barcode Generation and Recognition with Timeout Handling
-// Description: Demonstrates generating a Code128 barcode, reading it from a memory stream, and handling a RecognitionAbortedException when the read operation times out.
+// Title: Barcode recognition with timeout handling
+// Description: Demonstrates generating a Code128 barcode, setting a very low timeout, and catching RecognitionAbortedException when detection is aborted.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator, BarCodeReader, and DecodeType classes to create a barcode image in memory and attempt to read it with a custom timeout. Developers often need to handle recognition timeouts or aborts, making exception handling for RecognitionAbortedException essential for robust barcode scanning solutions.
// Prompt: Catch RecognitionAbortedException to handle cases where barcode detection is interrupted by timeout or abort.
-// Tags: barcode, code128, generation, recognition, timeout, exception handling, aspose.barcode
+// Tags: barcode, code128, timeout, recognitionabortedexception, generation, recognition, aspnet, aspose.barcode
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Example program that creates a barcode, attempts to read it, and gracefully handles a timeout abort.
+/// Generates a Code128 barcode, attempts to read it with an extremely low timeout,
+/// and demonstrates handling of when the
+/// recognition process is aborted (e.g., due to timeout).
///
class Program
{
///
- /// Entry point of the application. Generates a barcode, reads it, and catches RecognitionAbortedException.
+ /// Entry point of the example. Executes barcode generation, sets a short timeout,
+ /// and reads the barcode while handling possible abort scenarios.
///
static void Main()
{
- // Define the text to encode in the barcode.
- const string codeText = "1234567890";
-
- // Use a memory stream to hold the generated barcode image.
- using (var generationStream = new MemoryStream())
+ // Create a barcode generator for Code128 with sample data
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Create a barcode generator for Code128 symbology.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ // Generate the barcode image in memory
+ using (Bitmap barcodeImage = generator.GenerateBarCodeImage())
{
- // Save the barcode as a PNG image into the memory stream.
- generator.Save(generationStream, BarCodeImageFormat.Png);
- }
-
- // Reset the stream position to the beginning before reading.
- generationStream.Position = 0;
-
- // Initialize a barcode reader for the generated image, specifying the expected symbology.
- using (var reader = new BarCodeReader(generationStream, DecodeType.Code128))
- {
- // Set an extremely low timeout (1 ms) to force a RecognitionAbortedException.
- reader.Timeout = 1; // milliseconds
-
- try
+ // Initialize a barcode reader for the generated image, targeting Code128 symbology
+ using (var reader = new BarCodeReader(barcodeImage, DecodeType.Code128))
{
- // Iterate through all detected barcodes in the image.
- foreach (var result in reader.ReadBarCodes())
+ // Configure an extremely low timeout (1 ms) to force an abort condition
+ reader.Timeout = 1; // milliseconds
+
+ try
{
- Console.WriteLine($"Detected Type: {result.CodeTypeName}");
- Console.WriteLine($"Detected Text: {result.CodeText}");
+ // Attempt to read barcodes; may throw RecognitionAbortedException
+ foreach (BarCodeResult result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Detected Type: {result.CodeType}");
+ Console.WriteLine($"Detected Text: {result.CodeText}");
+ }
+ }
+ catch (RecognitionAbortedException ex)
+ {
+ // Handle recognition abort (e.g., timeout) gracefully
+ Console.WriteLine("Barcode recognition was aborted:");
+ Console.WriteLine(ex.Message);
+ }
+ catch (Exception ex)
+ {
+ // Fallback for any other unexpected errors
+ Console.WriteLine("An unexpected error occurred:");
+ Console.WriteLine(ex.Message);
}
- }
- catch (RecognitionAbortedException ex)
- {
- // Handle the case where recognition was aborted due to timeout or manual abort.
- Console.WriteLine($"Recognition aborted: {ex.Message}");
}
}
}
diff --git a/barcode-recognition-basics/change-source-image-after-construction-by-calling-setbarcodeimage-with-new-file-path.cs b/barcode-recognition-basics/change-source-image-after-construction-by-calling-setbarcodeimage-with-new-file-path.cs
index c2ce07a..193e6d2 100644
--- a/barcode-recognition-basics/change-source-image-after-construction-by-calling-setbarcodeimage-with-new-file-path.cs
+++ b/barcode-recognition-basics/change-source-image-after-construction-by-calling-setbarcodeimage-with-new-file-path.cs
@@ -1,58 +1,77 @@
-// Title: Changing BarCodeReader Source Image at Runtime
-// Description: Demonstrates how to read barcodes from an initial image, then switch to a different image using SetBarCodeImage, and read again.
+// Title: Change Barcode Source Image Using SetBarCodeImage
+// Description: Demonstrates how to switch the source image of a BarCodeReader after construction by calling SetBarCodeImage with a new file path.
+// Category-Description: This example belongs to the Aspose.BarCode image manipulation category, illustrating how to work with the BarCodeReader class to read barcodes from different images without recreating the reader. Typical use cases include batch processing of scanned documents where the same reader instance can be reused for performance. Developers often need to change the source image dynamically, and SetBarCodeImage provides a convenient way to do so.
// Prompt: Change the source image after construction by calling SetBarCodeImage with a new file path.
-// Tags: barcode, setimage, reader, decode, aspose.barcode
+// Tags: code128,qr,barcode generation,barcode reading,setbarcodeimage,aspose.barcode,output png
using System;
using System.IO;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.BarCode;
+using Aspose.Drawing.Imaging;
///
-/// Example program that shows how to change the source image of a
-/// after it has been constructed, using SetBarCodeImage.
+/// Example program that generates two barcode images, reads the first one,
+/// then switches the reader's source image to the second barcode using SetBarCodeImage.
///
class Program
{
///
- /// Entry point of the example. Reads barcodes from an initial image,
- /// switches to a new image, and reads barcodes again.
+ /// Entry point of the example. Generates barcode images, reads them, and demonstrates
+ /// changing the source image of a BarCodeReader instance.
///
static void Main()
{
- // Paths to the initial and the new barcode images.
- string initialImagePath = "barcode1.png";
- string newImagePath = "barcode2.png";
+ // --------------------------------------------------------------------
+ // Prepare output directory and file paths for the generated barcodes
+ // --------------------------------------------------------------------
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ Directory.CreateDirectory(outputDir);
+ string barcodePath1 = Path.Combine(outputDir, "barcode1.png");
+ string barcodePath2 = Path.Combine(outputDir, "barcode2.png");
- // Verify that the initial image exists.
- if (!File.Exists(initialImagePath))
+ // --------------------------------------------------------------------
+ // Generate the first barcode (Code128) and save it as PNG
+ // --------------------------------------------------------------------
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "ABC123"))
{
- Console.WriteLine($"Initial image not found: {initialImagePath}");
- return;
+ generator.Save(barcodePath1, BarCodeImageFormat.Png);
+ }
+
+ // --------------------------------------------------------------------
+ // Generate the second barcode (QR) and save it as PNG
+ // --------------------------------------------------------------------
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"))
+ {
+ generator.Save(barcodePath2, BarCodeImageFormat.Png);
}
- // Verify that the new image exists.
- if (!File.Exists(newImagePath))
+ // --------------------------------------------------------------------
+ // Verify that both barcode image files were created successfully
+ // --------------------------------------------------------------------
+ if (!File.Exists(barcodePath1) || !File.Exists(barcodePath2))
{
- Console.WriteLine($"New image not found: {newImagePath}");
+ Console.WriteLine("Failed to create barcode images.");
return;
}
- // Create a BarCodeReader for the initial image, supporting all barcode types.
- using (var reader = new BarCodeReader(initialImagePath, DecodeType.AllSupportedTypes))
+ // --------------------------------------------------------------------
+ // Create a BarCodeReader for the first image (Code128) and read its content
+ // --------------------------------------------------------------------
+ using (var reader = new BarCodeReader(barcodePath1, DecodeType.Code128))
{
- // Read and display barcodes from the initial image.
- Console.WriteLine("Reading barcodes from the initial image:");
+ Console.WriteLine("Reading from first image:");
foreach (BarCodeResult result in reader.ReadBarCodes())
{
Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}");
}
- // Change the source image to the new file.
- reader.SetBarCodeImage(newImagePath);
+ // ----------------------------------------------------------------
+ // Change the source image of the existing reader to the second barcode
+ // ----------------------------------------------------------------
+ reader.SetBarCodeImage(barcodePath2);
- // Read and display barcodes from the new image.
- Console.WriteLine("Reading barcodes after changing the source image:");
+ Console.WriteLine("Reading after SetBarCodeImage to second image:");
foreach (BarCodeResult result in reader.ReadBarCodes())
{
Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}");
diff --git a/barcode-recognition-basics/combine-multiple-target-regions-to-focus-recognition-on-several-distinct-areas-within-single-image-file.cs b/barcode-recognition-basics/combine-multiple-target-regions-to-focus-recognition-on-several-distinct-areas-within-single-image-file.cs
index ffae6cd..f3477ed 100644
--- a/barcode-recognition-basics/combine-multiple-target-regions-to-focus-recognition-on-several-distinct-areas-within-single-image-file.cs
+++ b/barcode-recognition-basics/combine-multiple-target-regions-to-focus-recognition-on-several-distinct-areas-within-single-image-file.cs
@@ -1,7 +1,8 @@
-// Title: Demonstrate combining multiple target regions for barcode recognition
-// Description: Shows how to define separate image areas to focus barcode detection on distinct regions within a single image file.
+// Title: Combine Multiple Target Regions for Barcode Recognition
+// Description: Demonstrates how to define several target regions in a single image to focus barcode recognition on distinct areas.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating the use of BarCodeReader with multiple target regions. It showcases key API classes such as BarcodeGenerator, BarCodeReader, and DecodeType, helping developers who need to scan specific parts of an image containing several barcodes, a common requirement in inventory and document processing scenarios.
// Prompt: Combine multiple target regions to focus recognition on several distinct areas within a single image file.
-// Tags: barcode, target region, recognition, aspnet, csharp, aspose.barcode
+// Tags: code128, qr, barcode recognition, target regions, aspose.barcode, c#
using System;
using System.IO;
@@ -11,111 +12,95 @@
using Aspose.Drawing.Imaging;
///
-/// Example program that creates an image containing two different barcodes,
-/// then reads them by specifying multiple target regions within the same image.
+/// Demonstrates combining two barcodes into a single image and recognizing them using multiple target regions.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Generates a combined image with Code128 and QR barcodes,
+ /// defines target regions for each, and reads the barcodes using Aspose.BarCode.
///
static void Main()
{
- // Path to the sample image that will contain multiple barcodes
- string imagePath = "sample_multi.png";
+ // Image dimensions for the combined bitmap.
+ const int imageWidth = 600;
+ const int imageHeight = 300;
- // If the image does not exist, create it with two barcodes placed at different locations
- if (!File.Exists(imagePath))
+ // Dimensions for each individual barcode.
+ const int barcodeWidth = 250;
+ const int barcodeHeight = 100;
+
+ // Create an empty bitmap that will hold both barcodes.
+ using (Bitmap combinedBitmap = new Bitmap(imageWidth, imageHeight))
{
- // Create a blank bitmap large enough to hold two barcodes side by side
- using (Bitmap canvas = new Bitmap(800, 400))
+ using (Graphics graphics = Graphics.FromImage(combinedBitmap))
{
- using (Graphics g = Graphics.FromImage(canvas))
- {
- // Fill background with white
- g.Clear(Color.White);
+ // Fill the background with white.
+ graphics.Clear(Color.White);
- // First barcode: Code128
- using (BarcodeGenerator gen1 = new BarcodeGenerator(EncodeTypes.Code128, "ABC123"))
+ // ----- First barcode: Code128 -----
+ using (var generator1 = new BarcodeGenerator(EncodeTypes.Code128, "CODE128-123"))
+ {
+ generator1.Parameters.Barcode.XDimension.Point = 2f;
+ using (MemoryStream ms1 = new MemoryStream())
{
- using (MemoryStream ms1 = new MemoryStream())
+ // Save the generated barcode to a memory stream.
+ generator1.Save(ms1, BarCodeImageFormat.Png);
+ ms1.Position = 0;
+ using (Bitmap barcodeBmp1 = new Bitmap(ms1))
{
- // Save generated barcode to memory stream as PNG
- gen1.Save(ms1, BarCodeImageFormat.Png);
- ms1.Position = 0;
- using (Bitmap bmp1 = new Bitmap(ms1))
- {
- // Draw the first barcode at (50,50)
- g.DrawImage(bmp1, new Point(50, 50));
- }
+ // Draw the first barcode at the left side of the combined image.
+ Rectangle destRect1 = new Rectangle(20, 20, barcodeWidth, barcodeHeight);
+ graphics.DrawImage(barcodeBmp1, destRect1);
}
}
+ }
- // Second barcode: QR
- using (BarcodeGenerator gen2 = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"))
+ // ----- Second barcode: QR Code -----
+ using (var generator2 = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"))
+ {
+ generator2.Parameters.Barcode.XDimension.Point = 3f;
+ using (MemoryStream ms2 = new MemoryStream())
{
- using (MemoryStream ms2 = new MemoryStream())
+ // Save the generated QR code to a memory stream.
+ generator2.Save(ms2, BarCodeImageFormat.Png);
+ ms2.Position = 0;
+ using (Bitmap barcodeBmp2 = new Bitmap(ms2))
{
- // Save generated QR code to memory stream as PNG
- gen2.Save(ms2, BarCodeImageFormat.Png);
- ms2.Position = 0;
- using (Bitmap bmp2 = new Bitmap(ms2))
- {
- // Draw the second barcode at (450,150)
- g.DrawImage(bmp2, new Point(450, 150));
- }
+ // Draw the second barcode at the right side of the combined image.
+ Rectangle destRect2 = new Rectangle(320, 20, barcodeWidth, barcodeHeight);
+ graphics.DrawImage(barcodeBmp2, destRect2);
}
}
}
-
- // Save the composed image to disk
- canvas.Save(imagePath, ImageFormat.Png);
}
- Console.WriteLine($"Sample image created at '{imagePath}'.");
- }
+ // Save the combined image for visual verification (optional).
+ const string combinedImagePath = "combined.png";
+ combinedBitmap.Save(combinedImagePath, ImageFormat.Png);
+ Console.WriteLine($"Combined image saved to '{combinedImagePath}'.");
- // Load the image for recognition
- using (Bitmap bitmap = new Bitmap(imagePath))
- {
- // Define two target regions (left and right halves of the image)
- Rectangle[] targetAreas = new Rectangle[]
+ // Define target regions that correspond to the locations of the two barcodes.
+ Rectangle[] targetRegions = new Rectangle[]
{
- new Rectangle(0, 0, bitmap.Width / 2, bitmap.Height),
- new Rectangle(bitmap.Width / 2, 0, bitmap.Width / 2, bitmap.Height)
+ new Rectangle(20, 20, barcodeWidth, barcodeHeight), // Region for Code128
+ new Rectangle(320, 20, barcodeWidth, barcodeHeight) // Region for QR
};
- // Initialize the barcode reader
- using (BarCodeReader reader = new BarCodeReader())
+ // Use BarCodeReader with the specified regions to focus recognition.
+ using (var reader = new BarCodeReader(combinedBitmap, targetRegions, DecodeType.AllSupportedTypes))
{
- // Detect all supported barcode types
- reader.BarCodeReadType = DecodeType.AllSupportedTypes;
-
- // Assign the image and the target regions
- reader.SetBarCodeImage(bitmap, targetAreas);
-
- // Perform recognition
- BarCodeResult[] results = reader.ReadBarCodes();
-
- // Output information about each detected barcode
- foreach (BarCodeResult result in results)
+ // Iterate over detected barcodes within the defined regions.
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
- Console.WriteLine($"Code Text : {result.CodeText}");
- Console.WriteLine($"Code Type : {result.CodeTypeName}");
-
- // Region rectangle (pixel coordinates)
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($"Code Text : {result.CodeText}");
+ // Output the region rectangle for each detected barcode.
var rect = result.Region.Rectangle;
- Console.WriteLine($"Region : X={rect.X}, Y={rect.Y}, Width={rect.Width}, Height={rect.Height}");
-
- // Orientation angle (degrees)
- Console.WriteLine($"Angle : {result.Region.Angle}");
+ Console.WriteLine($"Region : X={rect.X}, Y={rect.Y}, Width={rect.Width}, Height={rect.Height}");
+ Console.WriteLine($"Angle : {result.Region.Angle}");
Console.WriteLine(new string('-', 40));
}
-
- if (results.Length == 0)
- {
- Console.WriteLine("No barcodes were detected in the specified regions.");
- }
}
}
}
diff --git a/barcode-recognition-basics/compare-recognition-confidence-between-default-and-forced-checksum-validation-for-code-128-barcodes-in-performance-bench.cs b/barcode-recognition-basics/compare-recognition-confidence-between-default-and-forced-checksum-validation-for-code-128-barcodes-in-performance-bench.cs
index 7b779a6..cd6301c 100644
--- a/barcode-recognition-basics/compare-recognition-confidence-between-default-and-forced-checksum-validation-for-code-128-barcodes-in-performance-bench.cs
+++ b/barcode-recognition-basics/compare-recognition-confidence-between-default-and-forced-checksum-validation-for-code-128-barcodes-in-performance-bench.cs
@@ -1,71 +1,86 @@
-// Title: Code128 checksum validation confidence comparison
-// Description: Demonstrates how to generate a Code 128 barcode, then reads it twice—once with default checksum validation and once with forced checksum validation—to compare the confidence values returned by the recognizer.
+// Title: Compare checksum validation confidence for Code 128 barcodes
+// Description: Demonstrates how default and forced checksum validation affect recognition confidence and performance for a Code 128 barcode.
+// Category-Description: This example belongs to the Aspose.BarCode recognition performance benchmarks. It shows usage of BarcodeGenerator, BarCodeReader, and ChecksumValidation settings to compare confidence levels and processing time, a common task for developers optimizing barcode scanning reliability and speed.
// Prompt: Compare recognition confidence between default and forced checksum validation for Code 128 barcodes in a performance benchmark.
-// Tags: code128, checksum validation, confidence, performance benchmark, aspose.barcode, barcode generation, barcode recognition
+// Tags: code128, checksumvalidation, confidence, performance, benchmark, generation, recognition, aspose.barcode
using System;
+using System.Diagnostics;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that generates a Code128 barcode, then reads it using default and forced checksum validation
-/// to illustrate the difference in recognition confidence values.
+/// Generates a Code 128 barcode, then measures and compares recognition confidence
+/// and execution time using default checksum validation versus forced checksum validation.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a barcode image, verifies its creation, and performs two recognition passes:
- /// one with default checksum handling and another with checksum validation forced on.
+ /// Entry point of the example. Executes barcode generation, recognition, and timing.
///
static void Main()
{
- // Define the file name for the generated barcode image
+ // Path for the generated barcode image
const string imagePath = "code128.png";
// ------------------------------------------------------------
- // Generate a Code128 barcode with sample data and save it to disk
+ // Generate a Code128 barcode and save it to a file
// ------------------------------------------------------------
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Save the barcode image to the specified path
generator.Save(imagePath);
}
- // ------------------------------------------------------------
- // Verify that the image file was successfully created
- // ------------------------------------------------------------
+ // Verify that the image was created successfully
if (!File.Exists(imagePath))
{
- Console.WriteLine($"Error: Barcode image '{imagePath}' was not created.");
+ Console.WriteLine("Failed to create barcode image.");
return;
}
+ // Variables to hold confidence values for each scenario
+ BarCodeConfidence defaultConfidence = BarCodeConfidence.None;
+ BarCodeConfidence forcedConfidence = BarCodeConfidence.None;
+
// ------------------------------------------------------------
- // Read the barcode using default checksum validation (no explicit setting)
+ // Measure default recognition (checksum validation follows default behavior)
// ------------------------------------------------------------
- using (var readerDefault = new BarCodeReader(imagePath, DecodeType.Code128))
+ var defaultStopwatch = Stopwatch.StartNew();
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
{
- foreach (var result in readerDefault.ReadBarCodes())
+ foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"Default Validation Confidence: {result.Confidence}");
+ defaultConfidence = result.Confidence;
+ break; // Only one barcode expected
}
}
+ defaultStopwatch.Stop();
// ------------------------------------------------------------
- // Read the same barcode with forced checksum validation (ChecksumValidation.On)
+ // Measure recognition with forced checksum validation (ChecksumValidation.On)
// ------------------------------------------------------------
- using (var readerForced = new BarCodeReader(imagePath, DecodeType.Code128))
+ var forcedStopwatch = Stopwatch.StartNew();
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
{
- // Enable forced checksum validation
- readerForced.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
+ // Force checksum validation for this read operation
+ reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
- foreach (var result in readerForced.ReadBarCodes())
+ foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"Forced Validation Confidence: {result.Confidence}");
+ forcedConfidence = result.Confidence;
+ break; // Only one barcode expected
}
}
+ forcedStopwatch.Stop();
+
+ // ------------------------------------------------------------
+ // Output the comparison results
+ // ------------------------------------------------------------
+ Console.WriteLine($"Default checksum validation confidence: {defaultConfidence}");
+ Console.WriteLine($"Forced checksum validation confidence: {forcedConfidence}");
+ Console.WriteLine($"Default recognition time: {defaultStopwatch.ElapsedMilliseconds} ms");
+ Console.WriteLine($"Forced checksum recognition time: {forcedStopwatch.ElapsedMilliseconds} ms");
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/compare-recognition-quality-of-qr-codes-captured-under-different-lighting-conditions-by-analyzing-readingquality-values.cs b/barcode-recognition-basics/compare-recognition-quality-of-qr-codes-captured-under-different-lighting-conditions-by-analyzing-readingquality-values.cs
index 82a9fc5..a464f02 100644
--- a/barcode-recognition-basics/compare-recognition-quality-of-qr-codes-captured-under-different-lighting-conditions-by-analyzing-readingquality-values.cs
+++ b/barcode-recognition-basics/compare-recognition-quality-of-qr-codes-captured-under-different-lighting-conditions-by-analyzing-readingquality-values.cs
@@ -1,7 +1,8 @@
-// Title: QR Code ReadingQuality Comparison Under Varying Lighting
-// Description: Generates QR codes with different background shades to simulate lighting conditions and compares their ReadingQuality values after recognition.
+// Title: QR Code Reading Quality under Different Lighting Conditions
+// Description: Demonstrates generating QR codes with varying background colors to simulate lighting and compares their recognition quality using ReadingQuality values.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator for creating QR codes and BarCodeReader with QualitySettings for evaluating detection performance. Developers often need to assess how environmental factors like lighting affect barcode readability, making ReadingQuality a valuable metric for quality assurance and image preprocessing pipelines.
// Prompt: Compare recognition quality of QR codes captured under different lighting conditions by analyzing ReadingQuality values.
-// Tags: qr, readingquality, lighting, barcode, generation, recognition, aspnet, csharp
+// Tags: qr, lighting, readingquality, barcode, generation, recognition, aspose.barcode, aspose.drawing
using System;
using System.IO;
@@ -11,74 +12,73 @@
using Aspose.Drawing;
///
-/// Demonstrates how lighting (background color) affects QR code recognition quality
-/// by generating three QR images and reporting their ReadingQuality values.
+/// Generates QR code images with different simulated lighting conditions and evaluates their
+/// recognition quality using the ReadingQuality property provided by Aspose.BarCode.
///
class Program
{
///
- /// Entry point. Generates QR codes with normal, bright, and dark backgrounds,
- /// then reads each image and prints the ReadingQuality metric.
+ /// Entry point of the example. Creates QR codes with bright and dim backgrounds,
+ /// saves them, and then reads each image to output the ReadingQuality metric.
///
static void Main()
{
- // Text to encode in the QR code
+ // Define the directory where generated images will be stored.
+ string outputDir = "output";
+ if (!Directory.Exists(outputDir))
+ {
+ Directory.CreateDirectory(outputDir);
+ }
+
+ // Text to encode in the QR code.
const string qrText = "Lighting Test QR";
- // Create three memory streams – one for each simulated lighting condition
- using (var streamNormal = new MemoryStream())
- using (var streamBright = new MemoryStream())
- using (var streamDark = new MemoryStream())
+ // Define lighting scenarios: a name and the background color that simulates the lighting.
+ var conditions = new (string Name, Color Background)[]
{
- // ---------- Generate QR code with normal lighting (white background) ----------
- using (var generator = new BarcodeGenerator(EncodeTypes.QR, qrText))
- {
- generator.Parameters.BackColor = Color.White; // normal background
- generator.Save(streamNormal, BarCodeImageFormat.Png);
- }
+ ("Bright", Color.White), // Simulates well‑lit environment.
+ ("Dim", Color.LightGray) // Simulates low‑light environment.
+ };
- // ---------- Generate QR code with bright lighting (light gray background) ----------
+ // --------------------------------------------------------------------
+ // Generate QR code images for each lighting condition.
+ // --------------------------------------------------------------------
+ foreach (var condition in conditions)
+ {
+ string filePath = Path.Combine(outputDir, $"{condition.Name}.png");
using (var generator = new BarcodeGenerator(EncodeTypes.QR, qrText))
{
- generator.Parameters.BackColor = Color.LightGray; // brighter appearance
- generator.Save(streamBright, BarCodeImageFormat.Png);
- }
+ // Apply the background color to mimic the lighting condition.
+ generator.Parameters.BackColor = condition.Background;
- // ---------- Generate QR code with dark lighting (dark gray background) ----------
- using (var generator = new BarcodeGenerator(EncodeTypes.QR, qrText))
- {
- generator.Parameters.BackColor = Color.DarkGray; // darker appearance
- generator.Save(streamDark, BarCodeImageFormat.Png);
+ // Save the generated QR code as a PNG file.
+ generator.Save(filePath, BarCodeImageFormat.Png);
}
-
- // Reset stream positions so the reader starts from the beginning of each image
- streamNormal.Position = 0;
- streamBright.Position = 0;
- streamDark.Position = 0;
-
- // ---------- Read and compare ReadingQuality values ----------
- Console.WriteLine("ReadingQuality comparison for QR codes under different lighting conditions:");
- ReadAndReport(streamNormal, "Normal Lighting (White BG)");
- ReadAndReport(streamBright, "Bright Lighting (LightGray BG)");
- ReadAndReport(streamDark, "Dark Lighting (DarkGray BG)");
}
- }
- ///
- /// Reads a QR code from the provided image stream and writes its ReadingQuality to the console.
- ///
- /// Stream containing the QR code image.
- /// Human‑readable description of the lighting condition.
- static void ReadAndReport(Stream imageStream, string description)
- {
- // Initialize the reader for QR codes
- using (var reader = new BarCodeReader(imageStream, DecodeType.QR))
+ // --------------------------------------------------------------------
+ // Recognize each generated image and output its ReadingQuality value.
+ // --------------------------------------------------------------------
+ foreach (var condition in conditions)
{
- // Iterate through all detected barcodes (normally just one)
- foreach (var result in reader.ReadBarCodes())
+ string filePath = Path.Combine(outputDir, $"{condition.Name}.png");
+ if (!File.Exists(filePath))
{
- // ReadingQuality is a double representing the confidence percentage
- Console.WriteLine($"{description}: ReadingQuality = {result.ReadingQuality}%");
+ Console.WriteLine($"File not found: {filePath}");
+ continue;
+ }
+
+ using (var reader = new BarCodeReader(filePath, DecodeType.QR))
+ {
+ // Use high‑quality settings to improve detection accuracy.
+ reader.QualitySettings = QualitySettings.HighQuality;
+
+ // Iterate through all detected barcodes (should be one per image).
+ foreach (var result in reader.ReadBarCodes())
+ {
+ double quality = result.ReadingQuality;
+ Console.WriteLine($"{condition.Name} lighting - ReadingQuality: {quality}");
+ }
}
}
}
diff --git a/barcode-recognition-basics/configure-barcodesettingschecksumvalidation-to-on-for-both-obligatory-and-optional-checksum-symbologies-in-single-read-o.cs b/barcode-recognition-basics/configure-barcodesettingschecksumvalidation-to-on-for-both-obligatory-and-optional-checksum-symbologies-in-single-read-o.cs
index 5960b59..f4f414e 100644
--- a/barcode-recognition-basics/configure-barcodesettingschecksumvalidation-to-on-for-both-obligatory-and-optional-checksum-symbologies-in-single-read-o.cs
+++ b/barcode-recognition-basics/configure-barcodesettingschecksumvalidation-to-on-for-both-obligatory-and-optional-checksum-symbologies-in-single-read-o.cs
@@ -1,84 +1,63 @@
-// Title: Demonstrate checksum validation for mandatory and optional symbologies in a single read
-// Description: This example generates an EAN13 barcode (mandatory checksum) and a Code39 barcode (optional checksum), combines them, and reads both with checksum validation turned on.
+// Title: Barcode checksum validation for multiple symbologies in a single read
+// Description: Demonstrates enabling checksum validation for both mandatory and optional checksum symbologies while reading multiple barcodes in one image.
+// Category-Description: This example belongs to the Aspose.BarCode reading and validation category. It shows how to use BarCodeReader with BarcodeSettings.ChecksumValidation to enforce checksum checks across all supported symbologies, a common requirement when processing 1D barcodes such as EAN13 (mandatory checksum) and Code39 (optional checksum). Developers often need to validate data integrity in batch scanning scenarios, and this snippet illustrates the typical API usage for combined image generation and validation.
// Prompt: Configure BarcodeSettings.ChecksumValidation to On for both obligatory and optional checksum symbologies in a single read operation.
-// Tags: barcode symbology, checksum validation, read operation, aspose.barcode, csharp
+// Tags: barcode symbology, checksum validation, read operation, aspose.barcode, generation, recognition
using System;
-using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Sample program that creates two barcodes, merges them into a single image,
-/// and reads them back with checksum validation enabled for both mandatory
-/// and optional checksum symbologies.
+/// Example program that generates two barcodes, combines them into a single image,
+/// and reads them back with checksum validation enabled for both mandatory and optional checksum symbologies.
///
class Program
{
///
- /// Entry point. Generates barcodes, combines them, and performs a single read
- /// operation with ChecksumValidation set to On.
+ /// Entry point. Generates EAN13 and Code39 barcodes, merges them, and reads them with checksum validation turned on.
///
static void Main()
{
- // Generate first barcode (EAN13) – checksum is mandatory
+ // Generate an EAN13 barcode (checksum is mandatory)
using (var eanGenerator = new BarcodeGenerator(EncodeTypes.EAN13, "1234567890128"))
+ using (var eanImage = eanGenerator.GenerateBarCodeImage())
+ // Generate a Code39 barcode (checksum is optional)
+ using (var code39Generator = new BarcodeGenerator(EncodeTypes.Code39, "CODE39"))
+ using (var code39Image = code39Generator.GenerateBarCodeImage())
+ // Combine both images side by side into a single bitmap
+ using (var combined = new Bitmap(eanImage.Width + code39Image.Width,
+ Math.Max(eanImage.Height, code39Image.Height)))
{
- using (var eanStream = new MemoryStream())
+ // Draw the two barcode images onto the combined bitmap
+ using (var graphics = Graphics.FromImage(combined))
{
- eanGenerator.Save(eanStream, BarCodeImageFormat.Png);
- eanStream.Position = 0;
-
- // Generate second barcode (Code39) – checksum is optional
- using (var code39Generator = new BarcodeGenerator(EncodeTypes.Code39, "CODE39"))
- {
- using (var code39Stream = new MemoryStream())
- {
- code39Generator.Save(code39Stream, BarCodeImageFormat.Png);
- code39Stream.Position = 0;
-
- // Load both images from the memory streams
- using (var eanImage = new Bitmap(eanStream))
- using (var code39Image = new Bitmap(code39Stream))
- {
- // Create a combined image (side by side)
- int combinedWidth = eanImage.Width + code39Image.Width;
- int combinedHeight = Math.Max(eanImage.Height, code39Image.Height);
- using (var combinedImage = new Bitmap(combinedWidth, combinedHeight))
- {
- using (var graphics = Graphics.FromImage(combinedImage))
- {
- graphics.DrawImage(eanImage, 0, 0);
- graphics.DrawImage(code39Image, eanImage.Width, 0);
- }
-
- // Read both barcodes in a single operation with checksum validation enabled
- using (var reader = new BarCodeReader(combinedImage, DecodeType.EAN13, DecodeType.Code39))
- {
- // Enable checksum validation for all symbologies (mandatory and optional)
- reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
+ graphics.DrawImage(eanImage, 0, 0);
+ graphics.DrawImage(code39Image, eanImage.Width, 0);
+ }
- // Iterate through detected barcodes and output details
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine("Detected Type: " + result.CodeTypeName);
- Console.WriteLine("CodeText: " + result.CodeText);
+ // Read both barcodes in a single operation with checksum validation enabled
+ using (var reader = new BarCodeReader(combined, DecodeType.AllSupportedTypes))
+ {
+ // Enable checksum validation for all symbologies (mandatory and optional)
+ reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
- // For 1D barcodes, checksum info is available in Extended.OneD
- if (result.Extended.OneD != null)
- {
- Console.WriteLine("Value: " + result.Extended.OneD.Value);
- Console.WriteLine("Checksum: " + result.Extended.OneD.CheckSum);
- }
+ // Iterate through all detected barcodes
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($"Code Text: {result.CodeText}");
- Console.WriteLine();
- }
- }
- }
- }
+ // For 1D barcodes, also output the checksum if available
+ if (result.Extended?.OneD != null)
+ {
+ Console.WriteLine($"Checksum: {result.Extended.OneD.CheckSum}");
}
+
+ Console.WriteLine();
}
}
}
diff --git a/barcode-recognition-basics/configure-barcodesettingschecksumvalidation-to-on-for-optional-symbologies-like-code-39-before-reading.cs b/barcode-recognition-basics/configure-barcodesettingschecksumvalidation-to-on-for-optional-symbologies-like-code-39-before-reading.cs
index 78651de..66ce80a 100644
--- a/barcode-recognition-basics/configure-barcodesettingschecksumvalidation-to-on-for-optional-symbologies-like-code-39-before-reading.cs
+++ b/barcode-recognition-basics/configure-barcodesettingschecksumvalidation-to-on-for-optional-symbologies-like-code-39-before-reading.cs
@@ -1,7 +1,8 @@
-// Title: Demonstrate checksum validation for optional symbologies (Code 39)
-// Description: Shows how to enable BarcodeSettings.ChecksumValidation before reading a Code 39 barcode, ensuring checksum is validated when present.
+// Title: Enable Checksum Validation for Code39 Barcode Reading
+// Description: Demonstrates generating a Code39 barcode, saving it as PNG, and reading it with checksum validation enabled.
+// 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 BarcodeSettings to validate checksums, a common requirement when working with optional symbologies like Code 39. Developers often need to ensure data integrity during barcode scanning, and this snippet illustrates the key API classes and typical workflow for such scenarios.
// Prompt: Configure BarcodeSettings.ChecksumValidation to On for optional symbologies like Code 39 before reading.
-// Tags: barcode symbology, checksum validation, code39, generation, recognition, aspose.barcode
+// Tags: barcode symbology, checksum validation, code39, generation, recognition, png
using System;
using System.IO;
@@ -10,46 +11,46 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that generates a Code 39 barcode, saves it to a file,
-/// and then reads it back with checksum validation enabled.
+/// Example program that generates a Code39 barcode, saves it as a PNG image,
+/// and reads it back with checksum validation turned on.
///
class Program
{
///
- /// Entry point. Generates a barcode image, verifies its existence,
- /// and reads it while validating the checksum.
+ /// Entry point of the example. Executes barcode generation and reading with checksum validation.
///
static void Main()
{
- // Define file path for the generated barcode image
+ // Path for the generated barcode image
string imagePath = "code39.png";
- // Generate a Code39 barcode (checksum is optional for this symbology)
- using (var generator = new BarcodeGenerator(EncodeTypes.Code39, "CODE39"))
+ // Generate a Code39 barcode containing the text "ABC123"
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code39, "ABC123"))
{
- // Save the barcode image to a file
- generator.Save(imagePath);
+ // Save the generated barcode as a PNG file
+ generator.Save(imagePath, BarCodeImageFormat.Png);
}
- // Verify that the image file was created before attempting to read it
+ // Ensure the barcode image was successfully created
if (!File.Exists(imagePath))
{
- Console.WriteLine($"Error: Barcode image not found at '{imagePath}'.");
+ Console.WriteLine($"Error: Barcode image '{imagePath}' was not found.");
return;
}
- // Create a BarCodeReader for Code39 and enable checksum validation
+ // Initialize a reader for Code39 barcodes from the saved image
using (var reader = new BarCodeReader(imagePath, DecodeType.Code39))
{
- // Enable checksum validation (On) for optional symbologies like Code39
+ // Turn on checksum validation for optional symbologies like Code39
reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
- // Read barcodes from the image
+ // Iterate through all detected barcodes in the image
foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"Detected Type: {result.CodeTypeName}");
- Console.WriteLine($"CodeText: {result.CodeText}");
- // Extended parameters may contain checksum information for 1D barcodes
+ // Output the decoded text
+ Console.WriteLine($"Detected CodeText: {result.CodeText}");
+
+ // If extended 1D parameters are available, display the checksum value
if (result.Extended?.OneD != null)
{
Console.WriteLine($"Checksum: {result.Extended.OneD.CheckSum}");
diff --git a/barcode-recognition-basics/configure-multydecodetype-to-include-upca-upce-and-ean8-for-comprehensive-retail-barcode-scanning.cs b/barcode-recognition-basics/configure-multydecodetype-to-include-upca-upce-and-ean8-for-comprehensive-retail-barcode-scanning.cs
index d4cb7eb..97fbc86 100644
--- a/barcode-recognition-basics/configure-multydecodetype-to-include-upca-upce-and-ean8-for-comprehensive-retail-barcode-scanning.cs
+++ b/barcode-recognition-basics/configure-multydecodetype-to-include-upca-upce-and-ean8-for-comprehensive-retail-barcode-scanning.cs
@@ -1,61 +1,87 @@
-// Title: Multi-Decode Barcode Reader for UPC-A, UPC-E, and EAN-8
-// Description: Demonstrates configuring Aspose.BarCode's MultiDecodeType to recognize UPC-A, UPC-E, and EAN-8 barcodes, useful for retail scanning scenarios.
+// Title: Multi-Decode UPC-A, UPC-E, and EAN-8 Barcode Scanning Example
+// Description: Demonstrates generating UPC-A, UPC-E, and EAN-8 barcodes and configuring a BarCodeReader to decode them in a single pass.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing the use of MultiDecodeType with BarCodeReader to detect multiple symbologies simultaneously. It highlights key classes such as BarcodeGenerator, BarCodeReader, MultiDecodeType, and DecodeType, which developers commonly use for retail barcode scanning, inventory management, and point‑of‑sale applications.
// Prompt: Configure MultyDecodeType to include UPC-A, UPC-E, and EAN-8 for comprehensive retail barcode scanning.
-// Tags: barcode symbology, decoding, upc-a, upc-e, ean-8, aspose.barcode
+// Tags: barcode symbology, decoding, console output, aspose.barcode, aspose.drawing
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Example program that generates sample UPC-A, UPC-E, and EAN-8 barcodes
-/// and then reads them using a MultiDecodeType configuration.
+/// Generates sample UPC-A, UPC-E, and EAN-8 barcodes and reads them using a multi‑decode configuration.
///
class Program
{
///
- /// Entry point. Generates sample barcode images, configures the reader,
- /// and outputs detected barcode types and values.
+ /// Entry point of the example. Creates barcode images, configures a BarCodeReader with MultiDecodeType,
+ /// and outputs detected barcode information to the console.
///
static void Main()
{
- // --------------------------------------------------------------------
- // Generate sample barcode images for UPC-A, UPC-E, and EAN-8
- // --------------------------------------------------------------------
- GenerateSampleBarcodes();
+ // Prepare a folder for sample barcode images
+ string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(folderPath))
+ {
+ Directory.CreateDirectory(folderPath);
+ }
+
+ // Generate sample UPC-A barcode if it does not already exist
+ string upcAPath = Path.Combine(folderPath, "upca.png");
+ if (!File.Exists(upcAPath))
+ {
+ using (var generator = new BarcodeGenerator(EncodeTypes.UPCA, "012345678905"))
+ {
+ generator.Save(upcAPath);
+ }
+ }
- // --------------------------------------------------------------------
- // Define the list of image files to be scanned
- // --------------------------------------------------------------------
- string[] files = { "upca.png", "upce.png", "ean8.png" };
+ // Generate sample UPC-E barcode if it does not already exist
+ string upcEPath = Path.Combine(folderPath, "upce.png");
+ if (!File.Exists(upcEPath))
+ {
+ using (var generator = new BarcodeGenerator(EncodeTypes.UPCE, "01234565"))
+ {
+ generator.Save(upcEPath);
+ }
+ }
- // --------------------------------------------------------------------
- // Configure the barcode reader to detect the three desired symbologies
- // --------------------------------------------------------------------
+ // Generate sample EAN-8 barcode if it does not already exist
+ string ean8Path = Path.Combine(folderPath, "ean8.png");
+ if (!File.Exists(ean8Path))
+ {
+ using (var generator = new BarcodeGenerator(EncodeTypes.EAN8, "96385074"))
+ {
+ generator.Save(ean8Path);
+ }
+ }
+
+ // Configure a BarCodeReader to detect UPC-A, UPC-E, and EAN-8 in a single pass
using (var reader = new BarCodeReader())
{
- // MultiDecodeType includes UPC-A, UPC-E, and EAN-8
- reader.BarCodeReadType = new MultiDecodeType(DecodeType.UPCA, DecodeType.UPCE, DecodeType.EAN8);
+ // MultiDecodeType includes the three desired symbologies
+ var multiDecode = new MultiDecodeType(DecodeType.UPCA, DecodeType.UPCE, DecodeType.EAN8);
+ reader.BarCodeReadType = multiDecode;
- // Iterate over each file and attempt recognition
- foreach (var file in files)
+ // Process each generated image
+ string[] imageFiles = new[] { upcAPath, upcEPath, ean8Path };
+ foreach (string imageFile in imageFiles)
{
- // Verify that the file exists before processing
- if (!File.Exists(file))
+ if (!File.Exists(imageFile))
{
- Console.WriteLine($"File not found: {file}");
+ Console.WriteLine($"File not found: {imageFile}");
continue;
}
- // Assign the current image to the reader
- reader.SetBarCodeImage(file);
+ // Load the image into the reader
+ reader.SetBarCodeImage(imageFile);
- // Perform recognition and output results
+ // Read and display all detected barcodes
foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"File: {file}");
+ Console.WriteLine($"Image: {Path.GetFileName(imageFile)}");
Console.WriteLine($"Detected Type: {result.CodeTypeName}");
Console.WriteLine($"Code Text: {result.CodeText}");
Console.WriteLine();
@@ -63,28 +89,4 @@ static void Main()
}
}
}
-
- // ------------------------------------------------------------------------
- // Generates sample barcode images for demonstration purposes
- // ------------------------------------------------------------------------
- private static void GenerateSampleBarcodes()
- {
- // UPC-A (12 digits, last digit is checksum; generator can calculate it)
- using (var generator = new BarcodeGenerator(EncodeTypes.UPCA, "01234567890"))
- {
- generator.Save("upca.png");
- }
-
- // UPC-E (6 digits, generator will expand to UPC-A internally)
- using (var generator = new BarcodeGenerator(EncodeTypes.UPCE, "0123456"))
- {
- generator.Save("upce.png");
- }
-
- // EAN-8 (7 digits, checksum calculated automatically)
- using (var generator = new BarcodeGenerator(EncodeTypes.EAN8, "1234567"))
- {
- generator.Save("ean8.png");
- }
- }
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/configure-multydecodetype-with-code128-and-datamatrix-then-recognize-both-types-in-single-image.cs b/barcode-recognition-basics/configure-multydecodetype-with-code128-and-datamatrix-then-recognize-both-types-in-single-image.cs
index 32686d0..2cbc35f 100644
--- a/barcode-recognition-basics/configure-multydecodetype-with-code128-and-datamatrix-then-recognize-both-types-in-single-image.cs
+++ b/barcode-recognition-basics/configure-multydecodetype-with-code128-and-datamatrix-then-recognize-both-types-in-single-image.cs
@@ -1,7 +1,8 @@
-// Title: Multi-format barcode generation and recognition demo
-// Description: Demonstrates generating Code128 and DataMatrix barcodes, combining them into a single image, and recognizing both types using MultiDecodeType.
+// Title: Multi-Decode of Code128 and DataMatrix in a Single Image
+// Description: Demonstrates generating Code128 and DataMatrix barcodes, combining them into one PNG image, and recognizing both types using MultiDecodeType.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the BarcodeGenerator for creating barcodes, the Bitmap and Graphics classes for image composition, and the BarCodeReader with multiple DecodeType parameters for simultaneous detection. Developers often need to process mixed-symbology images, making multi‑decode a common requirement in inventory, logistics, and retail applications.
// Prompt: Configure MultyDecodeType with Code128 and DataMatrix, then recognize both types in a single image.
-// Tags: barcode, code128, datamatrix, multidecode, generation, recognition, aspnet, csharp
+// Tags: barcode symbology, multi-decode, png, barcodegenerator, barcodereader, aspnet.barcode, aspnet.drawing
using System;
using System.IO;
@@ -12,57 +13,77 @@
using Aspose.Drawing.Imaging;
///
-/// Example program that creates a combined image containing a Code128 and a DataMatrix barcode,
-/// then reads both barcodes from the single image using multi‑decode functionality.
+/// Generates Code128 and DataMatrix barcodes, merges them into a single image,
+/// and reads both barcode types using multi‑decode functionality.
///
class Program
{
///
- /// Entry point. Generates the barcodes, merges them, saves the combined image, and prints detected results.
+ /// Entry point of the example. Creates two barcodes, combines them, and decodes them.
///
static void Main()
{
- // Generate a Code128 barcode image
- using (var code128Generator = new BarcodeGenerator(EncodeTypes.Code128, "CODE128"))
+ // Sample texts for each barcode type
+ const string code128Text = "CODE128_SAMPLE";
+ const string dataMatrixText = "DATAMATRIX_SAMPLE";
+
+ // Generate Code128 barcode and store it in a memory stream
+ using (var code128Stream = new MemoryStream())
{
- using (Bitmap code128Image = code128Generator.GenerateBarCodeImage())
+ using (var code128Generator = new BarcodeGenerator(EncodeTypes.Code128, code128Text))
+ {
+ code128Generator.Save(code128Stream, BarCodeImageFormat.Png);
+ }
+ code128Stream.Position = 0; // Reset stream position for reading
+
+ // Generate DataMatrix barcode and store it in a separate memory stream
+ using (var dataMatrixStream = new MemoryStream())
{
- // Generate a DataMatrix barcode image
- using (var dmGenerator = new BarcodeGenerator(EncodeTypes.DataMatrix, "DM12345"))
+ using (var dataMatrixGenerator = new BarcodeGenerator(EncodeTypes.DataMatrix, dataMatrixText))
{
- using (Bitmap dmImage = dmGenerator.GenerateBarCodeImage())
- {
- // Determine combined image size (place side by side with a 20‑pixel gap)
- int combinedWidth = code128Image.Width + dmImage.Width + 20;
- int combinedHeight = Math.Max(code128Image.Height, dmImage.Height);
+ dataMatrixGenerator.Save(dataMatrixStream, BarCodeImageFormat.Png);
+ }
+ dataMatrixStream.Position = 0; // Reset stream position for reading
- // Create a new bitmap that will hold both barcodes
- using (Bitmap combinedBitmap = new Bitmap(combinedWidth, combinedHeight))
- {
- using (Graphics graphics = Graphics.FromImage(combinedBitmap))
- {
- // Fill the background with white for better contrast
- graphics.Clear(Color.White);
+ // Load both barcode images as Bitmap objects
+ using (var code128Bitmap = new Bitmap(code128Stream))
+ using (var dataMatrixBitmap = new Bitmap(dataMatrixStream))
+ {
+ // Determine dimensions for the combined image (side‑by‑side with a gap)
+ const int gap = 20;
+ int combinedWidth = code128Bitmap.Width + dataMatrixBitmap.Width + gap;
+ int combinedHeight = Math.Max(code128Bitmap.Height, dataMatrixBitmap.Height);
- // Draw the Code128 barcode on the left, vertically centered
- graphics.DrawImage(code128Image, 0, (combinedHeight - code128Image.Height) / 2);
+ // Create a new bitmap to hold the combined image
+ using (var combinedBitmap = new Bitmap(combinedWidth, combinedHeight))
+ {
+ // Draw the two barcodes onto the combined bitmap
+ using (var graphics = Graphics.FromImage(combinedBitmap))
+ {
+ graphics.Clear(Color.White); // Set background to white
+ graphics.DrawImage(code128Bitmap, 0, (combinedHeight - code128Bitmap.Height) / 2);
+ graphics.DrawImage(dataMatrixBitmap, code128Bitmap.Width + gap, (combinedHeight - dataMatrixBitmap.Height) / 2);
+ }
- // Draw the DataMatrix barcode on the right, leaving a 20‑pixel gap, vertically centered
- graphics.DrawImage(dmImage, code128Image.Width + 20, (combinedHeight - dmImage.Height) / 2);
- }
+ // Save the combined image to disk
+ const string combinedPath = "combined.png";
+ combinedBitmap.Save(combinedPath, ImageFormat.Png);
- // Save the combined image to a file (optional, useful for visual verification)
- string combinedPath = "combined.png";
- combinedBitmap.Save(combinedPath, ImageFormat.Png);
+ // Ensure the file was created before attempting to read it
+ if (!File.Exists(combinedPath))
+ {
+ Console.WriteLine("Failed to create the combined barcode image.");
+ return;
+ }
- // Recognize both barcode types from the combined image using MultiDecodeType
- using (var reader = new BarCodeReader(combinedBitmap, DecodeType.Code128, DecodeType.DataMatrix))
+ // Initialize the reader with both DecodeType values (multi‑decode)
+ using (var reader = new BarCodeReader(combinedPath, DecodeType.Code128, DecodeType.DataMatrix))
+ {
+ // Iterate through all detected barcodes and output their details
+ foreach (var result in reader.ReadBarCodes())
{
- foreach (BarCodeResult result in reader.ReadBarCodes())
- {
- Console.WriteLine("Detected Type: " + result.CodeTypeName);
- Console.WriteLine("Decoded Text: " + result.CodeText);
- }
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($"Decoded Text: {result.CodeText}");
}
}
}
diff --git a/barcode-recognition-basics/configure-qualitysettings-for-reed-solomon-error-correction-when-reading-datamatrix-barcodes-that-support-it.cs b/barcode-recognition-basics/configure-qualitysettings-for-reed-solomon-error-correction-when-reading-datamatrix-barcodes-that-support-it.cs
index df124aa..56e846d 100644
--- a/barcode-recognition-basics/configure-qualitysettings-for-reed-solomon-error-correction-when-reading-datamatrix-barcodes-that-support-it.cs
+++ b/barcode-recognition-basics/configure-qualitysettings-for-reed-solomon-error-correction-when-reading-datamatrix-barcodes-that-support-it.cs
@@ -1,69 +1,63 @@
-// Title: Reading DataMatrix with Reed‑Solomon Error Correction
-// Description: Demonstrates configuring QualitySettings for Reed‑Solomon error correction when reading DataMatrix barcodes, improving detection of damaged codes.
+// Title: Configure Reed‑Solomon error correction for DataMatrix barcode reading
+// Description: Demonstrates how to set QualitySettings to enable Reed‑Solomon error correction when decoding DataMatrix barcodes, ensuring robust reading of damaged or partially corrupted codes.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on error‑correction configuration. It showcases the use of BarCodeReader, QualitySettings, and DecodeType classes to handle DataMatrix symbology with Reed‑Solomon correction, a common requirement for applications that scan imperfect printed codes.
// Prompt: Configure QualitySettings for Reed‑Solomon error correction when reading DataMatrix barcodes that support it.
-// Tags: datamatrix, read, qualitysettings, reed-solomon, error-correction, aspose.barcode
+// Tags: datamatrix, reed-solomon, error-correction, qualitysettings, barcode-recognition, aspnet
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
///
/// Example program that generates a DataMatrix barcode, saves it as an image,
-/// and then reads it back using QualitySettings configured for Reed‑Solomon error correction.
+/// and then reads it back using Reed‑Solomon error correction via QualitySettings.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a DataMatrix barcode, saves it, and reads it with high‑quality settings.
+ /// Entry point of the example. Generates a DataMatrix barcode, writes it to disk,
+ /// and reads it back with maximum quality settings to demonstrate Reed‑Solomon handling.
///
static void Main()
{
- // Define the output image file path
+ // Path where the generated barcode image will be stored.
string imagePath = "datamatrix.png";
- // -------------------------------------------------
- // Generate a DataMatrix barcode and save it as PNG
- // -------------------------------------------------
+ // --------------------------------------------------------------------
+ // Generate a DataMatrix barcode and save it as a PNG file.
+ // --------------------------------------------------------------------
using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "SampleData"))
{
- // Set optional image dimensions (in points)
- generator.Parameters.ImageWidth.Point = 200f;
- generator.Parameters.ImageHeight.Point = 200f;
-
- // Save the generated barcode image to the specified path
+ // Additional generation options can be set here if needed.
generator.Save(imagePath, BarCodeImageFormat.Png);
}
- // -------------------------------------------------
- // Verify that the barcode image was successfully created
- // -------------------------------------------------
+ // Verify that the image file was successfully created.
if (!File.Exists(imagePath))
{
- Console.WriteLine($"Error: Barcode image not found at '{imagePath}'.");
+ Console.WriteLine($"Error: Barcode image '{imagePath}' was not found.");
return;
}
- // -------------------------------------------------
- // Read the DataMatrix barcode with Reed‑Solomon error correction enabled
- // -------------------------------------------------
+ // --------------------------------------------------------------------
+ // Read the barcode using the BarCodeReader with Reed‑Solomon error correction.
+ // --------------------------------------------------------------------
using (var reader = new BarCodeReader(imagePath, DecodeType.DataMatrix))
{
- // Apply a high‑quality preset to improve detection of damaged barcodes
- reader.QualitySettings = QualitySettings.HighQuality;
+ // Apply the highest quality preset, which enables full Reed‑Solomon correction.
+ reader.QualitySettings = QualitySettings.MaxQuality;
- // Allow reading of barcodes that may have incorrect checksums or damaged data
+ // Allow the reader to process barcodes that may have checksum errors or damage.
reader.QualitySettings.AllowIncorrectBarcodes = true;
- // Perform the recognition and output details for each detected barcode
+ // Iterate through all detected barcodes and output their details.
foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"Detected Type: {result.CodeTypeName}");
- Console.WriteLine($"Code Text: {result.CodeText}");
+ Console.WriteLine($"Detected CodeText: {result.CodeText}");
Console.WriteLine($"Confidence: {result.Confidence}");
- Console.WriteLine($"Reading Quality: {result.ReadingQuality}");
+ Console.WriteLine($"ReadingQuality: {result.ReadingQuality}");
}
}
}
diff --git a/barcode-recognition-basics/create-console-utility-that-accepts-directory-path-applies-checksumvalidationdefault-and-outputs-each-barcode-s-confiden.cs b/barcode-recognition-basics/create-console-utility-that-accepts-directory-path-applies-checksumvalidationdefault-and-outputs-each-barcode-s-confiden.cs
index 36e29ea..28963c2 100644
--- a/barcode-recognition-basics/create-console-utility-that-accepts-directory-path-applies-checksumvalidationdefault-and-outputs-each-barcode-s-confiden.cs
+++ b/barcode-recognition-basics/create-console-utility-that-accepts-directory-path-applies-checksumvalidationdefault-and-outputs-each-barcode-s-confiden.cs
@@ -1,66 +1,120 @@
-// Title: Barcode Confidence Level Scanner
-// Description: Scans a directory for supported image and PDF files, reads barcodes with default checksum validation, and prints each barcode's confidence level.
+// Title: Barcode Confidence Reader Console Utility
+// Description: Demonstrates reading barcodes from images in a directory, applying default checksum validation, and printing each barcode's confidence level.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing the use of BarCodeReader, BarcodeSettings, and DecodeType to process multiple image formats. Typical use cases include batch processing of scanned documents, validating barcode integrity, and extracting confidence metrics for quality control. Developers often need to configure checksum validation and iterate over detection results, as illustrated here.
// Prompt: Create a console utility that accepts a directory path, applies ChecksumValidation.Default, and outputs each barcode's confidence level.
-// Tags: barcode, checksumvalidation, console, confidence, aspose.barcode, file-processing
+// Tags: barcode, checksumvalidation, confidence, console, aspnet, aspnetcore, aspnet-barcode, aspose.barcode, barcode-recognition, image-processing
using System;
using System.IO;
using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Console utility that scans a directory for barcode images/PDFs,
+/// Console utility that reads barcodes from image files in a specified directory,
/// applies default checksum validation, and outputs each barcode's confidence level.
///
class Program
{
///
- /// Entry point. Accepts an optional directory path argument,
- /// processes supported files, and writes barcode details to the console.
+ /// Entry point. Accepts an optional directory path argument, generates sample barcodes if needed,
+ /// and processes each image file to display barcode information.
///
/// Command‑line arguments; first argument may be a directory path.
static void Main(string[] args)
{
- // Determine directory to scan; fallback to current directory if none provided.
- string directoryPath = args.Length > 0 ? args[0] : Directory.GetCurrentDirectory();
+ // Resolve the target folder: use the first argument if provided, otherwise create a temporary folder.
+ string folderPath;
+ if (args.Length > 0 && !string.IsNullOrWhiteSpace(args[0]))
+ {
+ folderPath = args[0];
+ }
+ else
+ {
+ // Create a temporary folder named "BarcodesSample" in the current working directory.
+ folderPath = Path.Combine(Directory.GetCurrentDirectory(), "BarcodesSample");
+ Directory.CreateDirectory(folderPath);
+ }
- // Verify that the directory exists before proceeding.
- if (!Directory.Exists(directoryPath))
+ // Verify that the folder exists before proceeding.
+ if (!Directory.Exists(folderPath))
{
- Console.WriteLine($"Directory not found: {directoryPath}");
+ Console.WriteLine($"Directory does not exist: {folderPath}");
return;
}
- // File extensions that Aspose.BarCode can read.
- string[] extensions = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".gif", ".pdf" };
-
- // Enumerate all files in the target directory.
- foreach (string filePath in Directory.GetFiles(directoryPath))
+ // If the folder is empty, generate a few sample barcode images for demonstration.
+ var sampleFiles = Directory.GetFiles(folderPath, "*.png");
+ if (sampleFiles.Length == 0)
{
- // Process only supported image/pdf files.
- if (Array.IndexOf(extensions, Path.GetExtension(filePath).ToLowerInvariant()) < 0)
- continue;
+ GenerateSampleBarcodes(folderPath);
+ }
- // Double‑check file existence (defensive programming).
- if (!File.Exists(filePath))
- {
- Console.WriteLine($"File not found (skipped): {filePath}");
- continue;
- }
+ // Define the image file patterns to process (PNG, JPG, BMP).
+ string[] patterns = new[] { "*.png", "*.jpg", "*.bmp" };
- // Open the barcode reader for the current file.
- using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
+ // Iterate over each pattern and process matching files.
+ foreach (var pattern in patterns)
+ {
+ foreach (var filePath in Directory.GetFiles(folderPath, pattern))
{
- // Apply default checksum validation as required.
- reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.Default;
+ // Guard against missing files (should not happen, but defensive programming).
+ if (!File.Exists(filePath))
+ {
+ Console.WriteLine($"File not found: {filePath}");
+ continue;
+ }
- // Read all barcodes in the file.
- foreach (BarCodeResult result in reader.ReadBarCodes())
+ // Open the image with BarCodeReader, requesting all supported barcode types.
+ using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
{
- // Output file name, barcode type, and confidence level.
- Console.WriteLine($"File: {Path.GetFileName(filePath)} | Type: {result.CodeTypeName} | Confidence: {result.Confidence}");
+ // Apply the default checksum validation setting.
+ reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.Default;
+
+ bool anyFound = false;
+
+ // Enumerate all detected barcodes in the image.
+ foreach (var result in reader.ReadBarCodes())
+ {
+ anyFound = true;
+ Console.WriteLine($"File: {Path.GetFileName(filePath)}");
+ Console.WriteLine($" Type: {result.CodeTypeName}");
+ Console.WriteLine($" CodeText: {result.CodeText}");
+ Console.WriteLine($" Confidence: {result.Confidence}");
+ }
+
+ // If no barcodes were detected, inform the user.
+ if (!anyFound)
+ {
+ Console.WriteLine($"No barcode detected in file: {Path.GetFileName(filePath)}");
+ }
}
}
}
}
+
+ // Generates a few barcode images into the specified folder for demonstration purposes.
+ private static void GenerateSampleBarcodes(string folder)
+ {
+ // Code128 barcode.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ {
+ string path = Path.Combine(folder, "code128.png");
+ generator.Save(path);
+ }
+
+ // QR code.
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR, "QR Sample Text"))
+ {
+ string path = Path.Combine(folder, "qr.png");
+ generator.Save(path);
+ }
+
+ // EAN13 barcode (requires a valid 12‑digit code; checksum is added automatically).
+ using (var generator = new BarcodeGenerator(EncodeTypes.EAN13, "590123412345"))
+ {
+ string path = Path.Combine(folder, "ean13.png");
+ generator.Save(path);
+ }
+ }
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/create-custom-exception-handler-that-retries-recognition-when-recognitionabortedexception-occurs-due-to-timeout.cs b/barcode-recognition-basics/create-custom-exception-handler-that-retries-recognition-when-recognitionabortedexception-occurs-due-to-timeout.cs
index d4f3516..d9276de 100644
--- a/barcode-recognition-basics/create-custom-exception-handler-that-retries-recognition-when-recognitionabortedexception-occurs-due-to-timeout.cs
+++ b/barcode-recognition-basics/create-custom-exception-handler-that-retries-recognition-when-recognitionabortedexception-occurs-due-to-timeout.cs
@@ -1,91 +1,101 @@
-// Title: Barcode generation and recognition with retry on timeout
-// Description: Demonstrates creating a Code128 barcode, saving it, and recognizing it with a custom retry handler for RecognitionAbortedException caused by timeout.
+// Title: Barcode Recognition with Retry on Timeout
+// Description: Demonstrates generating a Code128 barcode image and recognizing it with a custom retry handler for timeout exceptions.
+// Category-Description: This example belongs to the Aspose.BarCode recognition category, illustrating how to use BarcodeGenerator and BarCodeReader classes to create and read barcodes. It shows typical use cases such as handling RecognitionAbortedException, setting timeouts, and implementing retry logic—common tasks for developers integrating barcode scanning into applications.
// Prompt: Create a custom exception handler that retries recognition when RecognitionAbortedException occurs due to timeout.
-// Tags: barcode, code128, recognition, retry, timeout, aspose.barcodes, aspose.drawing
+// Tags: code128, barcode, recognition, timeout, retry, aspose.barcode, generation, reading
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Example program that generates a barcode image and attempts to recognize it,
-/// retrying when a timeout aborts the recognition.
+/// Generates a Code128 barcode image (if missing) and attempts to recognize it,
+/// retrying when a timeout causes a .
///
class Program
{
///
- /// Entry point. Generates a barcode, saves it, then reads it with retry logic for timeout exceptions.
+ /// Entry point of the example. Handles barcode generation, recognition, and retry logic.
///
static void Main()
{
- // Path for the temporary barcode image
- string imagePath = "sample.png";
+ // File path for the barcode image
+ const string imagePath = "sample.png";
- // Create a simple Code128 barcode and save it to a file
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
- {
- generator.Save(imagePath, BarCodeImageFormat.Png);
- }
+ // Text to encode in the barcode
+ const string codeText = "1234567890";
+
+ // Maximum number of recognition attempts
+ const int maxRetries = 3;
- // Verify that the image was created
+ // Timeout in milliseconds (intentionally low to provoke a timeout)
+ const int timeoutMs = 100;
+
+ // ------------------------------------------------------------
+ // Generate a barcode image if it does not already exist
+ // ------------------------------------------------------------
if (!File.Exists(imagePath))
{
- Console.WriteLine($"Error: Barcode image was not created at '{imagePath}'.");
- return;
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ {
+ generator.Save(imagePath);
+ Console.WriteLine($"Barcode image generated at '{imagePath}'.");
+ }
+ }
+ else
+ {
+ Console.WriteLine($"Using existing barcode image at '{imagePath}'.");
}
- const int maxRetries = 3; // Maximum number of recognition attempts
- int attempt = 0; // Current attempt counter
- bool success = false; // Flag indicating successful recognition
+ int attempt = 0;
+ bool success = false;
- // Retry loop for barcode recognition
+ // ------------------------------------------------------------
+ // Attempt recognition with retry logic
+ // ------------------------------------------------------------
while (attempt < maxRetries && !success)
{
attempt++;
try
{
- // Initialize the reader without an image
- using (var reader = new BarCodeReader())
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
{
- // Set a short timeout to trigger RecognitionAbortedException on delay
- reader.Timeout = 500; // milliseconds
+ // Apply a short timeout to simulate a timeout scenario
+ reader.Timeout = timeoutMs;
- // Load the barcode image into the reader
- using (var bitmap = new Bitmap(imagePath))
+ // Perform recognition; iterate over all detected barcodes
+ foreach (var result in reader.ReadBarCodes())
{
- reader.SetBarCodeImage(bitmap);
-
- // Perform recognition and output each detected result
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"Attempt {attempt}: Detected barcode type '{result.CodeTypeName}' with text '{result.CodeText}'.");
- }
+ Console.WriteLine($"Attempt {attempt}: Detected barcode type: {result.CodeTypeName}");
+ Console.WriteLine($"Attempt {attempt}: Detected barcode text: {result.CodeText}");
}
- }
- // If we reach this point, recognition succeeded
- success = true;
+ // If we reach this point, recognition succeeded
+ success = true;
+ }
}
catch (RecognitionAbortedException ex)
{
- // Recognition timed out – log and retry
+ // Handle timeout-specific exception and retry
Console.WriteLine($"Attempt {attempt}: Recognition aborted due to timeout. Retrying... ({ex.Message})");
+ // Loop continues for next attempt
}
catch (Exception ex)
{
- // Any other unexpected exception stops the retry loop
+ // Handle any other unexpected errors and abort further attempts
Console.WriteLine($"Attempt {attempt}: Unexpected error: {ex.Message}");
break;
}
}
- // Final status message if all attempts failed
+ // ------------------------------------------------------------
+ // Final outcome reporting
+ // ------------------------------------------------------------
if (!success)
{
- Console.WriteLine("Failed to recognize the barcode after multiple attempts.");
+ Console.WriteLine($"Failed to recognize barcode after {maxRetries} attempts.");
}
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/create-powershell-script-that-invokes-barcodereader-via-net-core-to-process-barcode-images-and-output-confidence-scores.cs b/barcode-recognition-basics/create-powershell-script-that-invokes-barcodereader-via-net-core-to-process-barcode-images-and-output-confidence-scores.cs
index fa3d515..b42b72f 100644
--- a/barcode-recognition-basics/create-powershell-script-that-invokes-barcodereader-via-net-core-to-process-barcode-images-and-output-confidence-scores.cs
+++ b/barcode-recognition-basics/create-powershell-script-that-invokes-barcodereader-via-net-core-to-process-barcode-images-and-output-confidence-scores.cs
@@ -1,86 +1,85 @@
-// Title: Barcode Confidence Score Demo
-// Description: Demonstrates using Aspose.BarCode to read barcodes from images and display confidence and reading quality scores.
+// Title: Generate and Read Barcodes with Confidence Scores
+// Description: This example generates barcode images for several symbologies and then reads them using BarCodeReader to display confidence scores and reading quality.
+// Category-Description: Demonstrates Aspose.BarCode generation and recognition workflows. It showcases the BarcodeGenerator for creating PNG images and the BarCodeReader for extracting barcode data, confidence, and quality metrics. Developers working with barcode automation, batch processing, or quality assessment will find this pattern useful when integrating Aspose.BarCode into .NET Core applications.
// Prompt: Create a PowerShell script that invokes BarCodeReader via .NET Core to process barcode images and output confidence scores.
-// Tags: barcode symbology, reading, confidence, console, aspnet
+// Tags: barcode symbology, generation, recognition, confidence, readingquality, png, aspose.barcode, aspose.drawing
using System;
-using System.Collections.Generic;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
-namespace BarcodeConfidenceDemo
+///
+/// Demonstrates how to generate barcode images and then read them back,
+/// outputting confidence scores and reading quality information.
+///
+class Program
{
///
- /// Entry point for the barcode confidence demonstration application.
+ /// Entry point of the example. Generates sample barcodes, saves them as PNG files,
+ /// and reads each file to display detection details.
///
- class Program
+ static void Main()
{
- ///
- /// Main method processes command‑line arguments, generates a sample barcode if none are provided,
- /// reads each image, and outputs barcode type, text, confidence, and reading quality.
- ///
- /// Array of image file paths supplied via the command line.
- static void Main(string[] args)
+ // Define the directory where barcode images will be stored.
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(outputDir))
{
- // Collect image file paths from command‑line arguments.
- // If none are provided, generate a sample barcode image to demonstrate the workflow.
- var imagePaths = new List();
+ // Create the directory if it does not already exist.
+ Directory.CreateDirectory(outputDir);
+ }
+
+ // Define a set of sample barcodes to generate.
+ var samples = new (BaseEncodeType EncodeType, string CodeText, string FileName)[]
+ {
+ (EncodeTypes.Code128, "Sample12345", "code128.png"),
+ (EncodeTypes.QR, "https://example.com", "qr.png"),
+ (EncodeTypes.DataMatrix, "DM1234567890", "datamatrix.png")
+ };
- if (args.Length > 0)
+ // -----------------------------------------------------------------
+ // Generate barcode images and save them as PNG files.
+ // -----------------------------------------------------------------
+ foreach (var sample in samples)
+ {
+ string filePath = Path.Combine(outputDir, sample.FileName);
+ using (BarcodeGenerator generator = new BarcodeGenerator(sample.EncodeType, sample.CodeText))
{
- foreach (var arg in args)
- {
- if (!string.IsNullOrWhiteSpace(arg))
- {
- imagePaths.Add(arg);
- }
- }
+ // Save the generated barcode image in PNG format.
+ generator.Save(filePath, BarCodeImageFormat.Png);
}
- else
- {
- // No input files – create a temporary sample barcode image (Code128).
- const string sampleFile = "sample_barcode.png";
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
- {
- // Save the generated barcode to a PNG file.
- generator.Save(sampleFile);
- }
+ }
- imagePaths.Add(sampleFile);
- Console.WriteLine($"No input files supplied. Generated sample image: {sampleFile}");
+ // -----------------------------------------------------------------
+ // Read each generated image and output barcode details.
+ // -----------------------------------------------------------------
+ foreach (var sample in samples)
+ {
+ string filePath = Path.Combine(outputDir, sample.FileName);
+ if (!File.Exists(filePath))
+ {
+ Console.WriteLine($"File not found: {filePath}");
+ continue;
}
- // Process each image file.
- foreach (var imagePath in imagePaths)
+ // Initialize the reader for all supported barcode types.
+ using (BarCodeReader reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
{
- if (!File.Exists(imagePath))
- {
- Console.WriteLine($"Warning: File not found – {imagePath}");
- continue;
- }
+ // Apply normal quality settings for balanced performance.
+ reader.QualitySettings = QualitySettings.NormalQuality;
- // Initialize the reader for all supported symbologies.
- using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ // Iterate through all detected barcodes in the image.
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
- // Use the default NormalQuality preset.
- reader.QualitySettings = QualitySettings.NormalQuality;
-
- // Read all barcodes found in the image.
- foreach (var result in reader.ReadBarCodes())
- {
- // Output barcode details, including confidence and reading quality.
- Console.WriteLine($"File: {imagePath}");
- Console.WriteLine($" Type : {result.CodeTypeName}");
- Console.WriteLine($" CodeText : {result.CodeText}");
- Console.WriteLine($" Confidence : {result.Confidence}");
- Console.WriteLine($" ReadingQuality : {result.ReadingQuality}");
- Console.WriteLine();
- }
+ Console.WriteLine($"File: {sample.FileName}");
+ Console.WriteLine($" Type: {result.CodeTypeName}");
+ Console.WriteLine($" CodeText: {result.CodeText}");
+ Console.WriteLine($" Confidence: {result.Confidence}");
+ Console.WriteLine($" ReadingQuality: {result.ReadingQuality}");
}
}
-
- // Program completes automatically; no user interaction required.
}
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/create-unit-test-verifying-automatic-utf8-detection-works-for-generated-qr-code-containing-multilingual-text.cs b/barcode-recognition-basics/create-unit-test-verifying-automatic-utf8-detection-works-for-generated-qr-code-containing-multilingual-text.cs
index 228e219..efa2fab 100644
--- a/barcode-recognition-basics/create-unit-test-verifying-automatic-utf8-detection-works-for-generated-qr-code-containing-multilingual-text.cs
+++ b/barcode-recognition-basics/create-unit-test-verifying-automatic-utf8-detection-works-for-generated-qr-code-containing-multilingual-text.cs
@@ -1,78 +1,76 @@
-// Title: QR Code UTF-8 Automatic Detection Unit Test
-// Description: Demonstrates generating a QR code with multilingual text and verifies that automatic UTF-8 detection correctly decodes it.
+// Title: UTF-8 Detection Test for QR Code
+// Description: Demonstrates generating a QR code with multilingual text and verifying automatic UTF-8 detection during recognition.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator (EncodeTypes.QR) to create a QR code, and BarCodeReader (DecodeType.QR) to read it back. Developers often need to ensure correct character encoding handling for multilingual data, especially when automatic UTF-8 detection is required. The snippet highlights key API classes, typical use cases, and serves as a reference for building unit tests around encoding detection.
// Prompt: Create a unit test verifying automatic UTF8 detection works for a generated QR code containing multilingual text.
-// Tags: qr,utf-8,encoding,detection,barcode,generation,recognition,unit-test
+// Tags: qr, utf8 detection, barcode generation, barcode recognition, multilingual, aspose.barcode, unit test
using System;
using System.IO;
using System.Text;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that generates a QR code containing multilingual text,
-/// then reads it back with and without automatic UTF‑8 detection enabled.
+/// Contains the entry point that generates a QR code with multilingual text,
+/// then reads it back to verify that automatic UTF-8 detection works correctly.
///
class Program
{
///
- /// Entry point of the example. Generates a QR code, reads it twice,
- /// and prints the results to verify automatic UTF‑8 detection.
+ /// Generates a QR code containing Latin, Chinese, and Cyrillic characters,
+ /// saves it to a memory stream, and validates that the reader automatically
+ /// detects UTF-8 encoding and returns the original text.
///
static void Main()
{
- // Multilingual text (Russian + Chinese) to be encoded in the QR code.
- string originalText = "Привет 世界";
+ // Multilingual text containing Latin, Chinese, and Cyrillic characters.
+ string originalText = "Hello 世界 Привет";
// Use a memory stream to avoid file I/O.
- using (var ms = new MemoryStream())
+ using (var memoryStream = new MemoryStream())
{
- // ---------- QR code generation ----------
+ // Create a QR code generator.
using (var generator = new BarcodeGenerator(EncodeTypes.QR))
{
- // Encode the text using UTF‑8 (adds BOM if needed).
+ // Encode the text using UTF-8. This inserts the appropriate ECI identifier.
generator.SetCodeText(originalText, Encoding.UTF8);
- // Save the generated QR code as PNG into the memory stream.
- generator.Save(ms, BarCodeImageFormat.Png);
+
+ // Save the barcode image to the memory stream in PNG format.
+ generator.Save(memoryStream, BarCodeImageFormat.Png);
}
- // Reset the stream position so it can be read from the beginning.
- ms.Position = 0;
+ // Reset the stream position to the beginning for reading.
+ memoryStream.Position = 0;
- // ---------- Detection enabled ----------
- string detectedWithEncoding;
- using (var reader = new BarCodeReader(ms, DecodeType.QR))
+ // Initialize a reader for QR codes.
+ using (var reader = new BarCodeReader(memoryStream, DecodeType.QR))
{
- // Enable automatic UTF‑8 detection.
+ // Ensure automatic UTF-8 detection is enabled (default is true).
reader.BarcodeSettings.DetectEncoding = true;
- // Read all barcodes from the stream.
- var result = reader.ReadBarCodes();
- // Extract the decoded text if a barcode was found.
- detectedWithEncoding = result.Length > 0 ? result[0].CodeText : string.Empty;
- }
-
- // Reset the stream again for the second read operation.
- ms.Position = 0;
- // ---------- Detection disabled ----------
- string detectedWithoutEncoding;
- using (var reader = new BarCodeReader(ms, DecodeType.QR))
- {
- // Disable automatic UTF‑8 detection.
- reader.BarcodeSettings.DetectEncoding = false;
- var result = reader.ReadBarCodes();
- detectedWithoutEncoding = result.Length > 0 ? result[0].CodeText : string.Empty;
- }
+ bool detectionSucceeded = false;
- // Verify that detection works: with detection the text matches,
- // without detection it does not (due to encoding mismatch).
- bool detectionWorks = detectedWithEncoding == originalText && detectedWithoutEncoding != originalText;
+ // Iterate through all detected barcodes (should be only one).
+ foreach (var result in reader.ReadBarCodes())
+ {
+ if (result.CodeText == originalText)
+ {
+ detectionSucceeded = true;
+ Console.WriteLine("UTF-8 detection succeeded: " + result.CodeText);
+ }
+ else
+ {
+ Console.WriteLine($"Mismatch detected. Expected: '{originalText}', Got: '{result.CodeText}'");
+ }
+ }
- // Output the results to the console.
- Console.WriteLine("Original Text: " + originalText);
- Console.WriteLine("Detected (DetectEncoding=true): " + detectedWithEncoding);
- Console.WriteLine("Detected (DetectEncoding=false): " + detectedWithoutEncoding);
- Console.WriteLine("Automatic UTF-8 detection works: " + detectionWorks);
+ // Report overall test outcome.
+ if (!detectionSucceeded)
+ {
+ Console.WriteLine("UTF-8 detection failed.");
+ }
+ }
}
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/create-unit-tests-that-verify-abort-method-successfully-stops-recognition-within-specified-time-frame.cs b/barcode-recognition-basics/create-unit-tests-that-verify-abort-method-successfully-stops-recognition-within-specified-time-frame.cs
index 3586963..a7ccef6 100644
--- a/barcode-recognition-basics/create-unit-tests-that-verify-abort-method-successfully-stops-recognition-within-specified-time-frame.cs
+++ b/barcode-recognition-basics/create-unit-tests-that-verify-abort-method-successfully-stops-recognition-within-specified-time-frame.cs
@@ -1,91 +1,75 @@
-// Title: Demonstrate aborting barcode recognition with Aspose.BarCode
-// Description: Shows how to abort a long-running barcode recognition task and verify it stops within a time limit.
+// Title: Abort Barcode Recognition Example
+// Description: Demonstrates how to abort a barcode recognition operation using Aspose.BarCode's Abort method.
+// Category-Description: This example belongs to the Aspose.BarCode recognition category, showcasing the use of BarCodeReader, BarcodeGenerator, and the Abort method to control long‑running recognition tasks. Developers often need to stop recognition after a timeout or user cancellation, and this snippet illustrates setting a timeout, running recognition asynchronously, and aborting it safely.
// Prompt: Create unit tests that verify Abort method successfully stops recognition within a specified time frame.
-// Tags: barcode, symbology, code128, abort, recognition, unit-test, aspose.barcode
+// Tags: code128, abort, recognition, aspose.barcode, generation, timeout
using System;
-using System.Diagnostics;
+using System.IO;
using System.Threading.Tasks;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Example program that generates a large barcode, starts recognition,
-/// aborts it, and checks that the abort completes within a specified time frame.
+/// Demonstrates aborting a barcode recognition operation.
///
class Program
{
///
- /// Entry point of the program. Executes the abort verification logic.
+ /// Entry point that generates a barcode, starts recognition asynchronously, aborts it, and reports the outcome.
///
static void Main()
{
- // Generate a large barcode image to ensure recognition takes noticeable time.
- const string longText = "1234567890123456789012345678901234567890";
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, longText))
+ // Generate a barcode image in memory
+ using (var imageStream = new MemoryStream())
{
- // Use interpolation mode and set a large image size.
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- generator.Parameters.ImageWidth.Point = 2000f;
- generator.Parameters.ImageHeight.Point = 2000f;
-
- using (Bitmap barcodeImage = generator.GenerateBarCodeImage())
+ // Create a barcode generator for Code128 with sample text
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "TestAbort"))
{
- // Prepare the reader.
- using (var reader = new BarCodeReader())
- {
- // Assign the image to the reader.
- reader.SetBarCodeImage(barcodeImage);
- // Set a generous timeout (will be ignored because we abort).
- reader.Timeout = 10000;
+ // Save the generated barcode as PNG into the memory stream
+ generator.Save(imageStream, BarCodeImageFormat.Png);
+ // Reset stream position for reading
+ imageStream.Position = 0;
+ }
- // Measure the time taken for the recognition task.
- var stopwatch = Stopwatch.StartNew();
+ // Initialize a barcode reader with a long timeout (10 seconds)
+ using (var reader = new BarCodeReader(imageStream, DecodeType.Code128))
+ {
+ reader.Timeout = 10000; // Timeout in milliseconds
- // Run recognition in a separate task.
- var recognitionTask = Task.Run(() =>
+ // Start recognition on a separate task to allow aborting
+ var recognitionTask = Task.Run(() =>
+ {
+ try
{
- try
- {
- // Attempt to read barcodes.
- var results = reader.ReadBarCodes();
- // Return the number of detected barcodes (should be 0 if aborted early).
- return results.Length;
- }
- catch (RecognitionAbortedException)
- {
- // Expected when abort is successful.
- return -1;
- }
- });
-
- // Immediately request abort.
- reader.Abort();
-
- // Wait for the task to finish.
- recognitionTask.Wait();
-
- stopwatch.Stop();
-
- // Determine if abort stopped recognition quickly (within 2 seconds).
- bool isFast = stopwatch.Elapsed.TotalMilliseconds < 2000;
- bool isAborted = recognitionTask.Result == -1 || recognitionTask.Result == 0;
-
- if (isFast && isAborted)
+ // Perform synchronous read; may be aborted
+ var results = reader.ReadBarCodes();
+ Console.WriteLine($"Recognition completed, found {results.Length} barcode(s).");
+ }
+ catch (RecognitionAbortedException ex)
{
- Console.WriteLine("Test Passed: Abort stopped recognition within the expected time frame.");
+ // Expected path when abort is invoked
+ Console.WriteLine($"Recognition aborted after {ex.ExecutionTime} ms (expected).");
}
- else
+ catch (Exception ex)
{
- Console.WriteLine("Test Failed:");
- Console.WriteLine($" Elapsed time (ms): {stopwatch.Elapsed.TotalMilliseconds}");
- Console.WriteLine($" Recognition result count: {recognitionTask.Result}");
- Console.WriteLine(" Expected abort to stop quickly.");
+ // Log any unexpected errors
+ Console.WriteLine($"Unexpected exception: {ex.GetType().Name} - {ex.Message}");
}
- }
+ });
+
+ // Brief pause before aborting to ensure recognition has started
+ Task.Delay(100).Wait(); // 100 ms delay
+ // Request abort of the ongoing recognition
+ reader.Abort();
+
+ // Wait for the recognition task to complete
+ recognitionTask.Wait();
}
}
+
+ // Indicate that the abort test has finished
+ Console.WriteLine("Abort test completed.");
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/design-ui-component-that-displays-real-time-barcode-detection-results-using-foundbarcodes-property-updates.cs b/barcode-recognition-basics/design-ui-component-that-displays-real-time-barcode-detection-results-using-foundbarcodes-property-updates.cs
index 0e1280a..dce44d5 100644
--- a/barcode-recognition-basics/design-ui-component-that-displays-real-time-barcode-detection-results-using-foundbarcodes-property-updates.cs
+++ b/barcode-recognition-basics/design-ui-component-that-displays-real-time-barcode-detection-results-using-foundbarcodes-property-updates.cs
@@ -1,68 +1,79 @@
-// Title: Real‑time barcode detection demo
-// Description: This console example generates a Code128 barcode, reads it, and displays detection results, illustrating how the FoundBarCodes property can be used for UI updates.
+// Title: Real‑time barcode detection demo using FoundBarCodes
+// Description: Generates sample barcodes, recognizes them, and displays detection details such as type, text, confidence, and region.
+// Category-Description: Demonstrates Aspose.BarCode barcode generation and recognition workflow, focusing on the BarCodeReader class and its FoundBarCodes collection. This example shows how to create barcodes with BarcodeGenerator, decode them with BarCodeReader, and retrieve detailed detection results—common tasks for developers building scanning or verification features. Suitable for search queries about Aspose.BarCode recognition examples.
// Prompt: Design a UI component that displays real‑time barcode detection results using FoundBarCodes property updates.
-// Tags: barcode symbology, generation, recognition, foundbarcodes, console
+// Tags: barcode generation, barcode recognition, foundbarcodes, real-time detection, aspose.barcode, csharp
using System;
+using System.Collections.Generic;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Demonstrates barcode generation, recognition, and how to access detection results via the
-/// FoundBarCodes property, which can be bound to a UI component for real‑time updates.
+/// Demonstrates generating various barcode types, recognizing them, and outputting detailed detection results.
///
class Program
{
///
- /// Entry point of the console application. Generates a barcode, reads it, and prints detection details.
+ /// Entry point of the demo. Generates sample barcodes, reads them, and prints detection information.
///
static void Main()
{
- // NOTE: The original task mentions a UI component for real‑time updates.
- // In this console example we simulate the process by generating a barcode,
- // reading it, and printing the detection results immediately.
+ // Define a collection of sample barcodes with their symbology and data.
+ var samples = new List<(BaseEncodeType EncodeType, string CodeText)>
+ {
+ (EncodeTypes.Code128, "ABC123456"),
+ (EncodeTypes.QR, "https://example.com"),
+ (EncodeTypes.DataMatrix, "DataMatrixSample"),
+ (EncodeTypes.Pdf417, "PDF417 Sample Text")
+ };
- // Create a barcode generator for Code128 with sample text.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ // Process each sample: generate, recognize, and display results.
+ foreach (var sample in samples)
{
- // Generate the barcode image in memory.
- using (var barcodeImage = generator.GenerateBarCodeImage())
+ // Generate a barcode image and store it in a memory stream.
+ using (var generator = new BarcodeGenerator(sample.EncodeType, sample.CodeText))
{
- // Initialize a reader that scans for all supported symbologies.
- using (var reader = new BarCodeReader(barcodeImage, DecodeType.AllSupportedTypes))
+ // Use default generation settings; customize here if needed.
+ using (var ms = new MemoryStream())
{
- // Perform the recognition.
- var results = reader.ReadBarCodes();
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0; // Reset stream position for reading.
- // The FoundBarCodes property holds the same results after reading.
- // Display each detected barcode's details.
- Console.WriteLine($"Detected {reader.FoundCount} barcode(s):");
- int index = 0;
- foreach (var result in results)
+ // Initialize a barcode reader to recognize the generated image.
+ using (var reader = new BarCodeReader())
{
- Console.WriteLine($"--- Barcode #{++index} ---");
- Console.WriteLine($"Type : {result.CodeTypeName}");
- Console.WriteLine($"CodeText : {result.CodeText}");
- Console.WriteLine($"Confidence : {result.Confidence}");
- Console.WriteLine($"Quality : {result.ReadingQuality}");
- 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}");
- }
+ // Configure the reader to detect all supported symbologies.
+ reader.BarCodeReadType = DecodeType.AllSupportedTypes;
+ reader.SetBarCodeImage(ms);
- // Demonstrate accessing the FoundBarCodes array directly.
- Console.WriteLine("\nAccessing FoundBarCodes property directly:");
- for (int i = 0; i < reader.FoundCount; i++)
- {
- var fb = reader.FoundBarCodes[i];
- Console.WriteLine($"FoundBarCodes[{i}] Type={fb.CodeTypeName}, Text={fb.CodeText}");
+ // Perform the recognition operation.
+ reader.ReadBarCodes();
+
+ // Output detection summary for the current sample.
+ Console.WriteLine($"--- Results for {sample.EncodeType.TypeName} ---");
+ Console.WriteLine($"FoundCount: {reader.FoundCount}");
+
+ // Iterate through each detected barcode and display its details.
+ foreach (var result in reader.FoundBarCodes)
+ {
+ Console.WriteLine($"Type: {result.CodeTypeName}");
+ Console.WriteLine($"Text: {result.CodeText}");
+ Console.WriteLine($"Confidence: {result.Confidence}");
+ Console.WriteLine($"ReadingQuality: {result.ReadingQuality}");
+ var rect = result.Region.Rectangle;
+ Console.WriteLine($"Region: X={rect.X}, Y={rect.Y}, Width={rect.Width}, Height={rect.Height}");
+ Console.WriteLine();
+ }
}
}
}
}
- // Program ends here; no external input or infinite loops are used.
+ // Indicate that the demo has finished executing.
+ Console.WriteLine("Barcode detection demo completed.");
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/develop-backend-service-that-receives-base64-encoded-barcode-images-decodes-them-with-detectencoding-enabled-and-returns.cs b/barcode-recognition-basics/develop-backend-service-that-receives-base64-encoded-barcode-images-decodes-them-with-detectencoding-enabled-and-returns.cs
index a1d6abf..925d552 100644
--- a/barcode-recognition-basics/develop-backend-service-that-receives-base64-encoded-barcode-images-decodes-them-with-detectencoding-enabled-and-returns.cs
+++ b/barcode-recognition-basics/develop-backend-service-that-receives-base64-encoded-barcode-images-decodes-them-with-detectencoding-enabled-and-returns.cs
@@ -1,60 +1,59 @@
-// Title: QR barcode generation, Base64 encoding, and decoding with encoding detection
-// Description: Demonstrates generating a QR barcode, converting it to a Base64 string, then decoding it back while detecting Unicode text encoding.
+// Title: Decode Base64‑Encoded Code128 Barcode with DetectEncoding
+// Description: Demonstrates receiving a Base64‑encoded barcode image, decoding it using Aspose.BarCode with DetectEncoding enabled, and outputting the decoded text.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing how to use BarCodeReader and BarcodeGenerator for end‑to‑end barcode processing. Typical use cases include backend services that accept barcode images (e.g., from mobile apps) and need to extract encoded information. Developers often need to handle various image formats, enable encoding detection, and process multiple symbologies.
// Prompt: Develop a backend service that receives base64‑encoded barcode images, decodes them with DetectEncoding enabled, and returns decoded text.
-// Tags: qr, barcode, base64, encoding detection, aspnet, aspose.barcode, csharp
+// Tags: code128, decode, text, barcodegenerator, barcodereader, aspose.barcode
using System;
using System.IO;
using System.Text;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
+using Aspose.BarCode;
///
-/// Example program that generates a QR barcode, encodes it to Base64, and decodes it with encoding detection enabled.
+/// Example program that generates a Code128 barcode, encodes it to Base64,
+/// decodes the Base64 string back to an image, and reads the barcode text
+/// with encoding detection enabled.
///
class Program
{
///
- /// Entry point. Generates a QR barcode from sample Unicode text, converts it to Base64, then reads it back detecting encoding.
+ /// Entry point of the example. Performs barcode generation, Base64 conversion,
+ /// and barcode recognition with DetectEncoding set to true.
///
static void Main()
{
- // Sample text containing Unicode characters to test encoding detection.
- const string sampleText = "Привет";
+ // Define the text to encode in the barcode.
+ string sampleText = "HelloWorld";
- // Generate a QR barcode image and encode it to a Base64 string.
- string base64Image;
- using (var generator = new BarcodeGenerator(EncodeTypes.QR, sampleText))
+ // Create a barcode generator for Code128 symbology.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, sampleText))
{
- using (var ms = new MemoryStream())
+ // Store the generated barcode image in a memory stream as PNG.
+ using (var imageStream = new MemoryStream())
{
- // Save the barcode as PNG into the memory stream.
- generator.Save(ms, BarCodeImageFormat.Png);
- // Convert the PNG bytes to a Base64 string.
- base64Image = Convert.ToBase64String(ms.ToArray());
- }
- }
-
- // Output the Base64 string (optional, can be removed in production).
- Console.WriteLine("Base64 Barcode Image:");
- Console.WriteLine(base64Image);
- Console.WriteLine();
+ generator.Save(imageStream, BarCodeImageFormat.Png);
- // Decode the Base64 string back to an image stream.
- byte[] imageBytes = Convert.FromBase64String(base64Image);
- using (var imageStream = new MemoryStream(imageBytes))
- {
- // Create a barcode reader that checks all supported symbologies.
- using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes))
- {
- // Enable detection of text encoding for Unicode code sets.
- reader.BarcodeSettings.DetectEncoding = true;
+ // Convert the image bytes to a Base64 string (simulating received data).
+ string base64Image = Convert.ToBase64String(imageStream.ToArray());
- // Read and output all detected barcodes.
- foreach (var result in reader.ReadBarCodes())
+ // Decode the Base64 string back to raw image bytes.
+ byte[] imageBytes = Convert.FromBase64String(base64Image);
+ using (var decodeStream = new MemoryStream(imageBytes))
{
- Console.WriteLine("Decoded Text: " + result.CodeText);
+ // Initialize a barcode reader that supports all barcode types.
+ using (var reader = new BarCodeReader(decodeStream, DecodeType.AllSupportedTypes))
+ {
+ // Enable automatic detection of character encoding (e.g., UTF‑8).
+ reader.BarcodeSettings.DetectEncoding = true;
+
+ // Iterate through all detected barcodes and output their decoded text.
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine("Decoded Text: " + result.CodeText);
+ }
+ }
}
}
}
diff --git a/barcode-recognition-basics/develop-console-application-that-reads-barcodes-from-list-of-file-paths-supplied-via-command-line.cs b/barcode-recognition-basics/develop-console-application-that-reads-barcodes-from-list-of-file-paths-supplied-via-command-line.cs
index a905387..399d93f 100644
--- a/barcode-recognition-basics/develop-console-application-that-reads-barcodes-from-list-of-file-paths-supplied-via-command-line.cs
+++ b/barcode-recognition-basics/develop-console-application-that-reads-barcodes-from-list-of-file-paths-supplied-via-command-line.cs
@@ -1,39 +1,73 @@
-// Title: Read Barcodes from Image Files via Command Line
-// Description: The console app iterates over image file paths supplied as command‑line arguments, detects any barcodes using Aspose.BarCode, and prints their type and value.
+// Title: Barcode Reader Console Example
+// Description: Demonstrates reading barcodes from image files supplied via command line, generating sample images when none are provided.
+// Category-Description: This example belongs to the Aspose.BarCode reading category, showcasing the BarCodeReader class to decode all supported symbologies. Typical use cases include batch processing of scanned documents or image files to extract embedded data. Developers often need to iterate over file collections, handle missing files, and output decoded information, which this sample illustrates.
// Prompt: Develop a console application that reads barcodes from a list of file paths supplied via command line.
-// Tags: barcode, read, console, aspose.barcode, decode, file-io
+// Tags: barcode, reading, console, batch, aspose.barcode, decode, all-supported-types
using System;
-using System.Collections.Generic;
using System.IO;
+using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates how to read barcodes from image files whose paths are provided via command‑line arguments.
+/// Console application that reads barcodes from image files provided via command line.
+/// Generates sample barcode images if no arguments are supplied.
///
class Program
{
///
- /// Entry point of the application. Processes each supplied file path, attempts to read any barcodes,
- /// and writes the results to the console.
+ /// Entry point. Accepts file paths as arguments, reads barcodes using BarCodeReader, and writes results to console.
///
- /// Array of file paths passed as command‑line arguments.
+ /// Array of file paths to process.
static void Main(string[] args)
{
- // Build a list of file paths: use command‑line arguments if present, otherwise fall back to sample names.
- var filePaths = new List();
- if (args != null && args.Length > 0)
+ string[] filePaths;
+
+ // If no command‑line arguments are provided, generate sample barcode images.
+ if (args.Length == 0)
{
- filePaths.AddRange(args);
+ // Create a folder for sample images in the current working directory.
+ string sampleDir = Path.Combine(Directory.GetCurrentDirectory(), "SampleBarcodes");
+ Directory.CreateDirectory(sampleDir);
+
+ // Prepare an array to hold the generated sample file paths.
+ string[] samples = new string[3];
+
+ // ---- Sample Code128 barcode ----
+ string code128Path = Path.Combine(sampleDir, "code128.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ {
+ generator.Save(code128Path);
+ }
+ samples[0] = code128Path;
+
+ // ---- Sample QR code ----
+ string qrPath = Path.Combine(sampleDir, "qr.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"))
+ {
+ generator.Save(qrPath);
+ }
+ samples[1] = qrPath;
+
+ // ---- Sample DataMatrix barcode ----
+ string dmPath = Path.Combine(sampleDir, "datamatrix.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "DM12345"))
+ {
+ generator.Save(dmPath);
+ }
+ samples[2] = dmPath;
+
+ // Use the generated samples as the input file list.
+ filePaths = samples;
}
else
{
- // Sample file names – the program will report if they are missing.
- filePaths.Add("sample1.png");
- filePaths.Add("sample2.png");
+ // Use the command‑line arguments as the input file list.
+ filePaths = args;
}
- // Process each file path individually.
+ // Process each file path in the list.
foreach (var path in filePaths)
{
// Verify that the file exists before attempting to read it.
@@ -43,34 +77,26 @@ static void Main(string[] args)
continue;
}
- try
+ // Open the image with BarCodeReader, requesting all supported barcode types.
+ using (var reader = new BarCodeReader(path, DecodeType.AllSupportedTypes))
{
- // Create a BarCodeReader that scans for all supported barcode types in the image.
- using (var reader = new BarCodeReader(path, DecodeType.AllSupportedTypes))
- {
- // Read all barcodes found in the image.
- var results = reader.ReadBarCodes();
+ // Read all barcodes present in the image.
+ var results = reader.ReadBarCodes();
- // If no barcodes were detected, inform the user.
- if (results.Length == 0)
- {
- Console.WriteLine($"No barcodes detected in file: {path}");
- }
- else
+ // Output the results to the console.
+ if (results.Length == 0)
+ {
+ Console.WriteLine($"No barcode detected in file: {path}");
+ }
+ else
+ {
+ Console.WriteLine($"Barcodes found in file: {path}");
+ foreach (var result in results)
{
- // Output each detected barcode's type and decoded text.
- foreach (var result in results)
- {
- Console.WriteLine($"File: {path} | Type: {result.CodeTypeName} | Text: {result.CodeText}");
- }
+ Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}");
}
}
}
- catch (Exception ex)
- {
- // Report any unexpected errors that occur during processing.
- Console.WriteLine($"Error processing file '{path}': {ex.Message}");
- }
}
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/develop-windows-service-that-monitors-folder-reads-incoming-barcode-images-and-logs-quality-metrics.cs b/barcode-recognition-basics/develop-windows-service-that-monitors-folder-reads-incoming-barcode-images-and-logs-quality-metrics.cs
index 2e77edd..1117fb6 100644
--- a/barcode-recognition-basics/develop-windows-service-that-monitors-folder-reads-incoming-barcode-images-and-logs-quality-metrics.cs
+++ b/barcode-recognition-basics/develop-windows-service-that-monitors-folder-reads-incoming-barcode-images-and-logs-quality-metrics.cs
@@ -1,96 +1,98 @@
-// Title: Folder Monitoring Barcode Reader
-// Description: Demonstrates reading barcode images from a folder and logging quality metrics for each detected barcode.
+// Title: Barcode generation, recognition, and logging example
+// Description: Demonstrates creating barcode images, reading them, and logging quality metrics to a file.
+// Category-Description: This example belongs to the Aspose.BarCode image processing category, showcasing how to generate barcodes, recognize multiple symbologies, and extract reading quality using BarcodeGenerator, BarCodeReader, and related classes. Developers often need to batch‑process barcode images, monitor directories, and log results for quality assurance or analytics, making this pattern useful for automation scripts and services.
// Prompt: Develop a Windows service that monitors a folder, reads incoming barcode images, and logs quality metrics.
-// Tags: barcode symbology, reading, console, aspose.barcode, folder monitoring
+// Tags: barcode generation, barcode recognition, quality metrics, file monitoring, aspose.barcode, csharp
using System;
using System.IO;
using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Simple console application that scans a folder for barcode images,
-/// reads any barcodes using Aspose.BarCode, and logs quality metrics.
+/// Demonstrates generating sample barcode images, reading them, and logging quality metrics.
///
class Program
{
///
- /// Entry point. Accepts an optional folder path argument, processes up to five image files,
- /// and writes barcode type, text, reading quality, and confidence to the console.
+ /// Entry point of the application. Generates barcodes, reads them, and writes log entries.
///
- /// Command‑line arguments; first argument may specify the folder to monitor.
- static void Main(string[] args)
+ static void Main()
{
- // Determine the folder to monitor. Use a default if not provided.
- string folderPath = args.Length > 0 ? args[0] : "Barcodes";
+ // Define the folder to store and read barcode images
+ string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ Directory.CreateDirectory(folderPath);
- // Verify that the folder exists before proceeding.
- if (!Directory.Exists(folderPath))
+ // Path for the log file
+ string logFilePath = Path.Combine(folderPath, "barcode_log.txt");
+
+ // Sample barcode data to generate
+ string[] sampleCodes = new string[]
{
- Console.WriteLine($"Folder not found: {folderPath}");
- return;
- }
+ "CODE128-12345",
+ "QR-HELLO",
+ "DATAMATRIX-987654321"
+ };
- // Define supported image extensions and collect up to five matching files.
- string[] supportedExtensions = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".gif" };
- string[] allFiles = Directory.GetFiles(folderPath);
- var imageFiles = new System.Collections.Generic.List();
- foreach (var file in allFiles)
+ // Generate sample barcode images
+ foreach (string code in sampleCodes)
{
- if (imageFiles.Count >= 5) break; // Limit to five files.
- if (Array.Exists(supportedExtensions, ext => ext.Equals(Path.GetExtension(file), StringComparison.OrdinalIgnoreCase)))
+ // Choose symbology based on code prefix
+ BaseEncodeType encodeType;
+ if (code.StartsWith("CODE128"))
+ encodeType = EncodeTypes.Code128;
+ else if (code.StartsWith("QR"))
+ encodeType = EncodeTypes.QR;
+ else
+ encodeType = EncodeTypes.DataMatrix;
+
+ string fileName = $"{code}.png";
+ string filePath = Path.Combine(folderPath, fileName);
+
+ // Create and save the barcode image as PNG
+ using (var generator = new BarcodeGenerator(encodeType, code))
{
- imageFiles.Add(file);
+ generator.Save(filePath);
}
}
- // If no supported images were found, inform the user and exit.
- if (imageFiles.Count == 0)
- {
- Console.WriteLine("No barcode image files found in the folder.");
- return;
- }
-
- // Process each image file individually.
- foreach (var imagePath in imageFiles)
+ // Process each PNG file in the folder
+ string[] imageFiles = Directory.GetFiles(folderPath, "*.png");
+ foreach (string imageFile in imageFiles)
{
- // Ensure the file still exists before attempting to read it.
- if (!File.Exists(imagePath))
+ if (!File.Exists(imageFile))
{
- Console.WriteLine($"File not found: {imagePath}");
+ Console.WriteLine($"File not found: {imageFile}");
continue;
}
- Console.WriteLine($"Processing file: {Path.GetFileName(imagePath)}");
-
- // Create a barcode reader for the image, enabling all supported decode types.
- using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ // Initialize the barcode reader for all supported types
+ using (var reader = new BarCodeReader(imageFile, DecodeType.AllSupportedTypes))
{
- // Apply normal quality settings for reading.
- reader.QualitySettings = QualitySettings.NormalQuality;
-
- // Attempt to read all barcodes present in the image.
- var results = reader.ReadBarCodes();
-
- // If no barcodes were detected, report and continue to the next file.
- if (results == null || results.Length == 0)
+ // Read all barcodes in the image
+ foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine(" No barcodes detected.");
- continue;
- }
+ // Prepare log entry with file name, barcode type, text, and quality
+ string logEntry = $"File: {Path.GetFileName(imageFile)} | Type: {result.CodeTypeName} | Text: {result.CodeText} | Quality: {result.ReadingQuality}";
- // Log quality metrics for each detected barcode.
- foreach (var result in results)
- {
- Console.WriteLine($" Type: {result.CodeTypeName}");
- Console.WriteLine($" CodeText: {result.CodeText}");
- Console.WriteLine($" ReadingQuality: {result.ReadingQuality}%");
- Console.WriteLine($" Confidence: {result.Confidence}");
+ // Output to console for immediate feedback
+ Console.WriteLine(logEntry);
+
+ // Append the log entry to the log file
+ try
+ {
+ File.AppendAllText(logFilePath, logEntry + Environment.NewLine);
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Failed to write log: {ex.Message}");
+ }
}
}
}
- // Indicate that processing of all files has completed.
- Console.WriteLine("Processing completed.");
+ // Indicate completion of processing
+ Console.WriteLine("Barcode processing completed.");
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/disable-detectencoding-and-manually-decode-raw-byte-data-using-encodingutf16-for-unicode-2d-barcodes.cs b/barcode-recognition-basics/disable-detectencoding-and-manually-decode-raw-byte-data-using-encodingutf16-for-unicode-2d-barcodes.cs
index aeecab7..48a8fd7 100644
--- a/barcode-recognition-basics/disable-detectencoding-and-manually-decode-raw-byte-data-using-encodingutf16-for-unicode-2d-barcodes.cs
+++ b/barcode-recognition-basics/disable-detectencoding-and-manually-decode-raw-byte-data-using-encodingutf16-for-unicode-2d-barcodes.cs
@@ -1,65 +1,55 @@
-// Title: Demonstrate manual UTF-16 decoding of Unicode QR code without auto-detect
-// Description: Shows how to generate a QR code with Unicode text, disable automatic encoding detection, and manually decode the raw byte data using Encoding.Unicode (UTF-16). Useful for handling 2D barcodes that contain Unicode characters.
+// Title: Disable DetectEncoding and manually decode Unicode QR barcode
+// Description: Demonstrates generating a QR code with UTF-16 text, disabling automatic encoding detection during recognition, and manually decoding the raw bytes using Encoding.Unicode.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on custom encoding handling. It showcases the use of BarcodeGenerator, BarCodeReader, and related settings to control encoding detection, a common requirement when working with Unicode 2D barcodes such as QR codes. Developers often need to disable automatic detection to process raw byte data and apply specific character encodings.
// Prompt: Disable DetectEncoding and manually decode raw byte data using Encoding.UTF16 for Unicode 2D barcodes.
-// Tags: qr, unicode, manual-decoding, detectencoding, encoding.unicode, aspose.barcode
+// Tags: qr, unicode, encoding, detectencoding, manualdecode, generation, recognition, aspose.barcode
using System;
using System.IO;
using System.Text;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that generates a QR code containing Unicode text,
-/// disables automatic encoding detection during reading, and manually
-/// decodes the raw byte data using UTF-16 (Encoding.Unicode).
+/// Demonstrates disabling automatic encoding detection and manually decoding raw byte data for a Unicode QR barcode.
///
class Program
{
///
- /// Entry point of the example. Generates a QR code, reads it back,
- /// and demonstrates manual decoding of the barcode text.
+ /// Entry point. Generates a QR code with UTF-16 text, reads it without encoding detection, and decodes using Encoding.Unicode.
///
static void Main()
{
- // Sample Unicode text to encode in the QR code
- const string unicodeText = "Привет";
+ // Original Unicode text to encode
+ const string originalText = "Привет";
- // Create a QR code generator and set the code text using UTF-16 encoding
+ // Create a QR code generator
using (var generator = new BarcodeGenerator(EncodeTypes.QR))
{
- generator.SetCodeText(unicodeText, Encoding.Unicode);
+ // Encode the text as UTF-16 (Unicode) bytes
+ generator.SetCodeText(originalText, Encoding.Unicode);
- // Save the generated barcode to a memory stream in PNG format
+ // Save the generated barcode image to a memory stream (PNG format)
using (var ms = new MemoryStream())
{
generator.Save(ms, BarCodeImageFormat.Png);
ms.Position = 0; // Reset stream position for reading
- // Initialize a barcode reader for QR codes, using the memory stream as input
+ // Initialize a barcode reader for QR codes
using (var reader = new BarCodeReader(ms, DecodeType.QR))
{
- // Disable automatic detection of the text encoding
+ // Turn off automatic detection of the text encoding
reader.BarcodeSettings.DetectEncoding = false;
- // Read all barcodes found in the image
- var results = reader.ReadBarCodes();
- if (results.Length == 0)
+ // Iterate through all detected barcodes in the image
+ foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine("No barcode detected.");
- return;
- }
-
- // Process each detected barcode result
- foreach (var result in results)
- {
- // When DetectEncoding is disabled, CodeText may contain garbled data
- Console.WriteLine("Raw CodeText (auto-detect disabled): " + result.CodeText);
+ // Display the raw CodeText (may appear garbled because DetectEncoding is disabled)
+ Console.WriteLine("Raw CodeText: " + result.CodeText);
- // Manually decode the raw byte data using UTF-16 (Encoding.Unicode)
+ // Manually decode the raw bytes using UTF-16 (Unicode) encoding
string decodedText = result.GetCodeText(Encoding.Unicode);
- Console.WriteLine("Manually decoded text (UTF-16): " + decodedText);
+ Console.WriteLine("Decoded with UTF-16: " + decodedText);
}
}
}
diff --git a/barcode-recognition-basics/enable-barcodereaderdetectencoding-to-true-and-read-utf8-encoded-pdf417-barcodes-without-manual-conversion.cs b/barcode-recognition-basics/enable-barcodereaderdetectencoding-to-true-and-read-utf8-encoded-pdf417-barcodes-without-manual-conversion.cs
index 7c3f775..25d832a 100644
--- a/barcode-recognition-basics/enable-barcodereaderdetectencoding-to-true-and-read-utf8-encoded-pdf417-barcodes-without-manual-conversion.cs
+++ b/barcode-recognition-basics/enable-barcodereaderdetectencoding-to-true-and-read-utf8-encoded-pdf417-barcodes-without-manual-conversion.cs
@@ -1,7 +1,8 @@
-// Title: Read UTF-8 PDF417 Barcodes with Automatic Encoding Detection
-// Description: Demonstrates generating a PDF417 barcode containing UTF-8 Cyrillic text and reading it back using BarCodeReader with DetectEncoding enabled, eliminating manual conversion.
+// Title: Read UTF-8 PDF417 barcode with automatic encoding detection
+// Description: Demonstrates enabling DetectEncoding on BarCodeReader to correctly decode UTF-8 encoded PDF417 barcodes.
+// Category-Description: This example belongs to the Aspose.BarCode barcode reading category, focusing on decoding PDF417 symbology with Unicode text. It showcases the use of BarcodeGenerator for creating barcodes, BarCodeReader for scanning, and the DetectEncoding setting to handle UTF-8 data automatically. Developers often need to read barcodes containing non‑ASCII characters without manual byte‑to‑string conversion.
// Prompt: Enable BarCodeReader.DetectEncoding to true and read UTF8 encoded PDF417 barcodes without manual conversion.
-// Tags: pdf417, barcode, encoding, detection, aspnet, csharp
+// Tags: pdf417, barcode, encoding detection, utf8, read, generation, aspose.barcode
using System;
using System.IO;
@@ -11,46 +12,44 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that creates a PDF417 barcode with UTF‑8 encoded text
-/// and reads it back using automatic encoding detection.
+/// Demonstrates generating a PDF417 barcode with UTF‑8 text and reading it back using automatic encoding detection.
///
class Program
{
///
- /// Entry point. Generates a barcode, then decodes it while automatically detecting the text encoding.
+ /// Entry point. Generates a barcode image, verifies its creation, and reads the encoded text.
///
static void Main()
{
- // Sample UTF-8 text containing Cyrillic characters
- const string utf8Text = "Пример UTF-8 текста";
+ // Path for the generated barcode image
+ string imagePath = "pdf417.png";
- // Generate a PDF417 barcode with UTF-8 encoding and store it in a memory stream
- using (var barcodeStream = new MemoryStream())
+ // Create a PDF417 barcode with UTF-8 encoded text
+ using (var generator = new BarcodeGenerator(EncodeTypes.Pdf417, string.Empty))
{
- // Create a barcode generator for PDF417 symbology
- using (var generator = new BarcodeGenerator(EncodeTypes.Pdf417))
- {
- // Encode the text using UTF-8 (adds BOM if needed)
- generator.SetCodeText(utf8Text, Encoding.UTF8);
- // Save the barcode image to the stream in PNG format
- generator.Save(barcodeStream, BarCodeImageFormat.Png);
- }
+ // Set Unicode text using UTF-8 encoding
+ generator.SetCodeText("Привет мир", Encoding.UTF8);
+ // Save the barcode image as PNG
+ generator.Save(imagePath, BarCodeImageFormat.Png);
+ }
+
+ // Verify that the image was created
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine($"Error: Barcode image '{imagePath}' was not created.");
+ return;
+ }
- // Reset stream position before reading
- barcodeStream.Position = 0;
+ // Read the barcode and enable automatic encoding detection
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Pdf417))
+ {
+ // Ensure DetectEncoding is enabled (default is true, but set explicitly)
+ reader.BarcodeSettings.DetectEncoding = true;
- // Create a reader for PDF417 barcodes from the stream
- using (var reader = new BarCodeReader(barcodeStream, DecodeType.Pdf417))
+ // Process detected barcodes
+ foreach (var result in reader.ReadBarCodes())
{
- // Enable automatic detection of the text encoding
- reader.BarcodeSettings.DetectEncoding = true;
-
- // Read all barcodes found in the image
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}");
- Console.WriteLine($"Decoded Text: {result.CodeText}");
- }
+ Console.WriteLine($"Decoded CodeText: {result.CodeText}");
}
}
}
diff --git a/barcode-recognition-basics/generate-barcode-with-barcodegenerator-then-read-it-using-checksumvalidationoff-to-observe-false-positive-detections.cs b/barcode-recognition-basics/generate-barcode-with-barcodegenerator-then-read-it-using-checksumvalidationoff-to-observe-false-positive-detections.cs
index 9122ccf..2caf463 100644
--- a/barcode-recognition-basics/generate-barcode-with-barcodegenerator-then-read-it-using-checksumvalidationoff-to-observe-false-positive-detections.cs
+++ b/barcode-recognition-basics/generate-barcode-with-barcodegenerator-then-read-it-using-checksumvalidationoff-to-observe-false-positive-detections.cs
@@ -1,7 +1,8 @@
-// Title: EAN13 Barcode Generation and Recognition with Checksum Validation Disabled
-// Description: This example generates a valid EAN13 barcode image, then reads it with checksum validation turned off to demonstrate false‑positive detection.
+// Title: Generate Code128 barcode and read with checksum validation off
+// Description: Demonstrates creating a Code128 barcode image and reading it while disabling checksum validation to show false positive detection handling.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, illustrating the use of BarcodeGenerator for image creation and BarCodeReader with customizable settings such as ChecksumValidation. Developers often need to generate barcodes, save them in various formats, and later decode them while controlling validation behavior to handle imperfect scans or custom checksum requirements.
// Prompt: Generate a barcode with BarcodeGenerator, then read it using ChecksumValidation.Off to observe false positive detections.
-// Tags: ean13, barcode generation, barcode recognition, checksumvalidation, off, aspnet, c#
+// Tags: code128, barcode generation, barcode recognition, checksumvalidation, off, png, aspose.barcode
using System;
using System.IO;
@@ -10,59 +11,51 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates how to generate an EAN13 barcode and read it with checksum validation disabled,
-/// which can lead to false‑positive detections.
+/// Demonstrates barcode generation and reading with checksum validation disabled.
///
class Program
{
///
- /// Entry point of the example. Generates a barcode image, verifies its creation,
- /// and then reads it with to show the effect on detection.
+ /// Entry point. Generates a Code128 barcode image, then reads it with checksum validation turned off.
///
static void Main()
{
- // Path where the generated barcode image will be saved
- string barcodePath = "barcode.png";
+ // Define the file path where the barcode image will be saved
+ string imagePath = "sample.png";
- // ------------------------------------------------------------
- // Generate an EAN13 barcode with a valid code text (includes correct checksum)
- // ------------------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.EAN13, "1234567890128"))
+ // Create a Code128 barcode containing the specified data and save it as a PNG file
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789012"))
{
- // Save the generated barcode image to the specified file
- generator.Save(barcodePath);
+ // Persist the generated barcode image to disk
+ generator.Save(imagePath, BarCodeImageFormat.Png);
}
- // ------------------------------------------------------------
- // Verify that the barcode image was successfully created
- // ------------------------------------------------------------
- if (!File.Exists(barcodePath))
+ // Verify that the image file was successfully created
+ if (!File.Exists(imagePath))
{
- Console.WriteLine($"Failed to create barcode image at '{barcodePath}'.");
+ Console.WriteLine($"Failed to create barcode image at {imagePath}");
return;
}
- // ------------------------------------------------------------
- // Read the barcode with checksum validation turned OFF (false positive detection)
- // ------------------------------------------------------------
- using (var reader = new BarCodeReader(barcodePath, DecodeType.EAN13))
+ // Initialize a barcode reader for the saved image, targeting Code128 symbology
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
{
- // Disable checksum validation to allow detection of potentially invalid barcodes
+ // Turn off checksum validation to allow detection of barcodes even when checksums are incorrect
reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.Off;
- // Perform recognition and iterate over all detected barcodes
+ // Iterate through all detected barcodes in the image
foreach (var result in reader.ReadBarCodes())
{
- // Output the raw code text detected in the barcode
- Console.WriteLine($"Detected CodeText: {result.CodeText}");
-
- // Extended data for 1D barcodes: separate value and checksum components
- Console.WriteLine($"Value: {result.Extended.OneD.Value}");
- Console.WriteLine($"Checksum: {result.Extended.OneD.CheckSum}");
-
- // Additional quality metrics provided by the recognizer
- Console.WriteLine($"Confidence: {result.Confidence}");
- Console.WriteLine($"ReadingQuality: {result.ReadingQuality}");
+ // Output basic barcode information
+ Console.WriteLine($"Detected Type: {result.CodeType}");
+ Console.WriteLine($"CodeText: {result.CodeText}");
+
+ // If extended 1D barcode data is available, display value and checksum details
+ if (result.Extended != null && result.Extended.OneD != null)
+ {
+ Console.WriteLine($"Value: {result.Extended.OneD.Value}");
+ Console.WriteLine($"Checksum: {result.Extended.OneD.CheckSum}");
+ }
}
}
}
diff --git a/barcode-recognition-basics/generate-report-summarizing-distribution-of-confidence-enumerations-across-large-dataset-of-scanned-barcodes.cs b/barcode-recognition-basics/generate-report-summarizing-distribution-of-confidence-enumerations-across-large-dataset-of-scanned-barcodes.cs
index 9b0e0c2..ebed1e0 100644
--- a/barcode-recognition-basics/generate-report-summarizing-distribution-of-confidence-enumerations-across-large-dataset-of-scanned-barcodes.cs
+++ b/barcode-recognition-basics/generate-report-summarizing-distribution-of-confidence-enumerations-across-large-dataset-of-scanned-barcodes.cs
@@ -1,104 +1,99 @@
// Title: Barcode Confidence Distribution Report
-// Description: Generates sample barcodes, reads them, and reports the count of each confidence level across the scanned set.
+// Description: Generates sample barcodes, scans them, and reports the distribution of confidence levels across the scanned results.
+// Category-Description: This example demonstrates Aspose.BarCode's generation and recognition APIs, focusing on creating barcodes, reading them, and analyzing the BarCodeConfidence enumeration. It showcases typical use cases such as batch processing of barcode images, confidence assessment for quality control, and reporting. Developers working with barcode scanning pipelines often need to aggregate confidence metrics to evaluate scanner performance and data reliability.
// Prompt: Generate a report summarizing the distribution of Confidence enumerations across a large dataset of scanned barcodes.
-// Tags: barcode symbology, confidence analysis, report, aspose.barcode, c#
+// Tags: barcode symbology, generation, recognition, confidence, report, aspose.barcode, csharp
using System;
using System.Collections.Generic;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Demonstrates how to generate barcodes, recognize them, and summarize the distribution
-/// of values across the scanned images.
+/// Demonstrates how to generate a set of barcodes, read them back,
+/// and produce a summary of the confidence levels reported by the Aspose.BarCode recognizer.
///
class Program
{
///
- /// Entry point of the example. Generates sample barcodes, reads them,
- /// aggregates confidence levels, outputs a summary, and cleans up temporary files.
+ /// Entry point of the example. Generates sample barcodes, scans them,
+ /// and prints the distribution of values.
///
static void Main()
{
// --------------------------------------------------------------------
- // 1. Prepare a small set of sample barcodes with expected confidence levels.
+ // Prepare output folder for generated barcode images
// --------------------------------------------------------------------
- var samples = new (BaseEncodeType type, string text, string file)[]
+ string outputFolder = "Barcodes";
+ Directory.CreateDirectory(outputFolder);
+
+ // --------------------------------------------------------------------
+ // Define a small set of sample barcodes (type, text, file name)
+ // --------------------------------------------------------------------
+ var samples = new List<(BaseEncodeType Type, string Text, string FileName)>
{
- (EncodeTypes.Code128, "12345", "code128.png"), // expected Moderate confidence
- (EncodeTypes.QR, "12345", "qr.png"), // expected Strong confidence
- (EncodeTypes.EAN13, "5901234123457", "ean13.png") // expected Strong confidence (EAN13 has checksum)
+ (EncodeTypes.Code128, "Sample123", "code128.png"), // typically Moderate confidence
+ (EncodeTypes.QR, "SampleQR", "qr.png"), // typically Strong confidence
+ (EncodeTypes.DataMatrix, "DM12345", "datamatrix.png") // confidence may vary
};
// --------------------------------------------------------------------
- // 2. Generate barcode images from the sample data.
+ // Generate barcode images using default settings
// --------------------------------------------------------------------
- foreach (var (type, text, file) in samples)
+ foreach (var sample in samples)
{
- using (var generator = new BarcodeGenerator(type, text))
+ string filePath = Path.Combine(outputFolder, sample.FileName);
+ using (var generator = new BarcodeGenerator(sample.Type, sample.Text))
{
- // Save the generated barcode to a PNG file.
- generator.Save(file);
+ // Save the generated barcode as PNG
+ generator.Save(filePath, BarCodeImageFormat.Png);
}
}
// --------------------------------------------------------------------
- // 3. Initialize a dictionary to hold the count of each confidence level.
+ // Initialize a dictionary to count each confidence level
// --------------------------------------------------------------------
- var confidenceCounts = new Dictionary();
+ var confidenceCounts = new Dictionary
+ {
+ { BarCodeConfidence.None, 0 },
+ { BarCodeConfidence.Moderate, 0 },
+ { BarCodeConfidence.Strong, 0 }
+ };
// --------------------------------------------------------------------
- // 4. Recognize each generated image and collect confidence values.
+ // Read each generated image and collect confidence values
// --------------------------------------------------------------------
- foreach (var (_, _, file) in samples)
+ foreach (var sample in samples)
{
- if (!File.Exists(file))
+ string filePath = Path.Combine(outputFolder, sample.FileName);
+ if (!File.Exists(filePath))
{
- Console.WriteLine($"Warning: file '{file}' not found, skipping.");
+ Console.WriteLine($"Warning: File not found - {filePath}");
continue;
}
- using (var reader = new BarCodeReader(file, DecodeType.AllSupportedTypes))
+ using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
{
foreach (var result in reader.ReadBarCodes())
{
- var confidence = result.Confidence;
-
- // Increment the count for the observed confidence level.
- if (confidenceCounts.ContainsKey(confidence))
- confidenceCounts[confidence] += 1;
+ BarCodeConfidence conf = result.Confidence;
+ if (confidenceCounts.ContainsKey(conf))
+ confidenceCounts[conf]++;
else
- confidenceCounts[confidence] = 1;
+ confidenceCounts[conf] = 1;
}
}
}
// --------------------------------------------------------------------
- // 5. Output the confidence distribution summary to the console.
+ // Output summary of confidence distribution
// --------------------------------------------------------------------
Console.WriteLine("Barcode Confidence Distribution:");
- foreach (BarCodeConfidence level in Enum.GetValues(typeof(BarCodeConfidence)))
+ foreach (var kvp in confidenceCounts)
{
- confidenceCounts.TryGetValue(level, out int count);
- Console.WriteLine($"{level}: {count}");
- }
-
- // --------------------------------------------------------------------
- // 6. Clean up generated files (optional).
- // --------------------------------------------------------------------
- foreach (var (_, _, file) in samples)
- {
- try
- {
- if (File.Exists(file))
- File.Delete(file);
- }
- catch
- {
- // Ignore any cleanup errors.
- }
+ Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/implement-configuration-file-allowing-toggling-detectencoding-and-checksumvalidation-values-without-recompiling-applicat.cs b/barcode-recognition-basics/implement-configuration-file-allowing-toggling-detectencoding-and-checksumvalidation-values-without-recompiling-applicat.cs
index 9ca3bd9..0163004 100644
--- a/barcode-recognition-basics/implement-configuration-file-allowing-toggling-detectencoding-and-checksumvalidation-values-without-recompiling-applicat.cs
+++ b/barcode-recognition-basics/implement-configuration-file-allowing-toggling-detectencoding-and-checksumvalidation-values-without-recompiling-applicat.cs
@@ -1,102 +1,99 @@
-// Title: Barcode generation and recognition with configurable settings
-// Description: Demonstrates generating an EAN13 barcode, reading it, and using a JSON configuration file to toggle DetectEncoding and ChecksumValidation without recompiling.
+// Title: QR Code Generation and Recognition with Configurable Encoding Detection
+// Description: Demonstrates generating a QR code containing Unicode text and reading it while toggling DetectEncoding and ChecksumValidation via a JSON config file.
+// Category-Description: This example belongs to the Aspose.BarCode configuration management category, showcasing how to use BarcodeGenerator, BarCodeReader, and BarcodeSettings to control encoding detection and checksum validation. Developers often need to adjust these settings at runtime without recompiling, especially when processing diverse barcode sources in enterprise applications.
// Prompt: Implement a configuration file allowing toggling DetectEncoding and ChecksumValidation values without recompiling the application.
-// Tags: barcode, ean13, generation, recognition, configuration, json
+// Tags: qr, unicode, encoding, checksum, configuration, aspose.barcode, barcodegeneration, barcoderecognition
using System;
using System.IO;
+using System.Text;
using System.Text.Json;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
/// Represents the configurable settings for barcode reading.
///
-class Config
+public class Config
{
///
- /// Gets or sets a value indicating whether the reader should attempt to detect the encoding of the barcode.
+ /// Gets or sets a value indicating whether the reader should attempt to detect the text encoding.
///
public bool DetectEncoding { get; set; } = true;
///
- /// Gets or sets the checksum validation mode for the barcode reader.
+ /// Gets or sets the checksum validation mode for the reader.
///
public ChecksumValidation ChecksumValidation { get; set; } = ChecksumValidation.Default;
}
///
-/// Entry point of the application that generates a sample barcode, reads it, and applies configuration settings.
+/// Example program that generates a QR code with Unicode text and reads it using configurable settings.
///
class Program
{
///
- /// Main method that orchestrates barcode generation, configuration loading, and barcode reading.
+ /// Entry point of the application. Generates a QR code, loads configuration, and reads the barcode.
///
static void Main()
{
- // Path to the JSON configuration file.
- const string configPath = "barcodeConfig.json";
-
- // Load configuration from file or create a default one if the file does not exist.
+ // --------------------------------------------------------------------
+ // Load configuration from "config.json" if it exists; otherwise use defaults.
+ // --------------------------------------------------------------------
Config config;
+ const string configPath = "config.json";
+
if (File.Exists(configPath))
{
try
{
- // Read JSON content.
string json = File.ReadAllText(configPath);
- // Deserialize JSON into Config object (case-insensitive).
- config = JsonSerializer.Deserialize(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new Config();
+ config = JsonSerializer.Deserialize(json) ?? new Config();
}
- catch
+ catch (Exception ex)
{
- // If deserialization fails, fall back to default configuration.
+ Console.WriteLine($"Failed to read config file: {ex.Message}");
config = new Config();
}
}
else
{
- // Create a new default configuration and persist it to disk.
config = new Config();
- string defaultJson = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true });
- File.WriteAllText(configPath, defaultJson);
}
- // Path to the sample barcode image.
- const string imagePath = "sample.png";
+ // --------------------------------------------------------------------
+ // Define file path and sample Unicode text for the QR code.
+ // --------------------------------------------------------------------
+ const string barcodePath = "barcode.png";
+ const string unicodeText = "Привет"; // Sample Unicode text
- // Generate a sample EAN13 barcode image if it does not already exist.
- if (!File.Exists(imagePath))
+ // --------------------------------------------------------------------
+ // Generate a QR code image containing the Unicode text.
+ // --------------------------------------------------------------------
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR))
{
- using (var generator = new BarcodeGenerator(EncodeTypes.EAN13, "1234567890128"))
- {
- generator.Save(imagePath);
- }
+ generator.SetCodeText(unicodeText, Encoding.UTF8);
+ generator.Save(barcodePath, BarCodeImageFormat.Png);
}
- // Initialize the barcode reader with the desired decode type.
- using (var reader = new BarCodeReader(imagePath, DecodeType.EAN13))
+ // --------------------------------------------------------------------
+ // Read the generated QR code using settings from the configuration.
+ // --------------------------------------------------------------------
+ using (var reader = new BarCodeReader(barcodePath, DecodeType.QR))
{
// Apply configuration values to the reader's settings.
reader.BarcodeSettings.DetectEncoding = config.DetectEncoding;
reader.BarcodeSettings.ChecksumValidation = config.ChecksumValidation;
- // Iterate through all detected barcodes.
- foreach (BarCodeResult result in reader.ReadBarCodes())
+ // Iterate through all detected barcodes (single in this case).
+ foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"CodeText: {result.CodeText}");
-
- // For 1D barcodes, checksum information is available in the extended data.
- if (result.Extended?.OneD != null)
- {
- Console.WriteLine($"Checksum: {result.Extended.OneD.CheckSum}");
- }
+ Console.WriteLine($"Detected CodeText: {result.CodeText}");
+ Console.WriteLine($"DetectEncoding: {reader.BarcodeSettings.DetectEncoding}");
+ Console.WriteLine($"ChecksumValidation: {reader.BarcodeSettings.ChecksumValidation}");
}
}
-
- // Indicate that processing has completed.
- Console.WriteLine("Barcode processing completed.");
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/implement-error-handling-for-checksum-failures-when-checksumvalidationon-is-set-for-optional-checksum-symbologies.cs b/barcode-recognition-basics/implement-error-handling-for-checksum-failures-when-checksumvalidationon-is-set-for-optional-checksum-symbologies.cs
index f8b723d..73dc3b2 100644
--- a/barcode-recognition-basics/implement-error-handling-for-checksum-failures-when-checksumvalidationon-is-set-for-optional-checksum-symbologies.cs
+++ b/barcode-recognition-basics/implement-error-handling-for-checksum-failures-when-checksumvalidationon-is-set-for-optional-checksum-symbologies.cs
@@ -1,7 +1,8 @@
-// Title: Code39 Barcode Generation and Checksum Validation
-// Description: Generates a Code39 barcode and demonstrates error handling when checksum validation is enabled for optional checksum symbologies.
+// Title: Checksum Validation Failure Handling for Optional Checksum Symbologies
+// Description: Demonstrates how to detect and handle checksum validation failures when reading a Code39 barcode generated without a checksum.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on checksum validation for optional checksum symbologies such as Code39. It showcases the use of BarcodeGenerator, BarCodeReader, and related settings like IsChecksumEnabled and ChecksumValidation. Developers often need to ensure data integrity by enabling checksum validation during decoding and handling cases where the checksum is missing or incorrect.
// Prompt: Implement error handling for checksum failures when ChecksumValidation.On is set for optional checksum symbologies.
-// Tags: barcode symbology, generation, recognition, checksum validation, code39, aspnet
+// Tags: barcode symbology, checksum validation, code39, generation, recognition, aspnet, aspose.barcode
using System;
using System.IO;
@@ -10,75 +11,72 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates creating a Code39 barcode, saving it to a file, and reading it back with checksum validation enabled.
-/// Includes error handling for checksum failures on optional checksum symbologies.
+/// Example program that generates a Code39 barcode without a checksum,
+/// then attempts to read it with checksum validation enabled to demonstrate error handling.
///
class Program
{
///
- /// Entry point of the example. Generates a barcode image, verifies its creation, and attempts to read it with strict checksum validation.
+ /// Entry point of the example. Generates a barcode, validates its existence,
+ /// reads it with checksum validation turned on, and handles possible checksum failures.
///
static void Main()
{
- // Define file path for the generated barcode image
+ // Path where the generated barcode image will be saved
string barcodePath = "code39.png";
- // Generate a Code39 barcode (checksum is optional for this symbology)
- using (var generator = new BarcodeGenerator(EncodeTypes.Code39, "ABC"))
+ // ------------------------------------------------------------
+ // Generate a Code39 barcode without an optional checksum
+ // ------------------------------------------------------------
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code39, "ABC123"))
{
- // Optional: set visual parameters for the barcode
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
- generator.Parameters.Barcode.XDimension.Point = 2f;
+ // Disable checksum generation for this optional checksum symbology
+ generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.No;
- // Save the generated barcode image to the specified path
+ // Save the barcode image to the specified file
generator.Save(barcodePath);
}
+ // ------------------------------------------------------------
// Verify that the barcode image was successfully created
+ // ------------------------------------------------------------
if (!File.Exists(barcodePath))
{
Console.WriteLine($"Failed to create barcode image at '{barcodePath}'.");
return;
}
- // Attempt to read the barcode with checksum validation enabled
- try
+ // ------------------------------------------------------------
+ // Read the barcode with checksum validation enabled
+ // ------------------------------------------------------------
+ using (var reader = new BarCodeReader(barcodePath, DecodeType.Code39))
{
- using (var reader = new BarCodeReader(barcodePath, DecodeType.Code39))
- {
- // Enable strict checksum validation for optional checksum symbologies
- reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
+ // Turn on checksum validation for optional checksum symbologies
+ reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
- // Read all barcodes from the image
- var results = reader.ReadBarCodes();
+ // Attempt to decode the barcode(s) in the image
+ BarCodeResult[] results = reader.ReadBarCodes();
- // If no results are returned, treat it as a checksum failure or unreadable barcode
- if (results == null || results.Length == 0)
- {
- Console.WriteLine("No barcode detected. This may be due to checksum validation failure.");
- }
- else
+ // If no results are returned, checksum validation likely failed
+ if (results == null || results.Length == 0)
+ {
+ Console.WriteLine("Checksum validation failed: barcode could not be recognized.");
+ }
+ else
+ {
+ // Process each recognized barcode (unexpected when checksum is invalid)
+ foreach (var result in results)
{
- // Iterate through each detected barcode and display its details
- foreach (var result in results)
- {
- Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
- Console.WriteLine($"BarCode CodeText: {result.CodeText}");
+ Console.WriteLine($"BarCode Type: {result.CodeType}");
+ Console.WriteLine($"BarCode CodeText: {result.CodeText}");
- // For 1D barcodes, extended data may contain checksum information
- if (result.Extended?.OneD != null)
- {
- Console.WriteLine($"BarCode Value: {result.Extended.OneD.Value}");
- Console.WriteLine($"BarCode Checksum: {result.Extended.OneD.CheckSum}");
- }
+ // For 1D barcodes, the detected checksum (if any) is available here
+ if (result.Extended?.OneD != null)
+ {
+ Console.WriteLine($"Detected Checksum: {result.Extended.OneD.CheckSum}");
}
}
}
}
- catch (Exception ex)
- {
- // Handle any exceptions that occur during reading (e.g., checksum validation errors)
- Console.WriteLine($"Error during barcode recognition: {ex.Message}");
- }
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/implement-error-logging-for-cases-where-setbarcodeimage-receives-unsupported-image-format-argument.cs b/barcode-recognition-basics/implement-error-logging-for-cases-where-setbarcodeimage-receives-unsupported-image-format-argument.cs
index f923549..fe0ed8d 100644
--- a/barcode-recognition-basics/implement-error-logging-for-cases-where-setbarcodeimage-receives-unsupported-image-format-argument.cs
+++ b/barcode-recognition-basics/implement-error-logging-for-cases-where-setbarcodeimage-receives-unsupported-image-format-argument.cs
@@ -1,69 +1,83 @@
-// Title: Demonstrate error handling for unsupported image format in BarCodeReader
-// Description: Shows how to catch and log errors when SetBarCodeImage receives a file that is not a supported image format, using Aspose.BarCode.
+// Title: Demonstrate barcode generation, reading, and error logging for unsupported image formats
+// Description: The example generates a Code128 barcode, reads it from a PNG image, then attempts to load a non‑image file and logs the resulting error.
+// Category-Description: This sample belongs to the Aspose.BarCode image handling category, illustrating how to use BarcodeGenerator to create barcodes, BarCodeReader to decode them, and how to handle invalid image inputs with SetBarCodeImage. Developers working with barcode generation and recognition often need to validate image sources and log errors when unsupported formats are encountered. The example showcases key classes such as BarcodeGenerator, BarCodeReader, and Image handling from Aspose.Drawing.
// Prompt: Implement error logging for cases where SetBarCodeImage receives an unsupported image format argument.
-// Tags: barcode symbology, error handling, image format, aspose.barcode, barcodereader
+// Tags: barcode symbology, generation, recognition, error handling, image format, aspose.barcode
using System;
using System.IO;
-using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Example program that attempts to read a barcode from an unsupported image file
-/// and logs appropriate error messages.
+/// Example program that generates a barcode, reads it, and demonstrates error logging
+/// when attempting to set a barcode image from an unsupported file format.
///
class Program
{
///
- /// Entry point of the application. Creates a dummy non‑image file, tries to read a barcode,
- /// and demonstrates error handling for unsupported image formats.
+ /// Entry point of the application.
///
static void Main()
{
- // --------------------------------------------------------------------
- // Prepare a dummy file with an unsupported image format (e.g., a text file)
- // --------------------------------------------------------------------
- string unsupportedFilePath = "unsupported.txt";
- if (!File.Exists(unsupportedFilePath))
+ // ------------------------------------------------------------
+ // Generate a valid barcode image (PNG) using BarcodeGenerator
+ // ------------------------------------------------------------
+ const string validImagePath = "valid.png";
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
{
- File.WriteAllText(unsupportedFilePath, "This is not an image.");
+ generator.Save(validImagePath, BarCodeImageFormat.Png);
}
- // --------------------------------------------------------------------
- // Attempt to use BarCodeReader with the unsupported file.
- // BarCodeReader expects a supported image format (png, jpg, bmp, etc.).
- // The constructor will throw an exception for unsupported formats.
- // --------------------------------------------------------------------
+ // ------------------------------------------------------------
+ // Create a file with an unsupported image format (plain text)
+ // ------------------------------------------------------------
+ const string unsupportedPath = "unsupported.txt";
+ File.WriteAllText(unsupportedPath, "This is not an image.");
+
+ // ------------------------------------------------------------
+ // Read barcode from the valid image (normal operation)
+ // ------------------------------------------------------------
+ using (var reader = new BarCodeReader(validImagePath, DecodeType.Code128))
+ {
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Read from valid image: {result.CodeText}");
+ }
+ }
+
+ // ------------------------------------------------------------
+ // Attempt to set a barcode image using an unsupported format
+ // ------------------------------------------------------------
try
{
- using (var reader = new BarCodeReader(unsupportedFilePath, DecodeType.Code128))
+ // Load the file as an Image; this will succeed for any file but will fail later when casting
+ using (Image image = Image.FromFile(unsupportedPath))
{
- // If no exception, attempt to read (unlikely for unsupported format)
- foreach (BarCodeResult result in reader.ReadBarCodes())
+ // BarCodeReader supports setting the image via SetBarCodeImage
+ using (var reader = new BarCodeReader())
{
- Console.WriteLine($"Found barcode: Type={result.CodeTypeName}, Text={result.CodeText}");
+ // Cast to Bitmap as required by SetBarCodeImage; this throws for non‑image files
+ reader.SetBarCodeImage((Bitmap)image);
+
+ // Attempt to read (won't be reached for unsupported format)
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Unexpected read: {result.CodeText}");
+ }
}
}
}
- catch (BarCodeException ex)
- {
- // Log the specific Aspose.BarCode exception indicating unsupported format
- Console.WriteLine($"Error: Unsupported image format for SetBarCodeImage. Details: {ex.Message}");
- }
catch (Exception ex)
{
- // Log any other unexpected exceptions
- Console.WriteLine($"Unexpected error: {ex.GetType().Name} - {ex.Message}");
- }
- finally
- {
- // --------------------------------------------------------------------
- // Clean up the dummy file
- // --------------------------------------------------------------------
- if (File.Exists(unsupportedFilePath))
- {
- File.Delete(unsupportedFilePath);
- }
+ // Log the error to console
+ Console.WriteLine($"Error loading unsupported image format: {ex.Message}");
+
+ // Append detailed error information to a simple log file
+ File.AppendAllText(
+ "error.log",
+ $"[{DateTime.Now}] Unsupported image load error: {ex}{Environment.NewLine}");
}
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/implement-fallback-decoding-routine-that-triggers-when-detectencoding-is-false-and-raw-data-cannot-be-interpreted-as-utf.cs b/barcode-recognition-basics/implement-fallback-decoding-routine-that-triggers-when-detectencoding-is-false-and-raw-data-cannot-be-interpreted-as-utf.cs
index 7366a1b..315ff8d 100644
--- a/barcode-recognition-basics/implement-fallback-decoding-routine-that-triggers-when-detectencoding-is-false-and-raw-data-cannot-be-interpreted-as-utf.cs
+++ b/barcode-recognition-basics/implement-fallback-decoding-routine-that-triggers-when-detectencoding-is-false-and-raw-data-cannot-be-interpreted-as-utf.cs
@@ -1,7 +1,8 @@
-// Title: QR Code Generation and Decoding with UTF-8 Fallback
-// Description: Demonstrates generating a QR code containing Unicode text, reading it with encoding detection disabled, and applying a fallback decoding when UTF‑8 fails.
+// Title: QR Code Generation and Fallback Decoding with Aspose.BarCode
+// Description: Demonstrates creating a QR code containing Cyrillic text, saving it to a memory stream, and decoding it with custom encoding handling, including a fallback when UTF‑8 decoding fails.
+// 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 extracting raw byte data. Developers often need to control text encoding, disable automatic detection, and implement fallback strategies for non‑UTF‑8 payloads, especially when handling international characters.
// Prompt: Implement a fallback decoding routine that triggers when DetectEncoding is false and raw data cannot be interpreted as UTF8.
-// Tags: qr, barcode, encoding, fallback, aspose.barcode, utf8, windows-1252
+// Tags: qr, unicode, encoding, fallback, decoding, aspose.barcode, generation, recognition
using System;
using System.IO;
@@ -11,68 +12,62 @@
using Aspose.Drawing;
///
-/// Example program that creates a QR code with Unicode text, reads it without automatic encoding detection,
-/// and demonstrates a manual fallback decoding strategy when UTF‑8 decoding is not successful.
+/// Generates a QR code with Cyrillic text, saves it to a memory stream,
+/// and reads it back using a custom decoding routine that includes a fallback
+/// when UTF‑8 decoding is not possible.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Performs barcode generation, saves to a stream,
+ /// and reads the barcode with explicit encoding handling.
///
static void Main()
{
- // ------------------------------------------------------------
- // 1. Generate a QR code containing Cyrillic text using UTF‑8 encoding.
- // ------------------------------------------------------------
+ // Create a memory stream to hold the generated QR code image.
using (var ms = new MemoryStream())
{
- // Create a barcode generator for QR codes with the desired text.
+ // Generate a QR code containing the Cyrillic word "Привет".
using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Привет"))
{
- // Explicitly set the code text with UTF‑8 encoding to ensure correct byte representation.
+ // Explicitly set the code text encoding to UTF‑8.
generator.SetCodeText("Привет", Encoding.UTF8);
-
- // Save the generated barcode image into the memory stream in PNG format.
+ // Save the QR code as a PNG image into the memory stream.
generator.Save(ms, BarCodeImageFormat.Png);
}
- // ------------------------------------------------------------
- // 2. Prepare the stream for reading the barcode image.
- // ------------------------------------------------------------
- ms.Position = 0; // Reset stream position to the beginning.
+ // Reset the stream position to the beginning for reading.
+ ms.Position = 0;
- // ------------------------------------------------------------
- // 3. Read the barcode with automatic encoding detection turned off.
- // ------------------------------------------------------------
+ // Initialize a barcode reader for QR codes, disabling automatic encoding detection.
using (var reader = new BarCodeReader(ms, DecodeType.QR))
{
- // Disable automatic detection so we can control the decoding process.
reader.BarcodeSettings.DetectEncoding = false;
- // Iterate over all detected barcodes (in this case, just one).
- foreach (BarCodeResult result in reader.ReadBarCodes())
+ // Iterate over all detected barcodes (there should be only one in this example).
+ foreach (var result in reader.ReadBarCodes())
{
- // Attempt to decode the raw data using UTF‑8.
- string textUtf8 = result.GetCodeText(Encoding.UTF8);
-
- // Determine whether a fallback is needed:
- // - Empty or null result indicates decoding failure.
- // - Presence of the Unicode replacement character (�) signals invalid UTF‑8 sequences.
- bool needFallback = string.IsNullOrEmpty(textUtf8) || textUtf8.Contains('\uFFFD');
+ Console.WriteLine("=== Detected Barcode ===");
+ Console.WriteLine("Symbology: " + result.CodeTypeName);
- if (needFallback)
+ // Attempt to decode the raw bytes using strict UTF‑8 decoding.
+ string decodedText;
+ var strictUtf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
+ try
{
- // ------------------------------------------------------------
- // 4. Fallback decoding: try Windows‑1252 (or any other desired encoding).
- // ------------------------------------------------------------
- string fallbackText = result.GetCodeText(Encoding.GetEncoding(1252));
- Console.WriteLine($"Fallback decoded text: {fallbackText}");
+ decodedText = strictUtf8.GetString(result.CodeBytes);
+ Console.WriteLine("Decoded (UTF-8): " + decodedText);
}
- else
+ catch (DecoderFallbackException)
{
- // UTF‑8 decoding succeeded; output the result.
- Console.WriteLine($"UTF8 decoded text: {textUtf8}");
+ // Fallback: decode using Windows‑1252 (or any other appropriate fallback encoding).
+ var fallbackEncoding = Encoding.GetEncoding(1252);
+ decodedText = fallbackEncoding.GetString(result.CodeBytes);
+ Console.WriteLine("Decoded (fallback encoding 1252): " + decodedText);
}
+
+ // Output the raw byte sequence for diagnostic purposes.
+ Console.WriteLine("Raw bytes: " + BitConverter.ToString(result.CodeBytes));
}
}
}
diff --git a/barcode-recognition-basics/implement-parallel-barcode-recognition-using-task-parallel-library-to-handle-multiple-images-concurrently.cs b/barcode-recognition-basics/implement-parallel-barcode-recognition-using-task-parallel-library-to-handle-multiple-images-concurrently.cs
index a5a2887..084c364 100644
--- a/barcode-recognition-basics/implement-parallel-barcode-recognition-using-task-parallel-library-to-handle-multiple-images-concurrently.cs
+++ b/barcode-recognition-basics/implement-parallel-barcode-recognition-using-task-parallel-library-to-handle-multiple-images-concurrently.cs
@@ -1,7 +1,8 @@
-// Title: Parallel Barcode Recognition with TPL
-// Description: Generates sample Code128 barcodes, then uses Task Parallel Library to recognize them concurrently, demonstrating multi‑core processing.
+// Title: Parallel barcode recognition using TPL
+// Description: Demonstrates generating sample barcodes and recognizing them concurrently across multiple images.
+// Category-Description: This example belongs to the Aspose.BarCode barcode processing category, showcasing how to use BarCodeGenerator for creating barcodes and BarCodeReader with ProcessorSettings for high‑performance parallel recognition. Typical use cases include batch processing of scanned documents, inventory systems, and automated data entry where many images must be decoded quickly. Developers often need to leverage the Task Parallel Library together with Aspose.BarCode APIs to maximize CPU utilization.
// Prompt: Implement parallel barcode recognition using Task Parallel Library to handle multiple images concurrently.
-// Tags: code128, generation, recognition, parallel, tpl, console
+// Tags: barcode, parallel, tpl, recognition, generation, aspnet, aspose.barcode, multithreading
using System;
using System.IO;
@@ -12,77 +13,98 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates generating barcode images and recognizing them in parallel using the Task Parallel Library.
+/// Sample program that generates several barcode images and then reads them in parallel
+/// using the Task Parallel Library (TPL). Demonstrates high‑performance batch barcode
+/// recognition with Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application. Generates sample barcodes, processes them concurrently, and cleans up temporary files.
+ /// Entry point of the application. Generates sample barcodes, configures parallel
+ /// processing, and reads all generated images concurrently.
///
- static void Main()
+ /// Command‑line arguments (not used).
+ static void Main(string[] args)
{
// --------------------------------------------------------------------
- // 1. Generate a small set of sample barcode images (5 items)
+ // 1. Prepare a folder for sample barcode images
// --------------------------------------------------------------------
- var imagePaths = new List();
- for (int i = 0; i < 5; i++)
+ string folder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(folder))
{
- // Create unique barcode text for each image
- string codeText = $"CODE{i + 1}";
- // Determine a temporary file path for the image
- string filePath = Path.Combine(Path.GetTempPath(), $"barcode_{i}.png");
+ Directory.CreateDirectory(folder);
+ }
- // Generate and save the barcode image using Code128 symbology
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ // --------------------------------------------------------------------
+ // 2. Define sample barcodes to generate (type, text, file name)
+ // --------------------------------------------------------------------
+ var samples = new (BaseEncodeType type, string text, string fileName)[]
+ {
+ (EncodeTypes.Code128, "ABC123", "code128.png"),
+ (EncodeTypes.QR, "Hello QR", "qr.png"),
+ (EncodeTypes.DataMatrix, "DM123", "datamatrix.png"),
+ (EncodeTypes.Pdf417, "PDF417 Sample", "pdf417.png"),
+ (EncodeTypes.Aztec, "Aztec", "aztec.png")
+ };
+
+ // --------------------------------------------------------------------
+ // 3. Generate barcode images and save them to the folder
+ // --------------------------------------------------------------------
+ foreach (var sample in samples)
+ {
+ string filePath = Path.Combine(folder, sample.fileName);
+ using (var generator = new BarcodeGenerator(sample.type, sample.text))
{
- generator.Save(filePath, BarCodeImageFormat.Png);
+ // Optional: set a modest XDimension for better visibility
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+ generator.Save(filePath);
}
-
- // Store the path for later processing
- imagePaths.Add(filePath);
}
// --------------------------------------------------------------------
- // 2. Configure the barcode reader to utilize all available CPU cores
+ // 4. Configure processor settings to use all available CPU cores
// --------------------------------------------------------------------
BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Environment.ProcessorCount;
// --------------------------------------------------------------------
- // 3. Perform parallel recognition of the generated images
+ // 5. Collect image file paths for later processing
// --------------------------------------------------------------------
- Parallel.ForEach(imagePaths, path =>
+ var imageFiles = new List();
+ foreach (var sample in samples)
{
- // Open a reader for the current image file
- using (var reader = new BarCodeReader(path, DecodeType.AllSupportedTypes))
+ string filePath = Path.Combine(folder, sample.fileName);
+ if (File.Exists(filePath))
{
- // Iterate over all detected barcodes in the image
- foreach (var result in reader.ReadBarCodes())
- {
- // Synchronize console output to avoid interleaved lines from multiple threads
- lock (Console.Out)
- {
- Console.WriteLine($"File: {Path.GetFileName(path)} | Type: {result.CodeTypeName} | Text: {result.CodeText}");
- }
- }
+ imageFiles.Add(filePath);
}
- });
+ }
// --------------------------------------------------------------------
- // 4. Clean up temporary files
+ // 6. Process images in parallel using TPL
// --------------------------------------------------------------------
- foreach (var path in imagePaths)
+ var tasks = new List();
+ foreach (string imagePath in imageFiles)
{
- try
+ tasks.Add(Task.Run(() =>
{
- if (File.Exists(path))
+ using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
- File.Delete(path);
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"{Path.GetFileName(imagePath)} | Type: {result.CodeTypeName} | Text: {result.CodeText}");
+ }
}
- }
- catch
- {
- // Ignore any cleanup errors (e.g., file in use)
- }
+ }));
}
+
+ // --------------------------------------------------------------------
+ // 7. Wait for all recognition tasks to complete
+ // --------------------------------------------------------------------
+ Task.WaitAll(tasks.ToArray());
+
+ // --------------------------------------------------------------------
+ // 8. Cleanup (optional): delete the generated images
+ // --------------------------------------------------------------------
+ // foreach (var file in imageFiles) { File.Delete(file); }
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/implement-retry-mechanism-that-re-reads-barcode-image-when-readingquality-is-reported-as-none.cs b/barcode-recognition-basics/implement-retry-mechanism-that-re-reads-barcode-image-when-readingquality-is-reported-as-none.cs
index 64f776c..b2fe881 100644
--- a/barcode-recognition-basics/implement-retry-mechanism-that-re-reads-barcode-image-when-readingquality-is-reported-as-none.cs
+++ b/barcode-recognition-basics/implement-retry-mechanism-that-re-reads-barcode-image-when-readingquality-is-reported-as-none.cs
@@ -1,100 +1,90 @@
-// Title: Barcode Reading with Retry on Low Quality
+// Title: Retry barcode read on low quality
// Description: Demonstrates generating a barcode image and reading it with a retry mechanism that re‑reads when the reading quality is reported as None.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It shows how to use BarcodeGenerator to create a barcode, BarCodeReader with DecodeType.AllSupportedTypes to detect barcodes, and QualitySettings to improve detection on retries. Developers often need to handle low‑confidence reads by adjusting quality settings and retrying until acceptable confidence is achieved.
// Prompt: Implement a retry mechanism that re‑reads a barcode image when ReadingQuality is reported as None.
-// Tags: barcode, code128, retry, readingquality, aspose.barcode, png
+// Tags: barcode symbology, generation, recognition, retry, qualitysettings, code128, png, barcodereader, barcodegenerator
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 as a PNG,
-/// and attempts to read it with a retry mechanism when the reading quality is insufficient.
+/// Example program that generates a Code128 barcode image (if missing) and attempts to read it,
+/// retrying with higher quality settings when the reading quality is reported as None.
///
class Program
{
///
- /// Entry point of the application. Generates a barcode if needed and reads it,
- /// retrying up to a maximum number of attempts if the reading quality is reported as None.
+ /// Entry point of the example. Implements the retry logic for barcode reading.
///
static void Main()
{
- // Define barcode content and output image file name
- const string codeText = "1234567890";
const string imagePath = "sample_barcode.png";
+ const string codeText = "1234567890";
+ const int maxRetries = 3;
- // ------------------------------------------------------------
- // Generate a barcode image if it does not already exist
- // ------------------------------------------------------------
+ // Ensure the barcode image exists; generate it if missing.
if (!File.Exists(imagePath))
{
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
{
+ // Simple generation settings: set X-dimension and save as PNG.
+ generator.Parameters.Barcode.XDimension.Point = 2f;
generator.Save(imagePath, BarCodeImageFormat.Png);
+ Console.WriteLine($"Generated barcode image: {imagePath}");
}
}
- // ------------------------------------------------------------
- // Verify the image file exists before attempting to read it
- // ------------------------------------------------------------
- if (!File.Exists(imagePath))
- {
- Console.WriteLine($"Error: Barcode image file '{imagePath}' not found.");
- return;
- }
-
- // ------------------------------------------------------------
- // Set up retry parameters
- // ------------------------------------------------------------
- const int maxAttempts = 3;
int attempt = 0;
bool success = false;
- // ------------------------------------------------------------
- // Attempt to read the barcode, retrying when quality is None
- // ------------------------------------------------------------
- while (attempt < maxAttempts && !success)
+ // Retry loop: attempt to read the barcode up to maxRetries times.
+ while (attempt < maxRetries && !success)
{
attempt++;
+ Console.WriteLine($"Attempt {attempt} to read barcode...");
using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
- // Use higher quality settings on subsequent attempts for better detection
+ // On retries, switch to a higher quality preset to improve detection.
if (attempt > 1)
{
reader.QualitySettings = QualitySettings.HighQuality;
}
- // Iterate over all detected barcodes in the image
- foreach (var result in reader.ReadBarCodes())
+ // Perform the read operation.
+ var results = reader.ReadBarCodes();
+
+ if (results.Length == 0)
+ {
+ Console.WriteLine("No barcodes detected.");
+ continue; // Proceed to next retry attempt.
+ }
+
+ // Process each detected barcode.
+ foreach (var result in results)
{
- // ReadingQuality == 0 indicates 'None' (no confidence)
+ // ReadingQuality is a double; 0 indicates BarCodeConfidence.None.
if (result.ReadingQuality == 0.0)
{
- Console.WriteLine($"Attempt {attempt}: ReadingQuality is None. Retrying...");
- // Continue to next attempt
- continue;
+ Console.WriteLine("ReadingQuality is None (0). Will retry if attempts remain.");
+ // Do not set success; loop will retry if attempts remain.
+ }
+ else
+ {
+ // Successful read with acceptable quality; output details.
+ Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
+ Console.WriteLine($"BarCode CodeText: {result.CodeText}");
+ Console.WriteLine($"ReadingQuality: {result.ReadingQuality}");
+ success = true;
}
-
- // Successful read with sufficient quality
- Console.WriteLine($"Attempt {attempt}: Barcode detected.");
- Console.WriteLine($" Type: {result.CodeTypeName}");
- Console.WriteLine($" CodeText: {result.CodeText}");
- Console.WriteLine($" ReadingQuality: {result.ReadingQuality}");
- success = true;
- break;
}
-
- // If not successful and more attempts remain, loop will continue
}
}
- // ------------------------------------------------------------
- // Report final outcome
- // ------------------------------------------------------------
+ // Final status message after all attempts.
if (!success)
{
Console.WriteLine("Failed to read barcode with sufficient quality after retries.");
diff --git a/barcode-recognition-basics/integrate-barcode-detection-into-web-api-endpoint-that-accepts-uploaded-image-streams-for-instant-processing.cs b/barcode-recognition-basics/integrate-barcode-detection-into-web-api-endpoint-that-accepts-uploaded-image-streams-for-instant-processing.cs
index fce121d..9550b93 100644
--- a/barcode-recognition-basics/integrate-barcode-detection-into-web-api-endpoint-that-accepts-uploaded-image-streams-for-instant-processing.cs
+++ b/barcode-recognition-basics/integrate-barcode-detection-into-web-api-endpoint-that-accepts-uploaded-image-streams-for-instant-processing.cs
@@ -1,67 +1,74 @@
-// Title: Barcode detection demo for image stream processing
-// Description: Shows how to generate a sample barcode image and detect barcodes from a stream, mimicking a web API endpoint.
+// Title: Barcode detection from in-memory image stream
+// Description: Demonstrates generating a Code128 barcode, saving it to a memory stream, and detecting it using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing how to use BarcodeGenerator, BarCodeReader, and related classes to create and read barcodes in memory. Typical use cases include processing uploaded images in web APIs, validating scanned codes, and batch processing. Developers often need to configure quality settings and handle multiple symbologies efficiently.
// Prompt: Integrate barcode detection into a web API endpoint that accepts uploaded image streams for instant processing.
-// Tags: barcode symbology, detection, png, aspose.barcode, console demo
+// Tags: barcode detection, code128, in-memory, aspnet, aspose.barcode, generation, recognition, png
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Demonstrates barcode generation and detection using Aspose.BarCode.
-/// Intended as core logic for a web API endpoint that processes uploaded image streams.
+/// Example program that generates a barcode, stores it in a memory stream,
+/// and then reads/detects the barcode using Aspose.BarCode APIs.
///
class Program
{
///
- /// Entry point. Generates a sample barcode if missing, then reads barcodes from the image stream.
+ /// Entry point of the example. Generates a sample barcode, writes it to a
+ /// memory stream, and uses to detect and display
+ /// information about the barcode(s) found.
///
static void Main()
{
- // NOTE: The original task describes a web API endpoint.
- // The snippet runner does not support hosting an HTTP server,
- // so this console program demonstrates the core barcode detection logic
- // that would be used inside such an endpoint.
-
- const string sampleImagePath = "sample.png";
-
- // Ensure a sample barcode image exists.
- if (!File.Exists(sampleImagePath))
+ // Create a BarcodeGenerator for Code128 with sample text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- // Create a simple Code128 barcode and save it as a PNG file.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ // Prepare a memory stream to hold the generated PNG image.
+ using (var imageStream = new MemoryStream())
{
- // Optional: configure image size.
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 150f;
- generator.Save(sampleImagePath);
- }
- }
+ // Save the barcode image into the stream.
+ generator.Save(imageStream, BarCodeImageFormat.Png);
- // Open the image file as a stream for recognition.
- using (var imageStream = new FileStream(sampleImagePath, FileMode.Open, FileAccess.Read))
- {
- // Initialize the reader and configure it to scan all supported symbologies.
- using (var reader = new BarCodeReader())
- {
- reader.BarCodeReadType = DecodeType.AllSupportedTypes;
- reader.SetBarCodeImage(imageStream);
+ // Reset the stream position so it can be read from the beginning.
+ imageStream.Position = 0;
- // Perform barcode detection.
- foreach (var result in reader.ReadBarCodes())
+ // Initialize a BarCodeReader to detect any supported barcode types.
+ using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes))
{
- // Output detected barcode type.
- Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}");
- // Output decoded text.
- Console.WriteLine($"Decoded Text: {result.CodeText}");
+ // Set high-quality detection settings (optional but improves accuracy).
+ reader.QualitySettings = QualitySettings.HighQuality;
+
+ // Perform the detection and retrieve all results.
+ var results = reader.ReadBarCodes();
+
+ // Limit processing to a maximum of 5 detected barcodes.
+ int maxToProcess = 5;
+ int count = 0;
+
+ foreach (var result in results)
+ {
+ if (count >= maxToProcess)
+ break;
+
+ // Output details of each detected barcode.
+ Console.WriteLine($"Detected Barcode {count + 1}:");
+ Console.WriteLine($" Type: {result.CodeTypeName}");
+ Console.WriteLine($" CodeText: {result.CodeText}");
+ Console.WriteLine($" Confidence: {result.Confidence}");
+ Console.WriteLine($" ReadingQuality: {result.ReadingQuality}");
+ Console.WriteLine();
+
+ count++;
+ }
- // Output the location of the barcode within the image.
- var rect = result.Region.Rectangle;
- Console.WriteLine($"Region - X:{rect.X}, Y:{rect.Y}, Width:{rect.Width}, Height:{rect.Height}");
- Console.WriteLine();
+ // Inform the user if no barcodes were found.
+ if (count == 0)
+ {
+ Console.WriteLine("No barcodes were detected in the provided image.");
+ }
}
}
}
diff --git a/barcode-recognition-basics/integrate-barcode-quality-assessment-into-warehouse-management-system-by-storing-readingquality-alongside-inventory-reco.cs b/barcode-recognition-basics/integrate-barcode-quality-assessment-into-warehouse-management-system-by-storing-readingquality-alongside-inventory-reco.cs
index 6110651..7ad186e 100644
--- a/barcode-recognition-basics/integrate-barcode-quality-assessment-into-warehouse-management-system-by-storing-readingquality-alongside-inventory-reco.cs
+++ b/barcode-recognition-basics/integrate-barcode-quality-assessment-into-warehouse-management-system-by-storing-readingquality-alongside-inventory-reco.cs
@@ -1,7 +1,8 @@
-// Title: Barcode quality assessment integration for inventory records
-// Description: Demonstrates generating barcodes, reading them, capturing reading quality, and storing it with inventory data.
+// Title: Barcode Quality Assessment for Warehouse Inventory
+// Description: Demonstrates generating Code128 barcodes, reading them, capturing reading quality, and storing results with inventory data.
+// Category-Description: This example belongs to Aspose.BarCode generation and recognition operations. It shows how to use BarcodeGenerator to create barcodes, BarCodeReader to decode them, and retrieve the ReadingQuality metric. Typical use cases include inventory management, quality control, and integration of barcode data into business systems. Developers often need to generate barcodes, assess scan reliability, and persist the information alongside product records.
// Prompt: Integrate barcode quality assessment into a warehouse management system by storing ReadingQuality alongside inventory records.
-// Tags: barcode, quality-assessment, inventory, json, aspose.barcode, code128
+// Tags: code128, barcode generation, barcode recognition, readingquality, png, json, inventory, aspose.barcode, aspose.barcode.generation, aspose.barcode.recognition
using System;
using System.Collections.Generic;
@@ -10,83 +11,80 @@
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
-///
-/// Represents an inventory item with barcode and reading quality information.
-///
-class InventoryItem
+namespace WarehouseBarcodeDemo
{
- public int Id { get; set; }
- public string Name { get; set; }
- public string BarcodeValue { get; set; }
- public double ReadingQuality { get; set; }
-}
-
-///
-/// Entry point of the sample program that generates barcodes, evaluates their reading quality, and saves inventory data to JSON.
-///
-class Program
-{
- static void Main()
+ ///
+ /// Simple inventory record that includes barcode reading quality.
+ ///
+ public class InventoryRecord
{
- // Sample inventory records to be processed
- var items = new List
- {
- new InventoryItem { Id = 1, Name = "Widget A", BarcodeValue = "WGT001" },
- new InventoryItem { Id = 2, Name = "Widget B", BarcodeValue = "WGT002" },
- new InventoryItem { Id = 3, Name = "Widget C", BarcodeValue = "WGT003" }
- };
-
- // Directory for temporary barcode images
- string tempDir = Path.Combine(Path.GetTempPath(), "BarcodeSamples");
- if (!Directory.Exists(tempDir))
- {
- // Ensure the temporary directory exists
- Directory.CreateDirectory(tempDir);
- }
+ public int Id { get; set; }
+ public string Name { get; set; }
+ public string CodeText { get; set; }
+ public double ReadingQuality { get; set; }
+ }
- // Process each inventory item
- foreach (var item in items)
+ ///
+ /// Demonstrates barcode generation, recognition, and quality capture for inventory items.
+ ///
+ class Program
+ {
+ ///
+ /// Entry point. Generates barcodes for sample inventory, reads them to obtain quality metrics,
+ /// and serializes the enriched records to a JSON file.
+ ///
+ static void Main()
{
- // Path for the generated barcode image
- string imagePath = Path.Combine(tempDir, $"barcode_{item.Id}.png");
+ // Define sample inventory items.
+ var inventory = new List
+ {
+ new InventoryRecord { Id = 1, Name = "Widget A", CodeText = "WIDGETA123" },
+ new InventoryRecord { Id = 2, Name = "Gadget B", CodeText = "GADGETB456" }
+ };
- // Generate barcode image for the current item
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, item.BarcodeValue))
+ // Ensure the output directory for barcode images exists.
+ string barcodeDir = "Barcodes";
+ if (!Directory.Exists(barcodeDir))
{
- // Optional visual settings for better contrast
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- generator.Save(imagePath);
+ Directory.CreateDirectory(barcodeDir);
}
- // Read the generated barcode and capture its reading quality
- using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ // Process each inventory item: generate barcode, read it, and store quality.
+ foreach (var item in inventory)
{
- foreach (var result in reader.ReadBarCodes())
+ // Build the file path for the barcode image.
+ string imagePath = Path.Combine(barcodeDir, $"barcode_{item.Id}.png");
+
+ // Generate a Code128 barcode image from the item's CodeText.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, item.CodeText))
{
- // Assuming the first detected barcode corresponds to our generated one
- item.ReadingQuality = result.ReadingQuality;
- break;
+ generator.Save(imagePath, BarCodeImageFormat.Png);
}
- }
- // Clean up the temporary image file
- if (File.Exists(imagePath))
- {
- File.Delete(imagePath);
+ // Read the generated barcode and capture its reading quality.
+ using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ {
+ // Iterate over detected barcodes (expecting one per image).
+ foreach (var result in reader.ReadBarCodes())
+ {
+ // ReadingQuality is a double representing the quality percentage.
+ item.ReadingQuality = result.ReadingQuality;
+ // Process only the first detected barcode for this image.
+ break;
+ }
+ }
}
- }
- // Serialize the inventory list, including reading quality, to a JSON file
- string jsonPath = Path.Combine(Environment.CurrentDirectory, "inventory.json");
- var jsonOptions = new JsonSerializerOptions { WriteIndented = true };
- string json = JsonSerializer.Serialize(items, jsonOptions);
- File.WriteAllText(jsonPath, json);
+ // Serialize the enriched inventory records to a formatted JSON file.
+ string jsonPath = "inventory.json";
+ string json = JsonSerializer.Serialize(inventory, new JsonSerializerOptions { WriteIndented = true });
+ File.WriteAllText(jsonPath, json);
- // Inform the user where the output has been saved
- Console.WriteLine("Inventory records with barcode reading quality have been saved to:");
- Console.WriteLine(jsonPath);
+ // Output summary information to the console.
+ Console.WriteLine($"Processed {inventory.Count} inventory items.");
+ Console.WriteLine($"Barcode images saved in '{barcodeDir}'.");
+ Console.WriteLine($"Inventory data with reading quality saved to '{jsonPath}'.");
+ }
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/integrate-barcodereader-into-aspnet-core-api-endpoint-that-returns-confidence-and-quality-metrics-in-json.cs b/barcode-recognition-basics/integrate-barcodereader-into-aspnet-core-api-endpoint-that-returns-confidence-and-quality-metrics-in-json.cs
index fcd4bbd..635e64a 100644
--- a/barcode-recognition-basics/integrate-barcodereader-into-aspnet-core-api-endpoint-that-returns-confidence-and-quality-metrics-in-json.cs
+++ b/barcode-recognition-basics/integrate-barcodereader-into-aspnet-core-api-endpoint-that-returns-confidence-and-quality-metrics-in-json.cs
@@ -1,82 +1,67 @@
-// Title: Barcode Reader Demo with Confidence and Quality Metrics
-// Description: Demonstrates generating a QR code, reading it with Aspose.BarCode, and returning confidence and quality metrics as JSON.
+// Title: ASP.NET Core API style barcode reading with confidence and quality metrics
+// Description: Demonstrates generating a barcode, reading it with BarCodeReader, and outputting confidence and quality data as JSON.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing how to use BarcodeGenerator, BarCodeReader, and related classes to extract detailed metrics such as confidence and reading quality. Typical use cases include building web APIs that return barcode analysis results in JSON for client applications. Developers often need to integrate these APIs into ASP.NET Core services for real-time scanning and validation.
// Prompt: Integrate BarCodeReader into an ASP.NET Core API endpoint that returns confidence and quality metrics in JSON.
-// Tags: barcode symbology, reading, json output, aspnet core, confidence, quality, aspose.barcode
+// Tags: barcode, code128, confidence, readingquality, json, aspnetcore, apireader, aspose.barcode
using System;
-using System.Collections.Generic;
using System.IO;
+using System.Collections.Generic;
using System.Text.Json;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.BarCode; // Required for BarCodeConfidence enum
///
-/// Demonstrates barcode generation, reading, and JSON output of confidence and quality metrics.
+/// Demonstrates barcode generation, reading, and JSON serialization of confidence and quality metrics.
///
class Program
{
///
- /// Entry point that generates a QR code, reads it, and prints metrics as JSON.
+ /// Entry point that creates a barcode, reads it, and prints the results as formatted JSON.
///
static void Main()
{
- // NOTE: The original request was for an ASP.NET Core API endpoint.
- // The snippet runner environment only supports a console application,
- // so we demonstrate the core barcode reading logic here and output JSON to the console.
-
- // Path for the temporary barcode image.
- string imagePath = "sample.png";
-
- // Generate a sample QR barcode image with the text "12345".
- using (var generator = new BarcodeGenerator(EncodeTypes.QR, "12345"))
+ // Generate a Code128 barcode image in memory.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- generator.Save(imagePath);
- }
-
- // Verify that the image file was created successfully.
- if (!File.Exists(imagePath))
- {
- Console.WriteLine($"Error: Barcode image file '{imagePath}' was not found.");
- return;
- }
+ using (var imageStream = new MemoryStream())
+ {
+ // Save the generated barcode to the memory stream as PNG.
+ generator.Save(imageStream, BarCodeImageFormat.Png);
+ imageStream.Position = 0; // Reset stream position for reading.
- // Prepare a list to hold barcode information including confidence and quality.
- var resultsInfo = new List();
+ // Initialize the reader to decode all supported barcode types.
+ using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes))
+ {
+ var results = new List();
- // Initialize the barcode reader for all supported types.
- using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
- {
- // Apply normal quality settings for reading.
- reader.QualitySettings = QualitySettings.NormalQuality;
+ // Iterate through all detected barcodes.
+ foreach (var result in reader.ReadBarCodes())
+ {
+ // Capture relevant information for each barcode.
+ var info = new BarcodeInfo
+ {
+ CodeText = result.CodeText,
+ Confidence = result.Confidence.ToString(),
+ ReadingQuality = result.ReadingQuality
+ };
+ results.Add(info);
+ }
- // Iterate over all detected barcodes in the image.
- foreach (var result in reader.ReadBarCodes())
- {
- // Map the raw result to a simple DTO for JSON serialization.
- var info = new BarcodeInfo
- {
- CodeTypeName = result.CodeTypeName,
- CodeText = result.CodeText,
- Confidence = result.Confidence.ToString(),
- ReadingQuality = result.ReadingQuality
- };
- resultsInfo.Add(info);
+ // Serialize the list of barcode info objects to indented JSON.
+ var json = JsonSerializer.Serialize(results, new JsonSerializerOptions { WriteIndented = true });
+ Console.WriteLine(json);
+ }
}
}
-
- // Serialize the collected barcode information to formatted JSON.
- var jsonOptions = new JsonSerializerOptions { WriteIndented = true };
- string json = JsonSerializer.Serialize(resultsInfo, jsonOptions);
-
- // Output the JSON to the console.
- Console.WriteLine(json);
}
- // Simple DTO for JSON serialization of barcode metrics.
+ ///
+ /// Simple DTO for serializing barcode details.
+ ///
private class BarcodeInfo
{
- public string CodeTypeName { get; set; }
public string CodeText { get; set; }
public string Confidence { get; set; }
public double ReadingQuality { get; set; }
diff --git a/barcode-recognition-basics/interpret-readingquality-value-of-0-as-none-and-prompt-user-to-rescan-barcode.cs b/barcode-recognition-basics/interpret-readingquality-value-of-0-as-none-and-prompt-user-to-rescan-barcode.cs
index af790fb..65be60c 100644
--- a/barcode-recognition-basics/interpret-readingquality-value-of-0-as-none-and-prompt-user-to-rescan-barcode.cs
+++ b/barcode-recognition-basics/interpret-readingquality-value-of-0-as-none-and-prompt-user-to-rescan-barcode.cs
@@ -1,54 +1,58 @@
-// Title: Barcode Reading Quality Evaluation
-// Description: Demonstrates generating a Code128 barcode, reading it, and interpreting a ReadingQuality of 0 as none, prompting the user to rescan.
+// Title: Demonstrate barcode generation, reading, and handling zero ReadingQuality
+// Description: This example generates a Code128 barcode, reads it, and treats a ReadingQuality of 0 as no quality, prompting a rescan.
+// Category-Description: Shows basic Aspose.BarCode operations such as barcode generation with BarcodeGenerator, image saving, and barcode recognition using BarCodeReader. Useful for developers needing to validate scan quality and handle low-quality reads in scanning applications. Covers common use cases like automated scanning, quality assessment, and error handling.
// Prompt: Interpret a ReadingQuality value of 0 as none and prompt the user to rescan the barcode.
-// Tags: barcode symbology, generation, recognition, readingquality, console
+// Tags: code128, barcode generation, barcode recognition, readingquality, quality assessment, aspnet, aspose.barcode
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.BarCode;
///
-/// Example program that creates a barcode, reads it, and checks the reading quality.
+/// Example program that generates a Code128 barcode, reads it, and checks the reading quality.
///
class Program
{
///
- /// Entry point of the application. Generates a barcode, reads it from memory,
- /// and reports the reading quality, prompting a rescan when quality is none.
+ /// Entry point. Generates a barcode, reads it, and outputs quality information.
///
static void Main()
{
- // Generate a Code128 barcode with the value "12345" and keep it in memory.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "12345"))
+ // Define the text to encode in the barcode.
+ const string sampleText = "12345";
+
+ // Create a barcode generator for Code128 symbology.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, sampleText))
{
// Store the generated barcode image in a memory stream.
using (var memoryStream = new MemoryStream())
{
// Save the barcode as a PNG image into the stream.
generator.Save(memoryStream, BarCodeImageFormat.Png);
-
- // Reset the stream position to the beginning for reading.
+ // Reset stream position to the beginning for reading.
memoryStream.Position = 0;
- // Create a reader that can decode all supported barcode types from the stream.
- using (var reader = new BarCodeReader(memoryStream, DecodeType.AllSupportedTypes))
+ // Initialize a barcode reader for Code128 from the memory stream.
+ using (var reader = new BarCodeReader(memoryStream, DecodeType.Code128))
{
- // Iterate through all detected barcodes in the image.
+ // Iterate through all detected barcodes.
foreach (var result in reader.ReadBarCodes())
{
// Retrieve the reading quality metric.
double quality = result.ReadingQuality;
- // If quality is zero, treat it as "none" and ask for a rescan.
- if (quality == 0)
+ // If quality is zero, treat it as none and suggest a rescan.
+ if (quality == 0.0)
{
Console.WriteLine("Reading quality is none. Please rescan the barcode.");
}
else
{
+ // Otherwise, display the quality and decoded text.
Console.WriteLine($"Reading quality: {quality}");
+ Console.WriteLine($"Decoded text: {result.CodeText}");
}
}
}
diff --git a/barcode-recognition-basics/invoke-readbarcodes-and-iterate-over-barcoderesult-array-to-log-each-barcode-s-text-and-type.cs b/barcode-recognition-basics/invoke-readbarcodes-and-iterate-over-barcoderesult-array-to-log-each-barcode-s-text-and-type.cs
index 0d5209f..417e655 100644
--- a/barcode-recognition-basics/invoke-readbarcodes-and-iterate-over-barcoderesult-array-to-log-each-barcode-s-text-and-type.cs
+++ b/barcode-recognition-basics/invoke-readbarcodes-and-iterate-over-barcoderesult-array-to-log-each-barcode-s-text-and-type.cs
@@ -1,38 +1,40 @@
// Title: Read and Log Barcodes from Generated Image
// Description: Generates a Code128 barcode in memory, reads it using Aspose.BarCode, and logs each detected barcode's type and text.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, demonstrating how to create a barcode image with BarcodeGenerator, detect barcodes using BarCodeReader, and process BarCodeResult objects. Developers commonly need to generate barcodes on the fly and immediately verify them by reading back the encoded data, useful in testing, batch processing, or dynamic document creation.
// Prompt: Invoke ReadBarCodes and iterate over the BarCodeResult array to log each barcode's text and type.
-// Tags: barcode symbology, read operation, console output, aspose.barcode, code128
+// Tags: code128, barcode generation, barcode recognition, read, console output, aspose.barcode, aspose.barcode.generation, aspose.barcode.recognition
using System;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Demonstrates how to generate a barcode, read it, and output the results to the console.
+/// Demonstrates generating a barcode, reading it, and outputting its type and text.
///
class Program
{
///
- /// Entry point of the application. Generates a barcode image, reads it, and logs each detected barcode's type and text.
+ /// Entry point. Generates a barcode image, reads it, and writes results to console.
///
static void Main()
{
- // Generate a Code128 barcode image in memory with the value "Sample123".
+ // Create a BarcodeGenerator for Code128 with the sample text "Sample123"
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- // Render the barcode to a bitmap.
+ // Generate the barcode image in memory (as a bitmap)
using (var bitmap = generator.GenerateBarCodeImage())
{
- // Initialize a reader that scans the bitmap for all supported barcode types.
+ // Initialize a BarCodeReader to detect all supported barcode types in the bitmap
using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
{
- // Read all barcodes found in the image.
+ // Read all detected barcodes and iterate over the results
foreach (var result in reader.ReadBarCodes())
{
- // Log the barcode type (symbology) and the decoded text.
- Console.WriteLine($"BarCode Type: {result.CodeTypeName}, Text: {result.CodeText}");
+ // Log the barcode type (e.g., Code128) to the console
+ Console.WriteLine("BarCode Type: " + result.CodeTypeName);
+ // Log the decoded text of the barcode to the console
+ Console.WriteLine("BarCode Text: " + result.CodeText);
}
}
}
diff --git a/barcode-recognition-basics/load-png-image-into-bitmap-object-and-recognize-barcodes-via-barcodereader-constructor.cs b/barcode-recognition-basics/load-png-image-into-bitmap-object-and-recognize-barcodes-via-barcodereader-constructor.cs
index a2961d6..6a2bf44 100644
--- a/barcode-recognition-basics/load-png-image-into-bitmap-object-and-recognize-barcodes-via-barcodereader-constructor.cs
+++ b/barcode-recognition-basics/load-png-image-into-bitmap-object-and-recognize-barcodes-via-barcodereader-constructor.cs
@@ -1,43 +1,54 @@
-// Title: Barcode Recognition from PNG using Aspose.BarCode
-// Description: Loads a PNG image into a Bitmap and uses BarCodeReader to detect and output all supported barcode types found in the image.
+// Title: Barcode generation and recognition from a PNG bitmap
+// Description: Demonstrates creating a Code128 barcode, loading it into a Bitmap, and recognizing it using BarCodeReader.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator, BarCodeReader, and related classes to produce a barcode image in memory, load it via Aspose.Drawing.Bitmap, and decode it. Developers often need to process barcode images without writing to disk, making in‑memory operations essential for web services and automated pipelines.
// Prompt: Load a PNG image into a Bitmap object and recognize barcodes via BarCodeReader constructor.
-// Tags: barcode, recognition, png, aspose, csharp
+// Tags: code128, barcode generation, barcode recognition, png, aspose.barcode, aspose.drawing
using System;
using System.IO;
-using Aspose.Drawing;
+using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates loading a PNG image and recognizing any barcodes it contains using Aspose.BarCode.
+/// Example program that generates a Code128 barcode, loads it into a Bitmap,
+/// and reads the barcode using Aspose.BarCode's BarCodeReader.
///
class Program
{
///
- /// Entry point of the example. Loads the image, creates a reader, and prints detected barcode information.
+ /// Entry point of the example. Generates a barcode, creates a bitmap from it,
+ /// and prints the detected barcode type and text to the console.
///
static void Main()
{
- // Path to the PNG image file
- const string imagePath = "sample.png";
+ // Define the barcode content.
+ string codeText = "1234567890";
- // Verify that the image file exists before attempting to load it
- if (!File.Exists(imagePath))
+ // Generate the barcode image in memory using a PNG format.
+ using (MemoryStream ms = new MemoryStream())
{
- Console.WriteLine($"File not found: {imagePath}");
- return;
- }
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ {
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0; // Reset stream position for reading.
+ }
- // Load the PNG image into an Aspose.Drawing.Bitmap instance
- using (Bitmap bitmap = new Bitmap(imagePath))
- // Initialize BarCodeReader with the bitmap, configuring it to detect all supported barcode types
- using (BarCodeReader reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
- {
- // Iterate through all detected barcodes and output their type and decoded text
- foreach (var result in reader.ReadBarCodes())
+ // Load the generated PNG image into an Aspose.Drawing.Bitmap.
+ using (Bitmap bitmap = new Bitmap(ms))
{
- Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
- Console.WriteLine($"BarCode Text: {result.CodeText}");
+ // Initialize the BarCodeReader to decode Code128 barcodes from the bitmap.
+ using (var reader = new BarCodeReader(bitmap, DecodeType.Code128))
+ {
+ // Iterate through all detected barcodes and output their details.
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($"Code Text: {result.CodeText}");
+ }
+ }
}
}
}
diff --git a/barcode-recognition-basics/log-detailed-recognition-metrics-including-processing-time-and-found-count-for-performance-monitoring-purposes.cs b/barcode-recognition-basics/log-detailed-recognition-metrics-including-processing-time-and-found-count-for-performance-monitoring-purposes.cs
index 4a88d62..5c9cdde 100644
--- a/barcode-recognition-basics/log-detailed-recognition-metrics-including-processing-time-and-found-count-for-performance-monitoring-purposes.cs
+++ b/barcode-recognition-basics/log-detailed-recognition-metrics-including-processing-time-and-found-count-for-performance-monitoring-purposes.cs
@@ -1,7 +1,8 @@
-// Title: Barcode Generation, Recognition, and Performance Logging
-// Description: Generates a Code128 barcode, recognizes it, and logs processing time and detection count for monitoring.
+// Title: Barcode Generation and Recognition with Performance Metrics
+// Description: Demonstrates creating a Code128 barcode, saving it as an image, and recognizing it while logging processing time and count of detected barcodes.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of core API classes such as BarcodeGenerator for creating barcodes, BarCodeReader for decoding, and DecodeType for specifying supported symbologies. Typical scenarios include automated testing, batch processing, and performance monitoring where developers need to generate barcodes, read them back, and capture detailed metrics.
// Prompt: Log detailed recognition metrics, including processing time and found count, for performance monitoring purposes.
-// Tags: barcode, generation, recognition, performance, metrics, code128, aspose, aspnet
+// Tags: code128, generation, recognition, performance, aspose.barcode, barcodegenerator, barcodereader, decodeType, barcoderesult
using System;
using System.Diagnostics;
@@ -11,60 +12,67 @@
using Aspose.Drawing;
///
-/// Demonstrates creating a barcode, recognizing it, and logging detailed performance metrics.
+/// Example program that generates a Code128 barcode, saves it to a file,
+/// reads it back, and logs detailed recognition metrics for performance monitoring.
///
class Program
{
///
- /// Entry point of the example. Generates a barcode, reads it back, and outputs recognition statistics.
+ /// Entry point of the application.
///
static void Main()
{
- // Create a sample barcode image in memory using Code128 symbology.
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ // Define the output image path for the generated barcode
+ string imagePath = "sample.png";
+
+ // Remove any existing file with the same name to ensure a clean run
+ if (File.Exists(imagePath))
{
- // Save the generated barcode to a memory stream in PNG format.
- using (MemoryStream ms = new MemoryStream())
- {
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for reading.
+ File.Delete(imagePath);
+ }
- // Load the PNG image as a Bitmap for barcode recognition.
- using (Bitmap bitmap = new Bitmap(ms))
- {
- // Initialize the barcode reader to detect all supported symbologies.
- using (BarCodeReader reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
- {
- // Start timing the recognition process.
- Stopwatch sw = Stopwatch.StartNew();
+ // Create a BarcodeGenerator for Code128 symbology with sample text
+ var generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123");
+ // Save the generated barcode image to the specified path
+ generator.Save(imagePath);
- // Perform barcode detection.
- BarCodeResult[] results = reader.ReadBarCodes();
+ // Verify that the barcode image was successfully created
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine("Failed to create the barcode image.");
+ return;
+ }
- // Stop timing after detection completes.
- sw.Stop();
+ // Initialize a Stopwatch to measure recognition duration
+ var stopwatch = new Stopwatch();
- // Log overall performance metrics.
- Console.WriteLine($"Processing Time (ms): {sw.ElapsedMilliseconds}");
- Console.WriteLine($"Barcodes Detected: {results.Length}");
+ // Open a BarCodeReader for all supported barcode types on the generated image
+ using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ {
+ // Start timing before the recognition process
+ stopwatch.Start();
+
+ // Perform barcode detection and retrieve results
+ BarCodeResult[] results = reader.ReadBarCodes();
- // Iterate through each detected barcode and log detailed information.
- for (int i = 0; i < results.Length; i++)
- {
- BarCodeResult result = results[i];
- Console.WriteLine($"--- Barcode #{i + 1} ---");
- Console.WriteLine($"Type: {result.CodeTypeName}");
- Console.WriteLine($"Text: {result.CodeText}");
- Console.WriteLine($"Confidence: {result.Confidence}");
- Console.WriteLine($"Reading Quality: {result.ReadingQuality}");
- Console.WriteLine($"Angle: {result.Region.Angle}");
+ // Stop timing after recognition completes
+ stopwatch.Stop();
- // Output the region rectangle coordinates (pixel values).
- var rect = result.Region.Rectangle;
- Console.WriteLine($"Region - X:{rect.X}, Y:{rect.Y}, Width:{rect.Width}, Height:{rect.Height}");
- }
- }
- }
+ // Output processing time and total number of barcodes detected
+ Console.WriteLine($"Processing Time (ms): {stopwatch.ElapsedMilliseconds}");
+ Console.WriteLine($"Barcodes Detected: {reader.FoundCount}");
+
+ // Iterate through each detected barcode and display detailed information
+ foreach (var result in results)
+ {
+ Console.WriteLine("----- Barcode -----");
+ Console.WriteLine($"Type: {result.CodeTypeName}");
+ Console.WriteLine($"Text: {result.CodeText}");
+ Console.WriteLine($"Confidence: {result.Confidence}");
+ Console.WriteLine($"Reading Quality: {result.ReadingQuality}");
+ 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}");
}
}
}
diff --git a/barcode-recognition-basics/log-warning-when-barcoderesultconfidence-equals-confidencemoderate-and-suggest-image-enhancement-to-user.cs b/barcode-recognition-basics/log-warning-when-barcoderesultconfidence-equals-confidencemoderate-and-suggest-image-enhancement-to-user.cs
index de42a46..3e87563 100644
--- a/barcode-recognition-basics/log-warning-when-barcoderesultconfidence-equals-confidencemoderate-and-suggest-image-enhancement-to-user.cs
+++ b/barcode-recognition-basics/log-warning-when-barcoderesultconfidence-equals-confidencemoderate-and-suggest-image-enhancement-to-user.cs
@@ -1,7 +1,8 @@
-// Title: Barcode generation, reading, and confidence warning demo
-// Description: Demonstrates creating a Code128 barcode, reading it, and logging a warning when the recognition confidence is moderate, suggesting image enhancement.
+// Title: Barcode Generation, Recognition, and Confidence Warning
+// Description: Demonstrates generating a Code128 barcode, reading it back, and logging a warning when recognition confidence is moderate.
+// 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 assess recognition confidence and provide guidance for image quality improvement, especially when confidence is moderate.
// Prompt: Log a warning when BarCodeResult.Confidence equals Confidence.Moderate and suggest image enhancement to the user.
-// Tags: barcode symbology, generation, recognition, confidence, warning, console
+// Tags: barcode, code128, generation, recognition, confidence, moderate, image enhancement, png, aspose.barcode
using System;
using System.IO;
@@ -10,78 +11,50 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates barcode generation, reading, and confidence handling.
+/// Generates a Code128 barcode, saves it as an image, reads it back,
+/// and logs a warning if the recognition confidence is moderate.
///
class Program
{
///
- /// Entry point. Generates a barcode image, reads it, and logs a warning if confidence is moderate.
+ /// Entry point of the example.
///
static void Main()
{
- // Define the path where the barcode image will be saved
- string imagePath = "barcode.png";
+ // Define the output path for the generated barcode image.
+ string imagePath = "sample_barcode.png";
- // -------------------------------------------------
- // Generate a simple Code128 barcode and save it to file
- // -------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
+ // Create a barcode generator for Code128 with the data "12345".
+ // Set a moderate resolution (300 DPI) to improve recognition confidence.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "12345"))
{
- // Set a standard resolution to improve image quality
- generator.Parameters.Resolution = 300;
- generator.Save(imagePath);
+ generator.Parameters.Resolution = 300; // DPI
+ generator.Save(imagePath); // Save the barcode image to the specified path.
}
- // -------------------------------------------------
- // Verify that the barcode image file was created successfully
- // -------------------------------------------------
+ // Verify that the image file was created before attempting to read it.
if (!File.Exists(imagePath))
{
Console.WriteLine($"Error: Barcode image not found at '{imagePath}'.");
return;
}
- // -------------------------------------------------
- // Read the barcode from the saved image file
- // -------------------------------------------------
+ // Initialize a barcode reader for Code128 and read the saved image.
using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
{
- bool anyResult = false;
-
- // Iterate through all detected barcodes
+ // Iterate through all detected barcode results.
foreach (BarCodeResult result in reader.ReadBarCodes())
{
- anyResult = true;
-
- // Output basic barcode information
- Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
- Console.WriteLine($"BarCode CodeText: {result.CodeText}");
- Console.WriteLine($"BarCode Confidence: {result.Confidence}");
+ Console.WriteLine($"Type: {result.CodeTypeName}");
+ Console.WriteLine($"Text: {result.CodeText}");
+ Console.WriteLine($"Confidence: {result.Confidence}");
- // Log a warning if the confidence level is moderate
+ // If the confidence level is moderate, log a warning and suggest image enhancement.
if (result.Confidence == BarCodeConfidence.Moderate)
{
- Console.WriteLine("Warning: Moderate confidence detected. Consider enhancing the image (e.g., increase resolution, improve lighting) for better recognition.");
+ Console.WriteLine("Warning: Barcode confidence is moderate. Consider enhancing the image (e.g., increase resolution, improve lighting).");
}
}
-
- // Inform the user if no barcodes were detected
- if (!anyResult)
- {
- Console.WriteLine("No barcodes were detected in the image.");
- }
- }
-
- // -------------------------------------------------
- // Clean up the generated image file (optional)
- // -------------------------------------------------
- try
- {
- File.Delete(imagePath);
- }
- catch
- {
- // Ignore any errors that occur during cleanup
}
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/map-readingquality-values-1-99-to-moderate-quality-and-trigger-warning-log-for-each-occurrence.cs b/barcode-recognition-basics/map-readingquality-values-1-99-to-moderate-quality-and-trigger-warning-log-for-each-occurrence.cs
index b1af33a..11a82a0 100644
--- a/barcode-recognition-basics/map-readingquality-values-1-99-to-moderate-quality-and-trigger-warning-log-for-each-occurrence.cs
+++ b/barcode-recognition-basics/map-readingquality-values-1-99-to-moderate-quality-and-trigger-warning-log-for-each-occurrence.cs
@@ -1,7 +1,8 @@
-// Title: Barcode Generation, Reading, and Quality Mapping
-// Description: Generates a Code128 barcode, reads it, and maps reading quality values 1‑99 to moderate quality, logging a warning for each occurrence.
+// Title: Mapping ReadingQuality to Moderate Quality with Warning Log
+// Description: Demonstrates generating Code128 barcodes, reading them, and mapping ReadingQuality values 1‑99 to moderate quality, logging a warning for each occurrence.
+// 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 the ReadingQuality property to assess scan confidence. Developers often need to evaluate reading quality to trigger alerts or adjust processing logic in inventory, logistics, or document automation scenarios.
// Prompt: Map ReadingQuality values 1‑99 to moderate quality and trigger a warning log for each occurrence.
-// Tags: barcode, generation, recognition, readingquality, warning, console
+// Tags: code128, generation, recognition, readingquality, png, aspose.barcode, barcode
using System;
using System.IO;
@@ -10,49 +11,54 @@
using Aspose.Drawing;
///
-/// Demonstrates barcode generation, recognition, and mapping of ReadingQuality values to moderate quality with warning logs.
+/// Generates sample Code128 barcodes, reads them back, and logs a warning when the
+/// falls within the moderate range (1‑99).
///
class Program
{
///
- /// Entry point of the example. Generates a barcode, reads it, and processes the reading quality.
+ /// Entry point of the example. Iterates over sample texts, creates barcode images,
+ /// decodes them, and evaluates the reading quality.
///
static void Main()
{
- // Generate a sample barcode and store it in a memory stream
- using (var ms = new MemoryStream())
+ // Define sample barcode texts to encode.
+ string[] texts = { "12345", "ABCDEF", "9876543210" };
+
+ // Process each text individually.
+ foreach (string text in texts)
{
- // Create a barcode generator for Code128 with sample text
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ // Create an in‑memory stream to hold the generated barcode image.
+ using (var ms = new MemoryStream())
{
- // Save the generated barcode as PNG into the memory stream
- generator.Save(ms, BarCodeImageFormat.Png);
- }
+ // Generate a Code128 barcode and save it as PNG into the stream.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, text))
+ {
+ generator.Save(ms, BarCodeImageFormat.Png);
+ }
- // Reset stream position before reading the image
- ms.Position = 0;
+ // Reset the stream position so it can be read from the beginning.
+ ms.Position = 0;
- // Load the image from the memory stream into a Bitmap (Aspose.Drawing)
- using (var bitmap = new Bitmap(ms))
- {
- // Create a reader that detects all supported barcode types
- using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
+ // Initialize a barcode reader that supports all available symbologies.
+ using (var reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes))
{
- // Iterate through each detected barcode result
- foreach (var result in reader.ReadBarCodes())
+ // Iterate over all detected barcodes in the image.
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
- // Output basic barcode information
- Console.WriteLine($"Barcode Type: {result.CodeTypeName}");
- Console.WriteLine($"Code Text: {result.CodeText}");
- Console.WriteLine($"Reading Quality: {result.ReadingQuality}");
+ double readingQuality = result.ReadingQuality;
+
+ // Output the decoded text and its reading quality.
+ Console.WriteLine($"Barcode Text: {result.CodeText}");
+ Console.WriteLine($"Reading Quality: {readingQuality}");
- // Map ReadingQuality values 1‑99 to moderate quality and log a warning
- if (result.ReadingQuality >= 1 && result.ReadingQuality <= 99)
+ // Map values 1‑99 to moderate quality and log a warning.
+ if (readingQuality >= 1 && readingQuality <= 99)
{
- Console.WriteLine($"Warning: ReadingQuality {result.ReadingQuality} is considered moderate.");
+ Console.WriteLine($"Warning: ReadingQuality {readingQuality} is considered moderate.");
}
- Console.WriteLine(); // Blank line for readability between results
+ Console.WriteLine(); // Blank line for readability between results.
}
}
}
diff --git a/barcode-recognition-basics/measure-impact-of-limiting-decodetype-versus-using-multydecodetype-on-overall-recognition-speed.cs b/barcode-recognition-basics/measure-impact-of-limiting-decodetype-versus-using-multydecodetype-on-overall-recognition-speed.cs
index 0b39ffb..3f5b0d9 100644
--- a/barcode-recognition-basics/measure-impact-of-limiting-decodetype-versus-using-multydecodetype-on-overall-recognition-speed.cs
+++ b/barcode-recognition-basics/measure-impact-of-limiting-decodetype-versus-using-multydecodetype-on-overall-recognition-speed.cs
@@ -1,118 +1,117 @@
-// Title: DecodeType vs MultiDecodeType performance comparison
-// Description: Demonstrates how limiting the DecodeType to a single symbology versus using MultiDecodeType affects barcode recognition speed.
+// Title: Measure impact of limited vs multi decode types on barcode recognition speed
+// Description: Demonstrates generating sample barcodes and comparing recognition time when using a specific DecodeType versus MultiDecodeType.
+// Category-Description: This example belongs to the Aspose.BarCode recognition performance category, illustrating how to use BarcodeGenerator, BarCodeReader, DecodeType, and MultiDecodeType classes. Developers often need to benchmark decoding speed for different symbologies to optimize scanning applications. The snippet shows typical use cases such as generating test images, configuring decoders, and measuring execution time, useful for performance tuning and CI testing.
// Prompt: Measure the impact of limiting DecodeType versus using MultyDecodeType on overall recognition speed.
-// Tags: barcode, decode, multidecode, performance, aspnet, csharp
+// Tags: barcode, decode, multidecode, performance, aspose.barcode, generation, recognition
using System;
-using System.Collections.Generic;
-using System.Diagnostics;
using System.IO;
-using System.Linq;
+using System.Diagnostics;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Sample program that generates several barcode images and measures the
-/// recognition time when using a single versus a
-/// that includes multiple symbologies.
+/// Demonstrates measuring the performance difference between limited
+/// and when recognizing barcodes using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application. Generates barcodes, reads them with
- /// different decode configurations, and reports average recognition times.
+ /// Entry point. Generates sample barcode images, then measures and prints average recognition times.
///
static void Main()
{
- // --------------------------------------------------------------------
- // Prepare a temporary folder for the generated barcode images.
- // --------------------------------------------------------------------
- string tempFolder = Path.Combine(Path.GetTempPath(), "AsposeBarcodeSample");
- if (!Directory.Exists(tempFolder))
- Directory.CreateDirectory(tempFolder);
+ // Prepare a folder for sample barcode images
+ string folder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(folder))
+ {
+ Directory.CreateDirectory(folder);
+ }
- // --------------------------------------------------------------------
- // Define the barcode specifications: symbology, text, and output file name.
- // --------------------------------------------------------------------
- var specs = new List<(BaseEncodeType encode, string text, string fileName)>
+ // Define sample barcodes to generate (type, text, file name)
+ var samples = new (BaseEncodeType encode, string text, string fileName)[]
{
(EncodeTypes.Code128, "CODE128_SAMPLE", "code128.png"),
(EncodeTypes.QR, "QR_SAMPLE", "qr.png"),
(EncodeTypes.DataMatrix, "DATAMATRIX_SAMPLE", "datamatrix.png")
};
- // --------------------------------------------------------------------
- // Generate barcode images based on the specifications.
- // --------------------------------------------------------------------
- var imagePaths = new List();
- foreach (var spec in specs)
+ // Generate barcode images and save them to the folder
+ foreach (var sample in samples)
{
- string path = Path.Combine(tempFolder, spec.fileName);
- using (var generator = new BarcodeGenerator(spec.encode, spec.text))
+ string path = Path.Combine(folder, sample.fileName);
+ using (var generator = new BarcodeGenerator(sample.encode, sample.text))
{
generator.Save(path);
}
- imagePaths.Add(path);
}
- // --------------------------------------------------------------------
- // Prepare decode configurations:
- // - limitedDecode: only Code128 is allowed.
- // - multiDecode: Code128, QR, and DataMatrix are allowed.
- // --------------------------------------------------------------------
- var limitedDecode = DecodeType.Code128; // example limited to Code128
+ // Define decode types for limited (single) and multi decode scenarios
+ var limitedDecodes = new (string name, BaseDecodeType decode)[]
+ {
+ ("Code128", DecodeType.Code128),
+ ("QR", DecodeType.QR),
+ ("DataMatrix", DecodeType.DataMatrix)
+ };
+
+ // MultiDecodeType that includes all three symbologies
var multiDecode = new MultiDecodeType(DecodeType.Code128, DecodeType.QR, DecodeType.DataMatrix);
- // --------------------------------------------------------------------
- // Containers for timing results.
- // --------------------------------------------------------------------
- var limitedTimes = new List();
- var multiTimes = new List();
+ // Header for the performance comparison output
+ Console.WriteLine("Recognition speed comparison (average over 5 runs per image):");
- // --------------------------------------------------------------------
- // Iterate over each generated image and measure recognition speed for both
- // decode configurations.
- // --------------------------------------------------------------------
- foreach (string imagePath in imagePaths)
+ // Iterate over each sample image and measure both decoding approaches
+ foreach (var sample in samples)
{
- if (!File.Exists(imagePath))
+ string imagePath = Path.Combine(folder, sample.fileName);
+ Console.WriteLine($"\nImage: {sample.fileName}");
+
+ // Find the matching limited decode type based on the file name (without extension)
+ var limited = Array.Find(limitedDecodes, d => d.name == Path.GetFileNameWithoutExtension(sample.fileName));
+ if (limited.decode == null)
{
- Console.WriteLine($"File not found: {imagePath}");
+ Console.WriteLine(" No matching limited decode type found.");
continue;
}
- // ---- Limited DecodeType (single symbology) ----
- using (var readerLimited = new BarCodeReader(imagePath, limitedDecode))
+ // Measure average time for limited (single) decode
+ long limitedTotalMs = 0;
+ for (int i = 0; i < 5; i++)
{
var sw = Stopwatch.StartNew();
- var results = readerLimited.ReadBarCodes();
+ using (var reader = new BarCodeReader(imagePath, limited.decode))
+ {
+ foreach (var result in reader.ReadBarCodes())
+ {
+ // Force recognition; result is not used further
+ }
+ }
sw.Stop();
-
- limitedTimes.Add(sw.ElapsedMilliseconds);
- Console.WriteLine($"Limited decode on '{Path.GetFileName(imagePath)}' found {results.Length} barcode(s) in {sw.ElapsedMilliseconds} ms.");
+ limitedTotalMs += sw.ElapsedMilliseconds;
}
+ double limitedAvg = limitedTotalMs / 5.0;
- // ---- MultiDecodeType (multiple symbologies) ----
- using (var readerMulti = new BarCodeReader(imagePath, multiDecode))
+ // Measure average time for multi decode (all three types)
+ long multiTotalMs = 0;
+ for (int i = 0; i < 5; i++)
{
var sw = Stopwatch.StartNew();
- var results = readerMulti.ReadBarCodes();
+ using (var reader = new BarCodeReader(imagePath, multiDecode))
+ {
+ foreach (var result in reader.ReadBarCodes())
+ {
+ // Force recognition; result is not used further
+ }
+ }
sw.Stop();
-
- multiTimes.Add(sw.ElapsedMilliseconds);
- Console.WriteLine($"Multi decode on '{Path.GetFileName(imagePath)}' found {results.Length} barcode(s) in {sw.ElapsedMilliseconds} ms.");
+ multiTotalMs += sw.ElapsedMilliseconds;
}
- }
-
- // --------------------------------------------------------------------
- // Compute and display average recognition times for both configurations.
- // --------------------------------------------------------------------
- double avgLimited = limitedTimes.Count > 0 ? (double)limitedTimes.Sum() / limitedTimes.Count : 0;
- double avgMulti = multiTimes.Count > 0 ? (double)multiTimes.Sum() / multiTimes.Count : 0;
+ double multiAvg = multiTotalMs / 5.0;
- Console.WriteLine();
- Console.WriteLine($"Average recognition time (limited DecodeType): {avgLimited:F2} ms");
- Console.WriteLine($"Average recognition time (MultiDecodeType): {avgMulti:F2} ms");
+ // Output the average times for both approaches
+ Console.WriteLine($" Limited decode ({limited.name}) avg time: {limitedAvg:F2} ms");
+ Console.WriteLine($" Multi decode (Code128+QR+DataMatrix) avg time: {multiAvg:F2} ms");
+ }
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/measure-memory-footprint-of-barcodereader-when-processing-10-000-barcode-images-sequentially-with-checksum-verification.cs b/barcode-recognition-basics/measure-memory-footprint-of-barcodereader-when-processing-10-000-barcode-images-sequentially-with-checksum-verification.cs
index 28c2a61..659610e 100644
--- a/barcode-recognition-basics/measure-memory-footprint-of-barcodereader-when-processing-10-000-barcode-images-sequentially-with-checksum-verification.cs
+++ b/barcode-recognition-basics/measure-memory-footprint-of-barcodereader-when-processing-10-000-barcode-images-sequentially-with-checksum-verification.cs
@@ -1,74 +1,93 @@
// Title: Measure memory usage of BarCodeReader with checksum validation
-// Description: Demonstrates generating and reading Code128 barcodes while measuring the process memory before and after handling a set of images.
+// Description: Demonstrates how to generate 10,000 Code128 barcode images, read them sequentially with checksum verification, and measure the memory footprint of BarCodeReader.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating the use of BarCodeReader and BarcodeGenerator for bulk processing. It shows typical scenarios where developers need to evaluate memory consumption while decoding large numbers of barcodes with checksum validation enabled, using classes such as BarcodeGenerator, BarCodeReader, and related settings.
// Prompt: Measure memory footprint of BarCodeReader when processing 10,000 barcode images sequentially with checksum verification enabled.
-// Tags: barcode, code128, memory, checksum, barcodereader, barcodegenerator
+// Tags: code128, checksum, memory, barcodereader, barcodegenerator, png, aspose.barcode
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 a few Code128 barcodes, reads them with checksum validation,
-/// and reports the memory consumption before and after processing.
+/// Demonstrates measuring the memory footprint of when processing a large number of barcode images with checksum validation enabled.
///
class Program
{
///
- /// Entry point of the application. Measures memory usage while processing barcode images.
+ /// Entry point of the example. Generates sample barcode images, reads them with checksum validation, and reports memory usage.
///
static void Main()
{
- // Sample barcode texts (Code128 includes checksum automatically)
- string[] codes = new string[]
+ // --------------------------------------------------------------------
+ // Create a temporary folder for sample barcode images
+ // --------------------------------------------------------------------
+ string folder = Path.Combine(Path.GetTempPath(), "AsposeBarCodeSample");
+ if (!Directory.Exists(folder))
{
- "123456789012",
- "987654321098",
- "555555555555",
- "111111111111",
- "222222222222"
- };
+ Directory.CreateDirectory(folder);
+ }
+
+ // --------------------------------------------------------------------
+ // Number of images to process (scaled down for demo; replace with 10000 for real measurement)
+ // --------------------------------------------------------------------
+ int sampleCount = 10;
+
+ // --------------------------------------------------------------------
+ // Generate sample barcode images (Code128) and save them as PNG files
+ // --------------------------------------------------------------------
+ for (int i = 0; i < sampleCount; i++)
+ {
+ string filePath = Path.Combine(folder, $"barcode_{i}.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"CODE{i:D5}"))
+ {
+ generator.Save(filePath, BarCodeImageFormat.Png);
+ }
+ }
- // Force garbage collection and capture baseline memory usage
- GC.Collect();
- GC.WaitForPendingFinalizers();
+ // --------------------------------------------------------------------
+ // Record memory usage before processing the images
+ // --------------------------------------------------------------------
long memoryBefore = GC.GetTotalMemory(true);
- // Process each barcode image sequentially
- foreach (string code in codes)
+ // --------------------------------------------------------------------
+ // Process each image sequentially with checksum validation enabled
+ // --------------------------------------------------------------------
+ for (int i = 0; i < sampleCount; i++)
{
- // Generate barcode image into a memory stream
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, code))
+ string filePath = Path.Combine(folder, $"barcode_{i}.png");
+ if (!File.Exists(filePath))
{
- using (var ms = new MemoryStream())
- {
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for reading
+ Console.WriteLine($"File not found: {filePath}");
+ continue;
+ }
- // Read the barcode with checksum validation enabled
- using (var reader = new BarCodeReader(ms, DecodeType.Code128))
- {
- reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"Detected: Type={result.CodeTypeName}, Text={result.CodeText}");
- }
- }
+ using (var reader = new BarCodeReader(filePath, DecodeType.Code128))
+ {
+ // Enable checksum validation for each read operation
+ reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
+
+ // Iterate through all detected barcodes in the image
+ foreach (var result in reader.ReadBarCodes())
+ {
+ // Output the type and text of the decoded barcode
+ Console.WriteLine($"Read {result.CodeTypeName}: {result.CodeText}");
}
}
}
- // Force garbage collection and capture final memory usage
- GC.Collect();
- GC.WaitForPendingFinalizers();
+ // --------------------------------------------------------------------
+ // Record memory usage after processing and calculate the difference
+ // --------------------------------------------------------------------
long memoryAfter = GC.GetTotalMemory(true);
+ long memoryUsed = memoryAfter - memoryBefore;
+ // --------------------------------------------------------------------
// Output memory consumption details
- Console.WriteLine($"Memory before processing: {memoryBefore / 1024} KB");
- Console.WriteLine($"Memory after processing: {memoryAfter / 1024} KB");
- Console.WriteLine($"Memory increase: { (memoryAfter - memoryBefore) / 1024 } KB");
+ // --------------------------------------------------------------------
+ Console.WriteLine($"Memory before: {memoryBefore} bytes");
+ Console.WriteLine($"Memory after: {memoryAfter} bytes");
+ Console.WriteLine($"Memory used during processing: {memoryUsed} bytes");
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/parallelize-barcode-reading-across-multiple-cpu-cores-by-creating-separate-barcodereader-instances-for-each-image.cs b/barcode-recognition-basics/parallelize-barcode-reading-across-multiple-cpu-cores-by-creating-separate-barcodereader-instances-for-each-image.cs
index 2b60bbd..d1013d2 100644
--- a/barcode-recognition-basics/parallelize-barcode-reading-across-multiple-cpu-cores-by-creating-separate-barcodereader-instances-for-each-image.cs
+++ b/barcode-recognition-basics/parallelize-barcode-reading-across-multiple-cpu-cores-by-creating-separate-barcodereader-instances-for-each-image.cs
@@ -1,104 +1,79 @@
-// Title: Parallel barcode reading across multiple CPU cores
-// Description: Demonstrates generating barcode images, then reading them concurrently using separate BarCodeReader instances per image to utilize all processor cores.
+// Title: Parallel Barcode Reading Using Multiple Cores
+// Description: Demonstrates how to read barcodes from multiple images concurrently by creating separate BarCodeReader instances per image.
+// Category-Description: This example belongs to the Aspose.BarCode reading operations category. It showcases the use of BarCodeReader, ProcessorSettings, and parallel programming (Parallel.ForEach) to efficiently decode barcodes across many files. Developers often need to process large batches of images quickly, and this pattern illustrates typical usage for high‑throughput barcode recognition in .NET applications.
// Prompt: Parallelize barcode reading across multiple CPU cores by creating separate BarCodeReader instances for each image.
-// Tags: barcode, parallel, multithreading, code128, aspose, generation, recognition
+// Tags: barcode symbology, barcode reading, parallel processing, multithreading, aspose.barcode, code128, png, decode
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates parallel barcode reading using Aspose.BarCode.
-/// Generates sample barcode images, reads them concurrently on multiple CPU cores,
-/// and then cleans up the temporary files.
+/// Demonstrates parallel barcode reading across multiple CPU cores using Aspose.BarCode.
///
class Program
{
///
- /// Entry point that generates sample barcodes, reads them in parallel, and cleans up.
+ /// Entry point that generates sample barcodes and reads them in parallel.
///
static void Main()
{
- // Configure Aspose.BarCode to use all available processor cores for each reader instance.
- BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Environment.ProcessorCount;
-
- // Create a temporary directory to store generated barcode images.
- string tempDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodes");
- Directory.CreateDirectory(tempDir);
-
- // Sample data to encode into barcodes.
- var sampleTexts = new List
+ // --------------------------------------------------------------------
+ // Prepare output folder for generated barcode images
+ // --------------------------------------------------------------------
+ string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(folderPath))
{
- "Sample001",
- "Sample002",
- "Sample003",
- "Sample004",
- "Sample005"
- };
+ Directory.CreateDirectory(folderPath);
+ }
- // Generate barcode images and collect their file paths.
- var imagePaths = new List();
- foreach (var text in sampleTexts)
+ // --------------------------------------------------------------------
+ // Generate a set of sample barcode images (5 PNG files)
+ // --------------------------------------------------------------------
+ List imageFiles = new List();
+ for (int i = 1; i <= 5; i++)
{
- string filePath = Path.Combine(tempDir, $"{text}.png");
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, text))
+ string filePath = Path.Combine(folderPath, $"barcode_{i}.png");
+ string codeText = $"Sample{i:D3}";
+
+ // Create a Code128 barcode and save it directly as PNG
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
{
- // Save each barcode as a PNG image.
generator.Save(filePath, BarCodeImageFormat.Png);
}
- imagePaths.Add(filePath);
+
+ imageFiles.Add(filePath);
}
- // Read barcodes in parallel, one BarCodeReader per image.
- Parallel.ForEach(imagePaths, imagePath =>
- {
- // Verify that the image file exists before attempting to read.
- if (!File.Exists(imagePath))
- {
- Console.WriteLine($"File not found: {imagePath}");
- return;
- }
+ // --------------------------------------------------------------------
+ // Configure the barcode processor to utilize all available CPU cores
+ // --------------------------------------------------------------------
+ BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Environment.ProcessorCount;
- // Each thread creates its own BarCodeReader instance.
- using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ // --------------------------------------------------------------------
+ // Perform parallel barcode reading – each thread gets its own reader
+ // --------------------------------------------------------------------
+ Parallel.ForEach(imageFiles, file =>
+ {
+ // Instantiate a BarCodeReader for the current image file
+ using (var reader = new BarCodeReader(file, DecodeType.AllSupportedTypes))
{
- // Read all barcodes present in the image.
- BarCodeResult[] results = reader.ReadBarCodes();
-
- // Output the results to the console.
- foreach (var result in results)
+ // Iterate through all detected barcodes in the image
+ foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"File: {Path.GetFileName(imagePath)} | Type: {result.CodeTypeName} | Text: {result.CodeText}");
+ // Ensure console output from multiple threads does not interleave
+ lock (Console.Out)
+ {
+ Console.WriteLine($"File: {Path.GetFileName(file)}");
+ Console.WriteLine($" Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($" Code Text: {result.CodeText}");
+ }
}
}
});
-
- // Cleanup temporary barcode image files (optional).
- foreach (var path in imagePaths)
- {
- try
- {
- File.Delete(path);
- }
- catch
- {
- // Ignore any errors during file deletion.
- }
- }
-
- // Remove the temporary directory.
- try
- {
- Directory.Delete(tempDir);
- }
- catch
- {
- // Ignore any errors during directory deletion.
- }
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/pass-memory-stream-containing-tiff-data-to-barcodereader-and-extract-all-detected-barcode-values.cs b/barcode-recognition-basics/pass-memory-stream-containing-tiff-data-to-barcodereader-and-extract-all-detected-barcode-values.cs
index 6f5900f..28b8882 100644
--- a/barcode-recognition-basics/pass-memory-stream-containing-tiff-data-to-barcodereader-and-extract-all-detected-barcode-values.cs
+++ b/barcode-recognition-basics/pass-memory-stream-containing-tiff-data-to-barcodereader-and-extract-all-detected-barcode-values.cs
@@ -1,7 +1,8 @@
-// Title: Barcode generation and recognition from a TIFF memory stream
-// Description: Demonstrates creating a Code128 barcode, storing it as a TIFF in a memory stream, then reading and outputting all detected barcode values.
+// Title: Read barcodes from a TIFF memory stream using Aspose.BarCode
+// Description: Demonstrates how to generate a Code128 barcode, store it in a TIFF memory stream, and then read all detected barcodes from that stream.
+// Category-Description: This example belongs to the Aspose.BarCode reading category, showcasing the use of BarCodeReader with DecodeType.AllSupportedTypes to extract barcode information from image streams. It highlights key classes such as BarcodeGenerator, BarCodeReader, and BarCodeImageFormat, which developers commonly use for barcode generation and recognition in automated processing pipelines.
// Prompt: Pass a memory stream containing TIFF data to BarCodeReader and extract all detected barcode values.
-// Tags: barcode, tiff, memorystream, generation, recognition, aspnet, csharp
+// Tags: barcode symbology, read, tiff, aspose.barcode, barcodereader, barcodegenerator
using System;
using System.IO;
@@ -11,42 +12,36 @@
///
/// Example program that generates a Code128 barcode, saves it as a TIFF image in a memory stream,
-/// and then reads the barcode back using .
+/// and then reads all detected barcodes from that stream using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application. Generates a barcode, writes it to a memory stream,
- /// and extracts all detected barcode values from the stream.
+ /// Entry point of the example. Generates a barcode, stores it in a TIFF memory stream,
+ /// and extracts barcode values using BarCodeReader.
///
static void Main()
{
// Create a memory stream to hold the generated TIFF image.
- using (var memoryStream = new MemoryStream())
+ using (var tiffStream = new MemoryStream())
{
- // Generate a Code128 barcode with the text "Sample123".
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ // Generate a Code128 barcode with the text "1234567890" and save it as TIFF into the stream.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Save the barcode image into the memory stream in TIFF format.
- generator.Save(memoryStream, BarCodeImageFormat.Tiff);
+ generator.Save(tiffStream, BarCodeImageFormat.Tiff);
}
// Reset the stream position to the beginning before reading.
- memoryStream.Position = 0;
+ tiffStream.Position = 0;
- // Initialize a BarCodeReader to process the TIFF image from the memory stream.
- using (var reader = new BarCodeReader(memoryStream))
+ // Initialize BarCodeReader to detect all supported barcode types from the TIFF stream.
+ using (var reader = new BarCodeReader(tiffStream, DecodeType.AllSupportedTypes))
{
- // Instruct the reader to detect all supported barcode types.
- reader.BarCodeReadType = DecodeType.AllSupportedTypes;
-
- // Perform the barcode detection and retrieve the results.
- var results = reader.ReadBarCodes();
-
- // Iterate through each detected barcode and output its text value.
- foreach (var result in results)
+ // Iterate through all detected barcodes and output their type and value.
+ foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"Detected barcode: {result.CodeText}");
+ Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
+ Console.WriteLine($"BarCode Value: {result.CodeText}");
}
}
}
diff --git a/barcode-recognition-basics/process-batch-of-image-files-in-directory-by-looping-barcodereader-construction-for-each-file-path.cs b/barcode-recognition-basics/process-batch-of-image-files-in-directory-by-looping-barcodereader-construction-for-each-file-path.cs
index e239c3b..bb0a240 100644
--- a/barcode-recognition-basics/process-batch-of-image-files-in-directory-by-looping-barcodereader-construction-for-each-file-path.cs
+++ b/barcode-recognition-basics/process-batch-of-image-files-in-directory-by-looping-barcodereader-construction-for-each-file-path.cs
@@ -1,64 +1,75 @@
-// Title: Batch Barcode Reading from Directory
-// Description: Demonstrates reading barcodes from multiple image files in a folder by creating a BarCodeReader for each file.
+// Title: Batch barcode reading from image files
+// Description: Generates sample Code128 barcodes as PNG images, then reads each image to extract barcode data.
+// Category-Description: This example demonstrates combined barcode generation and recognition using Aspose.BarCode. It showcases the BarcodeGenerator for creating barcodes and BarCodeReader for decoding them, a common workflow for batch processing of scanned documents, inventory images, or automated data entry systems. Developers often need to loop through files, construct readers per image, and handle multiple symbologies efficiently.
// Prompt: Process a batch of image files in a directory by looping BarCodeReader construction for each file path.
-// Tags: barcode, batch processing, image, aspose, barcodereader, console
+// Tags: code128, batch-processing, png, barcodegenerator, barcodereader, decode, encode
using System;
using System.IO;
+using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Example program that scans a set of image files for barcodes using Aspose.BarCode.
+/// Demonstrates how to generate a set of barcode images and then read them in a batch
+/// using Aspose.BarCode's and classes.
///
class Program
{
///
- /// Entry point. Loops through a limited number of image files in a directory,
- /// creates a for each, and prints detected barcode information.
+ /// Entry point of the example. Creates sample barcode PNG files, then iterates over each file,
+ /// constructs a for it, and outputs the decoded information.
///
- ///
- /// Optional command‑line argument specifying the directory path containing barcode images.
- /// If omitted, the program defaults to a folder named "Barcodes".
- ///
- static void Main(string[] args)
+ static void Main()
{
- // Determine the directory containing barcode images.
- // Use the first command‑line argument if provided; otherwise default to "Barcodes".
- string directoryPath = args.Length > 0 ? args[0] : "Barcodes";
-
- // Verify that the directory exists before proceeding.
- if (!Directory.Exists(directoryPath))
+ // --------------------------------------------------------------------
+ // Set up a folder to store generated barcode images
+ // --------------------------------------------------------------------
+ string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(folderPath))
{
- Console.WriteLine($"Directory not found: {directoryPath}");
- return;
+ Directory.CreateDirectory(folderPath);
}
- // Retrieve all files in the directory (any extension).
- string[] files = Directory.GetFiles(directoryPath);
+ // --------------------------------------------------------------------
+ // Generate a few sample Code128 barcode images (self‑contained example)
+ // --------------------------------------------------------------------
+ for (int i = 1; i <= 5; i++)
+ {
+ string fileName = $"barcode{i}.png";
+ string filePath = Path.Combine(folderPath, fileName);
- // Limit processing to a safe sample size (up to 5 files) to avoid long runtimes.
- int maxFiles = Math.Min(5, files.Length);
+ // Create a barcode generator for Code128 with sample text
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i}"))
+ {
+ // Save the generated barcode as a PNG file
+ generator.Save(filePath);
+ }
+ }
- // Iterate over each selected file.
- for (int i = 0; i < maxFiles; i++)
+ // --------------------------------------------------------------------
+ // Retrieve all PNG files from the folder for processing
+ // --------------------------------------------------------------------
+ string[] imageFiles = Directory.GetFiles(folderPath, "*.png");
+ foreach (string imageFile in imageFiles)
{
- string filePath = files[i];
-
- // Ensure the file still exists (it could have been removed after the initial listing).
- if (!File.Exists(filePath))
+ // Verify that the file still exists before attempting to read it
+ if (!File.Exists(imageFile))
{
- Console.WriteLine($"File not found: {filePath}");
+ Console.WriteLine($"File not found: {imageFile}");
continue;
}
- // Create a BarCodeReader for the current image file.
- using (BarCodeReader reader = new BarCodeReader(filePath))
+ // ----------------------------------------------------------------
+ // Create a BarCodeReader for the current image and decode all supported types
+ // ----------------------------------------------------------------
+ using (var reader = new BarCodeReader(imageFile, DecodeType.AllSupportedTypes))
{
- // Read all barcodes detected in the image.
+ // Iterate through all detected barcodes in the image
foreach (var result in reader.ReadBarCodes())
{
- // Output file name, barcode type, and decoded text.
- Console.WriteLine($"File: {Path.GetFileName(filePath)} | Type: {result.CodeTypeName} | Text: {result.CodeText}");
+ Console.WriteLine($"File: {Path.GetFileName(imageFile)} | Type: {result.CodeTypeName} | Text: {result.CodeText}");
}
}
}
diff --git a/barcode-recognition-basics/process-folder-of-code-39-images-using-barcodereader-with-checksumvalidationon-to-validate-optional-checksums.cs b/barcode-recognition-basics/process-folder-of-code-39-images-using-barcodereader-with-checksumvalidationon-to-validate-optional-checksums.cs
index 6746a40..587e00e 100644
--- a/barcode-recognition-basics/process-folder-of-code-39-images-using-barcodereader-with-checksumvalidationon-to-validate-optional-checksums.cs
+++ b/barcode-recognition-basics/process-folder-of-code-39-images-using-barcodereader-with-checksumvalidationon-to-validate-optional-checksums.cs
@@ -1,64 +1,77 @@
-// Title: Process Code 39 images with checksum validation
-// Description: Demonstrates reading Code 39 barcodes from a folder of images, enabling optional checksum validation to ensure data integrity.
+// Title: Validate Code 39 barcodes with optional checksum using BarCodeReader
+// Description: Demonstrates generating Code 39 barcode images, some with checksum enabled, and then reading them back while validating optional checksums.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator for creating Code 39 images and BarCodeReader with ChecksumValidation.On to verify optional checksums. Developers often need to batch‑process barcode images, ensure data integrity, and handle checksum validation in scanning workflows.
// Prompt: Process a folder of Code 39 images using BarCodeReader with ChecksumValidation.On to validate optional checksums.
-// Tags: code39, barcode, checksumvalidation, barcodereader, imageprocessing
+// Tags: code39, checksum validation, barcode generation, barcode recognition, aspose.barcode
using System;
using System.IO;
-using System.Linq;
+using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates processing a folder of Code 39 barcode images with checksum validation.
+/// Example program that generates Code 39 barcode images (including one with checksum enabled)
+/// and then reads all images in a folder while validating optional checksums.
///
class Program
{
///
- /// Entry point. Reads barcode images from a specified folder (or default) and prints decoded values.
+ /// Entry point. Generates sample barcodes, saves them to a folder, and processes the folder
+ /// using BarCodeReader with checksum validation turned on.
///
- /// Optional command‑line argument specifying the folder path.
- static void Main(string[] args)
+ static void Main()
{
- // Determine the folder containing Code 39 barcode images.
- // Use the first command‑line argument if provided; otherwise default to "Code39Images".
- string folderPath = args.Length > 0 ? args[0] : "Code39Images";
+ // --------------------------------------------------------------------
+ // Create a folder for sample barcode images
+ // --------------------------------------------------------------------
+ string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ Directory.CreateDirectory(folderPath);
- // Verify that the folder exists before proceeding.
- if (!Directory.Exists(folderPath))
- {
- Console.WriteLine($"Folder not found: {folderPath}");
- return;
- }
-
- // Retrieve image files (common bitmap extensions) from the folder.
- string[] imageFiles = Directory.GetFiles(folderPath, "*.*")
- .Where(f => f.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
- f.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) ||
- f.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase) ||
- f.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase))
- .ToArray();
+ // Sample Code39 texts (one with checksum enabled)
+ string[] sampleTexts = { "CODE39", "CODE39CHK", "123ABC" };
- // If no image files are found, inform the user and exit.
- if (imageFiles.Length == 0)
+ // --------------------------------------------------------------------
+ // Generate sample barcode images
+ // --------------------------------------------------------------------
+ foreach (string text in sampleTexts)
{
- Console.WriteLine($"No image files found in folder: {folderPath}");
- return;
+ string imagePath = Path.Combine(folderPath, $"{text}.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code39, text))
+ {
+ // Enable checksum for the second sample (CODE39CHK)
+ if (text == "CODE39CHK")
+ {
+ generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes;
+ }
+
+ // Save the generated barcode image to disk
+ generator.Save(imagePath);
+ Console.WriteLine($"Generated barcode: {imagePath}");
+ }
}
- // Process each image file individually.
- foreach (string imagePath in imageFiles)
+ // --------------------------------------------------------------------
+ // Process all PNG images in the folder using BarCodeReader with checksum validation
+ // --------------------------------------------------------------------
+ string[] imageFiles = Directory.GetFiles(folderPath, "*.png");
+ foreach (string file in imageFiles)
{
- // Initialize BarCodeReader for Code 39 decoding.
- using (var reader = new BarCodeReader(imagePath, DecodeType.Code39))
+ if (!File.Exists(file))
+ {
+ Console.WriteLine($"File not found: {file}");
+ continue;
+ }
+
+ using (var reader = new BarCodeReader(file, DecodeType.Code39))
{
- // Enable checksum validation for optional Code 39 checksums.
+ // Turn on validation of optional checksums
reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
- // Read all barcodes present in the current image.
+ // Read and output each detected barcode
foreach (var result in reader.ReadBarCodes())
{
- // Output the file name, barcode type, and decoded text to the console.
- Console.WriteLine($"File: {Path.GetFileName(imagePath)} | Type: {result.CodeTypeName} | Text: {result.CodeText}");
+ Console.WriteLine($"File: {Path.GetFileName(file)} - Detected CodeText: {result.CodeText}");
}
}
}
diff --git a/barcode-recognition-basics/provide-network-stream-to-setbarcodeimage-for-reading-barcodes-from-remote-image-data-without-saving-locally.cs b/barcode-recognition-basics/provide-network-stream-to-setbarcodeimage-for-reading-barcodes-from-remote-image-data-without-saving-locally.cs
index 9d6331c..d51aff4 100644
--- a/barcode-recognition-basics/provide-network-stream-to-setbarcodeimage-for-reading-barcodes-from-remote-image-data-without-saving-locally.cs
+++ b/barcode-recognition-basics/provide-network-stream-to-setbarcodeimage-for-reading-barcodes-from-remote-image-data-without-saving-locally.cs
@@ -1,65 +1,59 @@
// Title: Read Barcode from Remote Image via Network Stream
-// Description: Demonstrates using Aspose.BarCode to read barcodes directly from a network stream without saving the image locally.
+// Description: Demonstrates downloading a barcode image from a URL and decoding it directly from the network stream without saving to disk.
+// Category-Description: This example belongs to the Aspose.BarCode recognition category, showcasing how to use the BarCodeReader class to extract barcode data from images obtained over HTTP. Typical use cases include processing barcodes from web services, cloud storage, or any remote source where persisting the image locally is undesirable. Developers often need to stream image data directly into the reader to improve performance and reduce I/O overhead.
// Prompt: Provide a network stream to SetBarCodeImage for reading barcodes from remote image data without saving locally.
-// Tags: barcode, read, network stream, aspose, c#
+// Tags: barcode symbology, read, console, barcodereader, httpclient
using System;
using System.IO;
using System.Net.Http;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.BarCode.Generation;
///
-/// Example program that downloads a barcode image from a remote URL and reads barcodes using a network stream.
+/// Example program that downloads a barcode image from a remote URL and reads all supported barcode types directly from the network stream.
///
class Program
{
///
- /// Entry point of the application. Downloads an image, sets it as the source for BarCodeReader, and outputs detected barcodes.
+ /// Entry point of the application. Performs HTTP download, streams the image to BarCodeReader, and prints detected barcode information.
///
static void Main()
{
- // Remote image URL containing a barcode
+ // URL of the remote barcode image. Replace with a valid image URL.
const string imageUrl = "https://example.com/barcode.png";
- // Create an HttpClient to download the image as a stream without writing to disk
+ // Create an HttpClient instance for downloading the image.
using (var httpClient = new HttpClient())
{
try
{
- // Retrieve the image data as a stream (synchronous wait for simplicity)
- using (Stream imageStream = httpClient.GetStreamAsync(imageUrl).Result)
+ // Synchronously send GET request to the image URL.
+ using (var response = httpClient.GetAsync(imageUrl).Result)
{
- // Initialize the barcode reader
- using (var reader = new BarCodeReader())
- {
- // Configure the reader to detect all supported barcode types
- reader.SetBarCodeReadType(DecodeType.AllSupportedTypes);
-
- // Assign the network stream as the image source for barcode detection
- reader.SetBarCodeImage(imageStream);
-
- // Process up to 5 detected barcodes and output their type and text
- int processed = 0;
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"Detected Type: {result.CodeTypeName}, Text: {result.CodeText}");
- processed++;
- if (processed >= 5) break;
- }
+ // Throw if the HTTP response indicates failure.
+ response.EnsureSuccessStatusCode();
- // Inform the user if no barcodes were found
- if (processed == 0)
+ // Retrieve the response content as a stream.
+ using (var imageStream = response.Content.ReadAsStreamAsync().Result)
+ {
+ // Initialize BarCodeReader with the image stream, decoding all supported barcode types.
+ using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes))
{
- Console.WriteLine("No barcodes were detected in the image.");
+ // Iterate through each detected barcode and output its type and text.
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Barcode Type: {result.CodeTypeName}");
+ Console.WriteLine($"Barcode Text: {result.CodeText}");
+ Console.WriteLine();
+ }
}
}
}
}
catch (Exception ex)
{
- // Handle any errors that occur during download or processing
- Console.WriteLine($"Error retrieving or processing the image: {ex.Message}");
+ // Output any errors that occur during download or barcode recognition.
+ Console.WriteLine($"Error: {ex.Message}");
}
}
}
diff --git a/barcode-recognition-basics/read-barcodes-from-jpeg-file-using-barcodereader-constructor-and-retrieve-detection-results.cs b/barcode-recognition-basics/read-barcodes-from-jpeg-file-using-barcodereader-constructor-and-retrieve-detection-results.cs
index df14c10..d8a88ed 100644
--- a/barcode-recognition-basics/read-barcodes-from-jpeg-file-using-barcodereader-constructor-and-retrieve-detection-results.cs
+++ b/barcode-recognition-basics/read-barcodes-from-jpeg-file-using-barcodereader-constructor-and-retrieve-detection-results.cs
@@ -1,49 +1,63 @@
-// Title: Read Barcodes from JPEG using BarCodeReader
-// Description: Demonstrates how to load a JPEG image, detect all supported barcodes, and output their type, text, and location.
+// Title: Read barcodes from JPEG using BarCodeReader
+// Description: Demonstrates how to load a JPEG image, generate a sample barcode if missing, and read all supported barcode types using Aspose.BarCode's BarCodeReader.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing the BarCodeReader class for detecting and extracting barcode data from image files. Typical use cases include inventory scanning, document processing, and automated data capture where developers need to read multiple symbologies from various image formats. The snippet illustrates initializing the reader, iterating over detection results, and accessing barcode type, text, and region information.
// Prompt: Read barcodes from a JPEG file using BarCodeReader constructor and retrieve detection results.
-// Tags: barcode, read, jpeg, aspose, barcodereader, detection, console
+// Tags: barcode, jpeg, read, detection, aspnet, aspnetcore, aspose.barcode, barcodereader, decode, allsupportedtypes
using System;
using System.IO;
+using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that reads all supported barcodes from a JPEG image
-/// and prints their type, decoded text, and bounding region to the console.
+/// Example program that reads barcodes from a JPEG image using Aspose.BarCode's .
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point. Accepts an optional image path argument, generates a sample barcode if the file is missing,
+ /// and prints detection results for all supported barcode types.
///
- static void Main()
+ /// Command‑line arguments; first argument can be a custom image path.
+ static void Main(string[] args)
{
- // Path to the JPEG image containing barcodes.
- const string imagePath = "sample.jpg";
+ // Determine the image file to process: use the first argument if supplied, otherwise default to "sample.jpg".
+ string imagePath = args.Length > 0 ? args[0] : "sample.jpg";
- // Verify that the file exists before attempting to read it.
+ // If the specified file does not exist, create a simple Code128 barcode image for demonstration purposes.
+ if (!File.Exists(imagePath))
+ {
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ {
+ generator.Save(imagePath, BarCodeImageFormat.Jpeg);
+ }
+ Console.WriteLine($"Generated sample barcode image at '{imagePath}'.");
+ }
+
+ // Double‑check that the file now exists before attempting to read it.
if (!File.Exists(imagePath))
{
Console.WriteLine($"File not found: {imagePath}");
return;
}
- // Initialize the BarCodeReader for all supported barcode types.
- // The using statement ensures the reader is disposed properly.
+ // Initialize the reader to scan the image for all supported barcode symbologies.
using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
- // Iterate through all detected barcodes in the image.
+ // Optional: configure quality settings (default is NormalQuality).
+ // reader.QualitySettings = QualitySettings.NormalQuality;
+
+ // Iterate through each detected barcode and output its details.
foreach (var result in reader.ReadBarCodes())
{
- // Output the barcode type (symbology) and the decoded text.
Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
Console.WriteLine($"BarCode Text: {result.CodeText}");
- // Retrieve and display the bounding rectangle of the detected barcode.
- var rect = result.Region.Rectangle;
- Console.WriteLine($"Region - X:{rect.X}, Y:{rect.Y}, Width:{rect.Width}, Height:{rect.Height}");
-
- Console.WriteLine(); // Blank line for readability between results.
+ // Retrieve and display the bounding rectangle of the detected barcode region.
+ var bounds = result.Region.Rectangle;
+ Console.WriteLine($"Region - X:{bounds.X}, Y:{bounds.Y}, Width:{bounds.Width}, Height:{bounds.Height}");
+ Console.WriteLine();
}
}
}
diff --git a/barcode-recognition-basics/read-barcodes-from-memorystream-containing-image-bytes-and-verify-checksum-validation-matches-file-based-reads.cs b/barcode-recognition-basics/read-barcodes-from-memorystream-containing-image-bytes-and-verify-checksum-validation-matches-file-based-reads.cs
index 2d697cb..4047621 100644
--- a/barcode-recognition-basics/read-barcodes-from-memorystream-containing-image-bytes-and-verify-checksum-validation-matches-file-based-reads.cs
+++ b/barcode-recognition-basics/read-barcodes-from-memorystream-containing-image-bytes-and-verify-checksum-validation-matches-file-based-reads.cs
@@ -1,78 +1,85 @@
-// Title: Read and compare EAN13 barcode checksum from file and MemoryStream
-// Description: Demonstrates generating an EAN13 barcode, saving it to a file and a MemoryStream, then reading both sources with checksum validation to ensure they match.
+// Title: Read barcode from MemoryStream and verify checksum against file read
+// Description: Demonstrates generating an EAN‑13 barcode, saving it to a file and a MemoryStream, then reading both sources with checksum validation to ensure they match.
+// 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, covering typical scenarios such as saving to different storage mediums, using MemoryStream for in‑memory processing, and enabling checksum validation. Developers often need these patterns when integrating barcode handling into web services, batch processors, or desktop applications.
// Prompt: Read barcodes from a MemoryStream containing image bytes and verify checksum validation matches file‑based reads.
-// Tags: ean13, checksum, memorystream, file, barcode, generation, recognition, aspose
+// Tags: ean13, checksum, barcode, generation, recognition, memorystream, file, aspose.barcode, aspnet, csharp
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Demonstrates barcode generation, saving, and checksum validation using Aspose.BarCode.
+/// Example program that generates an EAN‑13 barcode, saves it to both a file and a MemoryStream,
+/// then reads the barcode from each source with checksum validation enabled to compare results.
///
class Program
{
///
- /// Entry point. Generates an EAN13 barcode, saves it to a file and MemoryStream, then reads both with checksum validation and compares results.
+ /// Entry point of the example. Executes barcode generation, storage, and verification steps.
///
static void Main()
{
- // Sample EAN13 barcode with a valid checksum
- const string codeText = "1234567890128";
- const string filePath = "barcode.png";
+ // Define the barcode data (EAN‑13 with checksum digit)
+ string ean13Code = "1234567890128";
- // Generate the barcode image and save it to a file and a memory stream
- using (var generator = new BarcodeGenerator(EncodeTypes.EAN13, codeText))
+ // Determine the output file path in the current working directory
+ string outputFile = Path.Combine(Directory.GetCurrentDirectory(), "barcode.png");
+
+ // Create a barcode generator for the specified symbology and data
+ using (var generator = new BarcodeGenerator(EncodeTypes.EAN13, ean13Code))
{
- // Save the generated barcode to a PNG file
- generator.Save(filePath, BarCodeImageFormat.Png);
+ // Save the generated barcode image to a physical file (PNG format)
+ generator.Save(outputFile, BarCodeImageFormat.Png);
- // Save the generated barcode to a MemoryStream
+ // Also save the barcode image to an in‑memory stream for later reading
using (var memoryStream = new MemoryStream())
{
generator.Save(memoryStream, BarCodeImageFormat.Png);
- memoryStream.Position = 0; // Reset stream position for reading
+ memoryStream.Position = 0; // Reset stream position to the beginning for reading
- // Read barcode from file with checksum validation enabled
- using (var fileReader = new BarCodeReader(filePath, DecodeType.EAN13))
+ // -------------------- Read from file --------------------
+ using (var readerFile = new BarCodeReader(outputFile, DecodeType.EAN13))
{
- fileReader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
- BarCodeResult fileResult = GetFirstResult(fileReader);
+ // Enable checksum validation for the file‑based read
+ readerFile.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
+ var resultsFile = readerFile.ReadBarCodes();
- // Read barcode from memory stream with the same checksum setting
- using (var streamReader = new BarCodeReader(memoryStream, DecodeType.EAN13))
+ // -------------------- Read from MemoryStream --------------------
+ using (var readerStream = new BarCodeReader(memoryStream, DecodeType.EAN13))
{
- streamReader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
- BarCodeResult streamResult = GetFirstResult(streamReader);
+ // Enable checksum validation for the stream‑based read
+ readerStream.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
+ var resultsStream = readerStream.ReadBarCodes();
- // Verify that both reads produce identical code text and checksum
- bool match = fileResult != null && streamResult != null &&
- fileResult.CodeText == streamResult.CodeText &&
- fileResult.Extended.OneD.CheckSum == streamResult.Extended.OneD.CheckSum;
+ // Assume a single barcode result for each reader
+ var resultFile = resultsFile.Length > 0 ? resultsFile[0] : null;
+ var resultStream = resultsStream.Length > 0 ? resultsStream[0] : null;
- Console.WriteLine($"Checksum validation match: {match}");
- if (fileResult != null)
- {
- Console.WriteLine($"File read - CodeText: {fileResult.CodeText}, CheckSum: {fileResult.Extended.OneD.CheckSum}");
- }
- if (streamResult != null)
+ // Validate that both reads succeeded
+ if (resultFile == null || resultStream == null)
{
- Console.WriteLine($"MemoryStream read - CodeText: {streamResult.CodeText}, CheckSum: {streamResult.Extended.OneD.CheckSum}");
+ Console.WriteLine("Failed to read barcode from one of the sources.");
+ return;
}
+
+ // Output the decoded values and checksum information
+ Console.WriteLine("File Read - CodeText: " + resultFile.CodeText);
+ Console.WriteLine("File Read - CheckSum: " + resultFile.Extended.OneD.CheckSum);
+ Console.WriteLine("Stream Read - CodeText: " + resultStream.CodeText);
+ Console.WriteLine("Stream Read - CheckSum: " + resultStream.Extended.OneD.CheckSum);
+
+ // Compare checksum and code text between the two sources
+ bool checksumMatches = resultFile.Extended.OneD.CheckSum == resultStream.Extended.OneD.CheckSum;
+ bool codeTextMatches = string.Equals(resultFile.CodeText, resultStream.CodeText, StringComparison.Ordinal);
+
+ Console.WriteLine("Checksum match: " + (checksumMatches ? "Yes" : "No"));
+ Console.WriteLine("CodeText match: " + (codeTextMatches ? "Yes" : "No"));
}
}
}
}
}
-
- // Helper to obtain the first detected barcode result
- private static BarCodeResult GetFirstResult(BarCodeReader reader)
- {
- foreach (var result in reader.ReadBarCodes())
- {
- return result;
- }
- return null;
- }
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/read-barcodes-from-pdf-pages-by-extracting-each-page-as-image-and-feeding-it-to-barcodereader.cs b/barcode-recognition-basics/read-barcodes-from-pdf-pages-by-extracting-each-page-as-image-and-feeding-it-to-barcodereader.cs
index 24f0725..a3e575c 100644
--- a/barcode-recognition-basics/read-barcodes-from-pdf-pages-by-extracting-each-page-as-image-and-feeding-it-to-barcodereader.cs
+++ b/barcode-recognition-basics/read-barcodes-from-pdf-pages-by-extracting-each-page-as-image-and-feeding-it-to-barcodereader.cs
@@ -1,77 +1,69 @@
-// Title: Read barcodes from PDF pages using Aspose
-// Description: Demonstrates extracting each PDF page as an image and scanning it for barcodes with BarCodeReader.
+// Title: Read barcodes from PDF pages by converting each page to an image
+// Description: Demonstrates extracting each page of a PDF as an image and using Aspose.BarCode's BarCodeReader to detect all supported barcode types.
+// Category-Description: This example belongs to the Aspose.BarCode PDF processing category, illustrating how to combine Aspose.Pdf and Aspose.BarCode APIs. It shows how to render PDF pages to images, enable barcode optimization, and read barcodes using BarCodeReader. Developers often need to scan documents for embedded barcodes, automate data capture, or validate printed codes in PDFs.
// Prompt: Read barcodes from PDF pages by extracting each page as an image and feeding it to BarCodeReader.
-// Tags: barcode, pdf, image extraction, aspose.pdf, aspose.barcode, csharp
+// Tags: pdf, barcode, extraction, image, aspose.pdf, aspose.barcode, decode, allsupportedtypes
using System;
using System.IO;
using Aspose.Pdf;
-using Aspose.Pdf.Devices;
+using Aspose.Pdf.Facades;
+using Aspose.BarCode;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
///
-/// Sample program that reads barcodes from each page of a PDF file.
+/// Demonstrates reading barcodes from each page of a PDF by converting pages to images and using BarCodeReader.
///
class Program
{
///
- /// Entry point. Loads a PDF, converts each page to an image, and scans for barcodes.
+ /// Entry point. Processes the PDF, extracts pages as images, and prints detected barcode information.
///
static void Main()
{
- // Path to the PDF file (adjust as needed)
- string pdfPath = "sample.pdf";
+ // Path to the PDF file to be processed.
+ const string pdfPath = "sample.pdf";
- // Verify that the PDF file exists
+ // Verify that the PDF file exists before attempting to read it.
if (!File.Exists(pdfPath))
{
- Console.WriteLine($"PDF file not found: {pdfPath}");
+ Console.WriteLine($"File not found: {pdfPath}");
+ Console.WriteLine("Please provide a PDF containing barcodes and place it in the executable directory.");
return;
}
- // Load the PDF document
+ // Open the PDF document.
using (var pdfDocument = new Document(pdfPath))
{
- int pageCount = pdfDocument.Pages.Count;
- Console.WriteLine($"Processing {pageCount} page(s) from '{pdfPath}'.");
-
- // Iterate through each page
- for (int pageIndex = 1; pageIndex <= pageCount; pageIndex++)
+ // Initialize the PDF converter.
+ using (var pdfConverter = new PdfConverter(pdfDocument))
{
- var page = pdfDocument.Pages[pageIndex];
+ // Enable barcode optimization for better extraction.
+ pdfConverter.RenderingOptions.BarcodeOptimization = true;
- // Convert the page to a JPEG image stored in a memory stream
- using (var imageStream = new MemoryStream())
+ // Process each page individually.
+ for (int pageNumber = 1; pageNumber <= pdfDocument.Pages.Count; pageNumber++)
{
- var resolution = new Resolution(300);
- var jpegDevice = new JpegDevice(resolution);
- jpegDevice.Process(page, imageStream);
- imageStream.Position = 0; // Reset stream position for reading
+ // Configure the converter to render only the current page.
+ pdfConverter.StartPage = pageNumber;
+ pdfConverter.EndPage = pageNumber;
- // Load the image into an Aspose.Drawing.Bitmap
- using (var bitmap = new Bitmap(imageStream))
- {
- // Initialize the barcode reader for all supported symbologies
- using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
- {
- // Use a standard quality preset
- reader.QualitySettings = QualitySettings.NormalQuality;
+ // Perform the conversion.
+ pdfConverter.DoConvert();
- // Perform barcode detection
- var results = reader.ReadBarCodes();
+ // Retrieve the rendered page as an image stream.
+ using (var imageStream = new MemoryStream())
+ {
+ pdfConverter.GetNextImage(imageStream);
+ imageStream.Position = 0; // Reset stream for reading.
- if (results.Length == 0)
- {
- Console.WriteLine($"Page {pageIndex}: No barcodes detected.");
- }
- else
+ // Create a barcode reader for the image stream.
+ using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes))
+ {
+ // Iterate through all detected barcodes on this page.
+ foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"Page {pageIndex}: Detected {results.Length} barcode(s).");
- foreach (var result in results)
- {
- Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}");
- }
+ Console.WriteLine($"Page {pageNumber}: Type = {result.CodeTypeName}, Text = {result.CodeText}");
}
}
}
diff --git a/barcode-recognition-basics/read-foundcount-property-to-verify-total-number-of-barcodes-detected-in-source-image.cs b/barcode-recognition-basics/read-foundcount-property-to-verify-total-number-of-barcodes-detected-in-source-image.cs
index 5832b1e..421ebc3 100644
--- a/barcode-recognition-basics/read-foundcount-property-to-verify-total-number-of-barcodes-detected-in-source-image.cs
+++ b/barcode-recognition-basics/read-foundcount-property-to-verify-total-number-of-barcodes-detected-in-source-image.cs
@@ -1,47 +1,52 @@
-// Title: Read FoundCount Property to Verify Detected Barcodes
-// Description: Demonstrates how to use Aspose.BarCode to read an image, detect all supported barcodes, and retrieve the total count via the FoundCount property.
+// Title: Detect and count barcodes in an image using Aspose.BarCode
+// Description: Demonstrates how to generate a barcode image if missing, read it, and use the FoundCount property to report the total number of detected barcodes.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing the BarCodeReader class for detecting multiple barcode symbologies in an image. Typical use cases include inventory scanning, document processing, and quality control where developers need to verify the presence and count of barcodes. The snippet illustrates generating a sample barcode, reading all supported types, and accessing the FoundCount property.
// Prompt: Read the FoundCount property to verify the total number of barcodes detected in the source image.
-// Tags: barcode, detection, foundcount, aspose.barcode, csharp
+// Tags: barcode detection, foundcount, barcodereader, code128, png, aspnet.barcode
using System;
using System.IO;
+using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that reads an image, detects all supported barcodes,
-/// and reports the total number of barcodes found using the FoundCount property.
+/// Demonstrates barcode generation, detection, and counting using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point. Generates a sample barcode if needed, reads the image, and prints the total count of detected barcodes.
///
static void Main()
{
- // Path to the image containing barcodes
- string imagePath = "sample.png";
+ // Path for the sample barcode image
+ const string imagePath = "sample.png";
- // Verify that the image file exists before attempting to read it
+ // Generate a sample barcode image if it does not exist
if (!File.Exists(imagePath))
{
- Console.WriteLine($"File not found: {imagePath}");
- return;
+ // Create a generator for Code128 symbology with sample text "123456"
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ {
+ // Save the generated barcode as a PNG file
+ generator.Save(imagePath, BarCodeImageFormat.Png);
+ }
}
- // Initialize the barcode reader for all supported symbologies
+ // Initialize a reader that will detect all supported barcode types in the image
using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
- // Perform barcode detection on the image
- reader.ReadBarCodes();
+ // Perform the recognition and retrieve all detected barcode results
+ var results = reader.ReadBarCodes();
- // Retrieve the total number of detected barcodes via the FoundCount property
- int totalBarcodes = reader.FoundCount;
- Console.WriteLine($"Total barcodes detected: {totalBarcodes}");
+ // Output the total number of detected barcodes using the FoundCount property
+ Console.WriteLine($"Total barcodes detected: {reader.FoundCount}");
- // Optionally, output each detected barcode's text value
- for (int i = 0; i < totalBarcodes; i++)
+ // List each detected barcode's type and decoded text
+ foreach (var result in results)
{
- Console.WriteLine($"Barcode {i + 1}: {reader.FoundBarCodes[i].CodeText}");
+ Console.WriteLine($"Type: {result.CodeTypeName}, Text: {result.CodeText}");
}
}
}
diff --git a/barcode-recognition-basics/read-single-code-11-barcode-image-after-enabling-obligatory-checksum-verification-with-checksumvalidationon.cs b/barcode-recognition-basics/read-single-code-11-barcode-image-after-enabling-obligatory-checksum-verification-with-checksumvalidationon.cs
index 4a179d4..4aa8ba2 100644
--- a/barcode-recognition-basics/read-single-code-11-barcode-image-after-enabling-obligatory-checksum-verification-with-checksumvalidationon.cs
+++ b/barcode-recognition-basics/read-single-code-11-barcode-image-after-enabling-obligatory-checksum-verification-with-checksumvalidationon.cs
@@ -1,7 +1,8 @@
// Title: Read Code 11 barcode with checksum validation
// Description: Demonstrates reading a Code 11 barcode image while enforcing checksum verification using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition and generation category. It showcases the use of BarcodeGenerator to create a Code 11 image and BarCodeReader with BarcodeSettings to validate mandatory checksums. Developers commonly need to generate barcodes for testing and then read them with strict checksum enforcement to ensure data integrity in logistics, inventory, and manufacturing systems.
// Prompt: Read a single Code 11 barcode image after enabling obligatory checksum verification with ChecksumValidation.On.
-// Tags: code11, read, checksum, console, barcodereader, aspose.barcode
+// Tags: code11, barcode, read, checksum, aspose.barcode, generation, recognition
using System;
using System.IO;
@@ -11,57 +12,54 @@
///
/// Example program that generates (if needed) and reads a Code 11 barcode image
-/// with checksum validation enabled.
+/// with mandatory checksum validation enabled.
///
class Program
{
///
- /// Entry point. Generates a barcode image if missing, then reads it with checksum verification.
+ /// Entry point. Generates a Code 11 barcode image if missing, then reads it
+ /// while enforcing checksum verification.
///
static void Main()
{
- // Define the path for the sample barcode image
- const string imagePath = "code11.png";
+ // Path to the barcode image file
+ string imagePath = "code11.png";
- // ------------------------------------------------------------
// Generate a Code 11 barcode image if it does not already exist
- // ------------------------------------------------------------
if (!File.Exists(imagePath))
{
- // Create a barcode generator for Code 11 with sample data
using (var generator = new BarcodeGenerator(EncodeTypes.Code11, "1234567890"))
{
- // Save the generated barcode to the specified file
+ // Save the generated barcode to a PNG file
generator.Save(imagePath);
+ Console.WriteLine($"Generated barcode image: {imagePath}");
}
}
- // ------------------------------------------------------------
- // Verify that the image now exists before attempting to read it
- // ------------------------------------------------------------
+ // Ensure the image file exists before attempting to read it
if (!File.Exists(imagePath))
{
- Console.WriteLine("Failed to create barcode image.");
+ Console.WriteLine($"Error: Barcode image file not found at '{imagePath}'.");
return;
}
- // ------------------------------------------------------------
- // Read the barcode with checksum validation enabled
- // ------------------------------------------------------------
+ // Create a BarCodeReader for Code 11 with checksum validation enabled
using (var reader = new BarCodeReader(imagePath, DecodeType.Code11))
{
// Enable obligatory checksum verification
reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
- // Iterate through all detected barcodes (should be only one)
+ // Iterate through all detected barcodes in the image
foreach (var result in reader.ReadBarCodes())
{
- // Output the raw decoded text
- Console.WriteLine($"CodeText: {result.CodeText}");
+ Console.WriteLine("Detected Code 11 barcode:");
+ Console.WriteLine($" CodeText: {result.CodeText}");
- // Output checksum and value without checksum (OneD extended info)
- Console.WriteLine($"Checksum: {result.Extended.OneD.CheckSum}");
- Console.WriteLine($"Value (without checksum): {result.Extended.OneD.Value}");
+ // If extended OneD data is available, display the checksum value
+ if (result.Extended?.OneD != null)
+ {
+ Console.WriteLine($" CheckSum: {result.Extended.OneD.CheckSum}");
+ }
}
}
}
diff --git a/barcode-recognition-basics/replace-current-bitmap-source-using-setbarcodeimage-to-process-different-in-memory-image.cs b/barcode-recognition-basics/replace-current-bitmap-source-using-setbarcodeimage-to-process-different-in-memory-image.cs
index 76a07bb..8396307 100644
--- a/barcode-recognition-basics/replace-current-bitmap-source-using-setbarcodeimage-to-process-different-in-memory-image.cs
+++ b/barcode-recognition-basics/replace-current-bitmap-source-using-setbarcodeimage-to-process-different-in-memory-image.cs
@@ -1,69 +1,70 @@
-// Title: Demonstrate SetBarCodeImage to replace barcode source
-// Description: Shows how to generate two barcode images in memory, read the first, then replace the reader's image with a second barcode using SetBarCodeImage.
+// Title: Replace barcode image source using SetBarCodeImage
+// Description: Demonstrates how to replace the image source of a BarCodeReader with a different in‑memory bitmap.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator to create a barcode, BarCodeReader to decode it, and the SetBarCodeImage method to swap the source image at runtime. Developers working with dynamic image streams, in‑memory processing, or custom image pipelines commonly need these APIs to read barcodes without persisting intermediate files.
// Prompt: Replace the current bitmap source using SetBarCodeImage to process a different in‑memory image.
-// Tags: barcode, setbarcodeimage, in-memory, code128, aspose.barcode
+// Tags: barcode, setbarcodeimage, in-memory image, code128, generation, recognition, 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 demonstrates replacing the bitmap source of a
-/// with a different in‑memory image using SetBarCodeImage.
+/// Example program that generates a Code128 barcode, reads it, then replaces the
+/// source image with a new in‑memory bitmap using SetBarCodeImage.
///
class Program
{
///
- /// Entry point. Generates two Code128 barcodes in memory, reads the first,
- /// then swaps the reader's image to the second barcode and reads again.
+ /// Entry point of the example. Generates a barcode, reads it, swaps the image,
+ /// and attempts to read again.
///
static void Main()
{
- // Generate the first barcode image (Code128) and keep it in a memory stream
- using (var generator1 = new BarcodeGenerator(EncodeTypes.Code128, "First123"))
+ // Generate a simple Code128 barcode and keep it in memory
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC"))
{
- using (var stream1 = new MemoryStream())
+ using (Bitmap originalBitmap = generator.GenerateBarCodeImage())
{
- generator1.Save(stream1, BarCodeImageFormat.Png);
- stream1.Position = 0; // Reset stream position for reading
+ // Save the original image to a file (optional, just for visual verification)
+ const string originalPath = "original.png";
+ originalBitmap.Save(originalPath, ImageFormat.Png);
+ Console.WriteLine($"Original barcode saved to {originalPath}");
- // Load the first image into a Bitmap object
- using (var bitmap1 = new Bitmap(stream1))
+ // Create a BarCodeReader using the generated bitmap
+ using (var reader = new BarCodeReader(originalBitmap, DecodeType.Code128))
{
- // Create a reader for the first bitmap, configured for Code128 decoding
- using (var reader = new BarCodeReader(bitmap1, DecodeType.Code128))
+ // Read and display the first detected barcode from the original image
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
- Console.WriteLine("Reading first barcode:");
- foreach (BarCodeResult result in reader.ReadBarCodes())
+ Console.WriteLine($"Detected barcode (original image): Type={result.CodeTypeName}, Text={result.CodeText}");
+ }
+
+ // Create a different in‑memory image (blank white bitmap)
+ using (Bitmap newBitmap = new Bitmap(200, 100, PixelFormat.Format32bppArgb))
+ {
+ using (Graphics graphics = Graphics.FromImage(newBitmap))
{
- Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}");
+ // Fill the bitmap with white background
+ graphics.Clear(Color.White);
}
- // Generate the second barcode image (Code128) in a new memory stream
- using (var generator2 = new BarcodeGenerator(EncodeTypes.Code128, "Second456"))
- {
- using (var stream2 = new MemoryStream())
- {
- generator2.Save(stream2, BarCodeImageFormat.Png);
- stream2.Position = 0; // Reset stream position for reading
+ // Replace the bitmap source of the reader with the new image
+ reader.SetBarCodeImage(newBitmap);
- // Load the second image into a Bitmap object
- using (var bitmap2 = new Bitmap(stream2))
- {
- // Replace the bitmap source of the existing reader with the second image
- reader.SetBarCodeImage(bitmap2);
+ // Attempt to read barcodes from the new image
+ bool anyFound = false;
+ foreach (BarCodeResult result in reader.ReadBarCodes())
+ {
+ anyFound = true;
+ Console.WriteLine($"Detected barcode (new image): Type={result.CodeTypeName}, Text={result.CodeText}");
+ }
- Console.WriteLine("Reading after replacing bitmap source:");
- foreach (BarCodeResult result in reader.ReadBarCodes())
- {
- Console.WriteLine($" Type: {result.CodeTypeName}, Text: {result.CodeText}");
- }
- }
- }
+ if (!anyFound)
+ {
+ Console.WriteLine("No barcode detected in the new image after SetBarCodeImage.");
}
}
}
diff --git a/barcode-recognition-basics/retrieve-barcoderesultconfidence-after-reading-qr-code-and-log-enumeration-to-diagnostics-file.cs b/barcode-recognition-basics/retrieve-barcoderesultconfidence-after-reading-qr-code-and-log-enumeration-to-diagnostics-file.cs
index b7b976c..461070a 100644
--- a/barcode-recognition-basics/retrieve-barcoderesultconfidence-after-reading-qr-code-and-log-enumeration-to-diagnostics-file.cs
+++ b/barcode-recognition-basics/retrieve-barcoderesultconfidence-after-reading-qr-code-and-log-enumeration-to-diagnostics-file.cs
@@ -1,7 +1,8 @@
-// Title: QR Code Generation, Reading, and Confidence Logging
-// Description: Generates a QR code image, reads it back, extracts the confidence level, and writes the value to a diagnostics file.
+// Title: Retrieve QR Code Confidence and Log to Diagnostics File
+// Description: Demonstrates generating a QR code, reading it, extracting the BarCodeResult.Confidence enumeration, and writing the value to a diagnostics log.
+// Category-Description: This example belongs to the Aspose.BarCode reading and generation category, showcasing how to use BarcodeGenerator, BarCodeReader, and BarCodeResult classes. Typical use cases include validating barcode quality, logging confidence levels for diagnostics, and integrating barcode verification into automated workflows. Developers often need to capture confidence metrics to assess scan reliability and troubleshoot scanning issues.
// Prompt: Retrieve BarCodeResult.Confidence after reading a QR code and log the enumeration to a diagnostics file.
-// Tags: qr, barcode, confidence, diagnostics, generation, recognition, aspose
+// Tags: qr, confidence, barcode, reading, generation, diagnostics, logfile, aspose.barcode
using System;
using System.IO;
@@ -10,54 +11,70 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates how to generate a QR code, read it, retrieve the confidence level,
-/// and log the result to a diagnostics file using Aspose.BarCode.
+/// Example program that generates a QR code, reads it back, extracts the confidence level,
+/// and logs the result to a diagnostics file.
///
class Program
{
///
- /// Entry point of the example. Generates a QR code, reads it, and logs the confidence.
+ /// Entry point of the application.
+ /// Generates a QR code image, reads the barcode, logs the confidence enumeration,
+ /// and provides console feedback.
///
static void Main()
{
- const string imagePath = "qr.png";
- const string diagnosticsPath = "diagnostics.txt";
+ // Define file paths for the QR image and the diagnostics log.
+ string imagePath = "qr.png";
+ string logPath = "diagnostics.txt";
- // ------------------------------------------------------------
- // Generate a QR code image and save it to disk.
- // ------------------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Sample QR Text"))
+ // Clean up any previous run artifacts to ensure a fresh start.
+ if (File.Exists(imagePath))
{
- // Set a moderate error correction level (optional).
- generator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelM;
+ File.Delete(imagePath);
+ }
+ if (File.Exists(logPath))
+ {
+ File.Delete(logPath);
+ }
- // Save the generated QR code as a PNG file.
- generator.Save(imagePath, BarCodeImageFormat.Png);
+ // Generate a QR code containing sample text and save it to disk.
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "Sample QR Code"))
+ {
+ generator.Save(imagePath);
}
- // ------------------------------------------------------------
- // Verify that the QR code image was successfully created.
- // ------------------------------------------------------------
+ // Verify that the QR code image was successfully created before attempting to read it.
if (!File.Exists(imagePath))
{
- // Log an error message if the image file is missing.
- File.WriteAllText(diagnosticsPath, "Error: QR code image was not created." + Environment.NewLine);
+ Console.WriteLine("Failed to create QR code image.");
return;
}
- // ------------------------------------------------------------
- // Read the QR code from the image and retrieve the confidence level.
- // ------------------------------------------------------------
- using (var reader = new BarCodeReader(imagePath, DecodeType.QR))
+ // Initialize a barcode reader for QR codes and process the generated image.
+ using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.QR))
{
- foreach (var result in reader.ReadBarCodes())
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
- // Build a log entry containing the confidence enumeration value.
- string logEntry = $"Confidence: {result.Confidence}";
+ // Retrieve the confidence enumeration from the read result.
+ BarCodeConfidence confidence = result.Confidence;
+
+ // Build a log entry string containing the confidence value.
+ string logEntry = $"BarCode Confidence: {confidence}";
- // Append the confidence information to the diagnostics file.
- File.AppendAllText(diagnosticsPath, logEntry + Environment.NewLine);
+ // Append the log entry to the diagnostics file.
+ File.AppendAllText(logPath, logEntry + Environment.NewLine);
+
+ // Output the log entry to the console for immediate visibility.
+ Console.WriteLine(logEntry);
}
}
+
+ // If no barcode was detected, write a warning message to the diagnostics file and console.
+ if (!File.Exists(logPath) || new FileInfo(logPath).Length == 0)
+ {
+ string warning = "No barcode detected or confidence could not be retrieved.";
+ File.AppendAllText(logPath, warning + Environment.NewLine);
+ Console.WriteLine(warning);
+ }
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/set-barcodereader-s-timeout-to-zero-to-allow-unlimited-processing-time-for-complex-multi-barcode-images.cs b/barcode-recognition-basics/set-barcodereader-s-timeout-to-zero-to-allow-unlimited-processing-time-for-complex-multi-barcode-images.cs
index 236964a..495ac02 100644
--- a/barcode-recognition-basics/set-barcodereader-s-timeout-to-zero-to-allow-unlimited-processing-time-for-complex-multi-barcode-images.cs
+++ b/barcode-recognition-basics/set-barcodereader-s-timeout-to-zero-to-allow-unlimited-processing-time-for-complex-multi-barcode-images.cs
@@ -1,47 +1,48 @@
-// Title: Unlimited Barcode Processing with BarCodeReader Timeout
-// Description: Demonstrates setting BarCodeReader.Timeout to zero to allow unlimited processing time when reading complex images containing multiple barcodes.
+// Title: Unlimited Timeout for BarCodeReader with Complex Images
+// Description: Demonstrates setting BarCodeReader.Timeout to zero for unlimited processing time when reading multiple barcodes from an image.
+// Category-Description: This example belongs to the Aspose.BarCode reading operations collection. It showcases how to use BarCodeReader and BarcodeGenerator to create a barcode image in memory and then decode all barcodes without a time limit. Developers working with high‑density or multi‑barcode images often need to adjust the timeout to avoid premature termination. The key API classes illustrated are BarcodeGenerator, BarCodeReader, and related encoding/recognition types.
// Prompt: Set BarCodeReader's TimeOut to zero to allow unlimited processing time for complex multi‑barcode images.
-// Tags: barcode, timeout, multibarcode, aspose, csharp
+// Tags: code128, barcode reading, console output, barcodegenerator, barcodereader
using System;
-using System.IO;
+using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Example program that reads all barcodes from an image using Aspose.BarCode.
-/// It sets the reader's Timeout to zero, which disables the time limit
-/// and enables processing of complex multi‑barcode images without interruption.
+/// Generates a barcode image in memory and reads all barcodes from it using an unlimited timeout.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Creates a Code128 barcode, sets BarCodeReader.Timeout to zero,
+ /// and prints detected barcode types and texts to the console.
///
static void Main()
{
- // Path to the image containing multiple barcodes.
- const string imagePath = "multi_barcodes.png";
-
- // Verify that the image file exists before attempting to read it.
- if (!File.Exists(imagePath))
- {
- Console.WriteLine($"File not found: {imagePath}");
- return;
- }
-
- // Create a BarCodeReader for the specified image file.
- using (var reader = new BarCodeReader(imagePath))
+ // Create a BarcodeGenerator for Code128 with sample data
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- // Set the timeout to zero to allow unlimited processing time.
- reader.Timeout = 0;
+ // Generate the barcode image in memory
+ using (var barcodeImage = generator.GenerateBarCodeImage())
+ {
+ // Initialize BarCodeReader without an image (will be set later)
+ using (var reader = new BarCodeReader())
+ {
+ // Set unlimited timeout (0 milliseconds) to handle complex images
+ reader.Timeout = 0;
- // Configure the reader to detect all supported barcode types.
- reader.BarCodeReadType = DecodeType.AllSupportedTypes;
+ // Assign the generated image to the reader for processing
+ reader.SetBarCodeImage(barcodeImage);
- // Iterate through all detected barcodes and output their type and text.
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"Type: {result.CodeTypeName}, Text: {result.CodeText}");
+ // Iterate through all detected barcodes and output their details
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($"Code Text: {result.CodeText}");
+ }
+ }
}
}
}
diff --git a/barcode-recognition-basics/set-barcodesettingschecksumvalidation-to-off-to-disable-checksum-verification-for-code-11-during-batch-processing.cs b/barcode-recognition-basics/set-barcodesettingschecksumvalidation-to-off-to-disable-checksum-verification-for-code-11-during-batch-processing.cs
index 4db163c..8725a3a 100644
--- a/barcode-recognition-basics/set-barcodesettingschecksumvalidation-to-off-to-disable-checksum-verification-for-code-11-during-batch-processing.cs
+++ b/barcode-recognition-basics/set-barcodesettingschecksumvalidation-to-off-to-disable-checksum-verification-for-code-11-during-batch-processing.cs
@@ -1,7 +1,8 @@
-// Title: Code11 barcode generation and checksum‑disabled batch reading
-// Description: Demonstrates generating Code11 barcodes, saving them as PNG, and reading them back with checksum validation turned off.
+// Title: Disable Code11 checksum validation during batch barcode reading
+// Description: Demonstrates how to turn off checksum verification for Code 11 barcodes when reading multiple images in a batch.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It shows how to use BarcodeGenerator to create Code 11 barcodes and BarCodeReader with BarcodeSettings to control checksum validation. Developers often need to generate barcodes in bulk and later read them without strict checksum checks, especially when dealing with legacy data or noisy scans.
// Prompt: Set BarcodeSettings.ChecksumValidation to Off to disable checksum verification for Code 11 during batch processing.
-// Tags: code11, barcode, generation, recognition, checksumvalidation, aspnet, csharp
+// Tags: code11, checksum, batch processing, barcode generation, barcode recognition, aspose.barcode, generation, recognition
using System;
using System.IO;
@@ -10,67 +11,45 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Generates Code11 barcodes, saves them as PNG files, and reads them back with checksum validation disabled.
+/// Example program that generates Code 11 barcodes, then reads them back with checksum validation disabled.
///
class Program
{
///
- /// Application entry point. Creates sample Code11 barcodes, writes PNG files, then reads them while turning off checksum verification.
+ /// Entry point of the example. Generates barcode images, disables checksum validation, and reads the barcodes.
///
static void Main()
{
- // Define sample Code11 values to encode
- string[] codeTexts = { "12345", "67890", "112233" };
+ // Create a folder for generated barcode images
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ Directory.CreateDirectory(outputDir);
- // Prepare output directory for generated barcode images
- string outputFolder = "Barcodes";
- Directory.CreateDirectory(outputFolder);
+ // Sample Code11 codetexts
+ string[] codeTexts = { "12345", "67890", "112233" };
- // ------------------------------------------------------------
- // Generate Code11 barcodes and save each as a PNG file
- // ------------------------------------------------------------
+ // Generate barcode images for each codetext
for (int i = 0; i < codeTexts.Length; i++)
{
- // Build full file path for the current barcode image
- string filePath = Path.Combine(outputFolder, $"code11_{i}.png");
-
- // Create a barcode generator for Code11 with the current text
+ string filePath = Path.Combine(outputDir, $"code11_{i}.png");
using (var generator = new BarcodeGenerator(EncodeTypes.Code11, codeTexts[i]))
{
- // Save the generated barcode image in PNG format
+ // Save the barcode as a PNG image
generator.Save(filePath, BarCodeImageFormat.Png);
}
}
- // ------------------------------------------------------------
- // Read each generated barcode image with checksum validation disabled
- // ------------------------------------------------------------
- foreach (string file in Directory.GetFiles(outputFolder, "*.png"))
+ // Read the generated barcodes with checksum validation disabled
+ foreach (string file in Directory.GetFiles(outputDir, "*.png"))
{
- // Verify that the file actually exists before attempting to read
- if (!File.Exists(file))
- {
- Console.WriteLine($"File not found: {file}");
- continue;
- }
-
- // Initialize a barcode reader for Code11
using (var reader = new BarCodeReader(file, DecodeType.Code11))
{
- // Disable checksum verification for Code11 as required by the prompt
+ // Disable checksum verification for Code 11
reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.Off;
// Iterate through all detected barcodes in the image
- foreach (BarCodeResult result in reader.ReadBarCodes())
+ foreach (var result in reader.ReadBarCodes())
{
- // Output basic barcode information
- Console.WriteLine($"File: {Path.GetFileName(file)} CodeText: {result.CodeText}");
-
- // If extended 1D information is available, display the checksum value
- if (result.Extended?.OneD != null)
- {
- Console.WriteLine($"Checksum: {result.Extended.OneD.CheckSum}");
- }
+ Console.WriteLine($"File: {Path.GetFileName(file)} | Detected CodeText: {result.CodeText}");
}
}
}
diff --git a/barcode-recognition-basics/set-decodetype-to-qr-before-reading-image-to-limit-recognition-to-qr-symbology-only.cs b/barcode-recognition-basics/set-decodetype-to-qr-before-reading-image-to-limit-recognition-to-qr-symbology-only.cs
index dbded95..67aa1f7 100644
--- a/barcode-recognition-basics/set-decodetype-to-qr-before-reading-image-to-limit-recognition-to-qr-symbology-only.cs
+++ b/barcode-recognition-basics/set-decodetype-to-qr-before-reading-image-to-limit-recognition-to-qr-symbology-only.cs
@@ -1,7 +1,8 @@
// Title: QR Code Generation and QR-Only Decoding Example
-// Description: Demonstrates generating a QR code image and then reading it using Aspose.BarCode with DecodeType set to QR to restrict recognition to QR symbology only.
+// Description: Demonstrates generating a QR barcode image and then decoding it while restricting recognition to QR symbology.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator for creating QR codes and BarCodeReader with DecodeType.QR to limit decoding to a specific symbology. Developers often need to generate barcodes and later read them efficiently, especially when only one type of barcode is expected, to improve performance and accuracy.
// Prompt: Set DecodeType to QR before reading an image to limit recognition to QR symbology only.
-// Tags: qr, barcode, generation, recognition, decode, aspose.barcode
+// Tags: barcode symbology, qr, generation, decoding, aspose.barcode, decode type
using System;
using System.IO;
@@ -10,49 +11,44 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Generates a QR code image (if missing) and reads it using a QR‑only decoder.
+/// Generates a QR barcode image and reads it back, limiting the decoding process to QR symbology only.
///
class Program
{
///
- /// Entry point of the example. Creates a QR code image and decodes it with DecodeType.QR.
+ /// Entry point of the example. Creates a QR code, saves it as PNG, and then decodes it using QR‑only recognition.
///
static void Main()
{
- // Path to the QR code image file
- const string imagePath = "qr.png";
+ // Path where the generated QR image will be saved
+ string qrImagePath = "qr.png";
// ------------------------------------------------------------
- // Generate a QR code image if it does not already exist
+ // Generate a QR barcode image
// ------------------------------------------------------------
- if (!File.Exists(imagePath))
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Hello QR"))
{
- // Initialize the generator with QR symbology and sample text
- using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Hello QR"))
- {
- // Save the generated QR code to a PNG file
- generator.Save(imagePath);
- }
+ // Save the QR code as a PNG file
+ generator.Save(qrImagePath, BarCodeImageFormat.Png);
}
- // ------------------------------------------------------------
- // Verify that the image file exists before attempting to read it
- // ------------------------------------------------------------
- if (!File.Exists(imagePath))
+ // Verify that the image file was successfully created
+ if (!File.Exists(qrImagePath))
{
- Console.WriteLine($"Image file not found: {imagePath}");
+ Console.WriteLine("Failed to create QR image.");
return;
}
// ------------------------------------------------------------
- // Create a BarCodeReader limited to QR symbology only
+ // Read the image, limiting recognition to QR symbology only
// ------------------------------------------------------------
- using (var reader = new BarCodeReader(imagePath, DecodeType.QR))
+ using (var reader = new BarCodeReader(qrImagePath, DecodeType.QR))
{
- // Iterate through all detected barcodes (expected: only QR codes)
+ // Iterate through all detected barcodes (expected to be one QR code)
foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"Detected QR Code: {result.CodeText}");
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($"Decoded Text: {result.CodeText}");
}
}
}
diff --git a/barcode-recognition-basics/set-timeout-property-to-five-seconds-to-abort-recognition-if-processing-exceeds-specified-limit.cs b/barcode-recognition-basics/set-timeout-property-to-five-seconds-to-abort-recognition-if-processing-exceeds-specified-limit.cs
index ed7ff05..b69896b 100644
--- a/barcode-recognition-basics/set-timeout-property-to-five-seconds-to-abort-recognition-if-processing-exceeds-specified-limit.cs
+++ b/barcode-recognition-basics/set-timeout-property-to-five-seconds-to-abort-recognition-if-processing-exceeds-specified-limit.cs
@@ -1,52 +1,47 @@
-// Title: Barcode Recognition with Timeout
-// Description: Demonstrates generating a sample Code128 barcode if missing, then reading it with a 5‑second timeout to abort long processing.
+// Title: Barcode recognition with timeout handling
+// Description: Demonstrates generating a Code128 barcode, then recognizing it with a 5‑second timeout to abort long processing.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It shows how to use BarcodeGenerator to create barcodes and BarCodeReader with the Timeout property to control recognition duration. Developers often need to generate barcodes on the fly and ensure recognition does not hang, especially in high‑throughput or web services.
// Prompt: Set TimeOut property to five seconds to abort recognition if processing exceeds the specified limit.
-// Tags: barcode, code128, timeout, recognition, aspose.barcode
+// Tags: barcode, code128, timeout, recognition, generation, aspose.barcode, csharp
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.BarCode;
///
-/// Example program that creates a barcode image (if needed) and reads it using a timeout setting.
+/// Demonstrates generating a Code128 barcode and recognizing it with a timeout.
///
class Program
{
///
- /// Entry point of the application. Generates a sample barcode if it does not exist,
- /// then reads the barcode with a 5‑second timeout to prevent long‑running recognition.
+ /// Entry point. Generates a barcode, saves to memory, and reads it with a 5‑second timeout.
///
static void Main()
{
- const string imagePath = "barcode.png";
-
- // ------------------------------------------------------------
- // Ensure a sample barcode image exists; create one if missing.
- // ------------------------------------------------------------
- if (!File.Exists(imagePath))
+ // Initialize a BarcodeGenerator for Code128 with the desired text
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
{
- // Generate a Code128 barcode with the text "12345" and save as PNG.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "12345"))
+ // Store the generated barcode image in a memory stream
+ using (var ms = new MemoryStream())
{
- generator.Save(imagePath, BarCodeImageFormat.Png);
- }
- }
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0; // Reset stream position for subsequent reading
- // ------------------------------------------------------------
- // Read the barcode image using a timeout of 5 seconds (5000 ms).
- // ------------------------------------------------------------
- using (var reader = new BarCodeReader(imagePath))
- {
- // Abort recognition if it exceeds the specified time limit.
- reader.Timeout = 5000;
+ // Create a BarCodeReader to recognize Code128 from the memory stream
+ using (var reader = new BarCodeReader(ms, DecodeType.Code128))
+ {
+ // Set the timeout to 5000 ms (5 seconds) to abort if recognition takes too long
+ reader.Timeout = 5000;
- // Iterate through all detected barcodes and output their type and text.
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine("BarCode Type: " + result.CodeTypeName);
- Console.WriteLine("BarCode CodeText: " + result.CodeText);
+ // Iterate through all recognized barcodes and output their details
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
+ Console.WriteLine($"BarCode CodeText: {result.CodeText}");
+ }
+ }
}
}
}
diff --git a/barcode-recognition-basics/specify-rectangular-target-region-before-recognition-to-limit-barcode-detection-to-defined-area-of-image.cs b/barcode-recognition-basics/specify-rectangular-target-region-before-recognition-to-limit-barcode-detection-to-defined-area-of-image.cs
index 6582ddd..e42c7b5 100644
--- a/barcode-recognition-basics/specify-rectangular-target-region-before-recognition-to-limit-barcode-detection-to-defined-area-of-image.cs
+++ b/barcode-recognition-basics/specify-rectangular-target-region-before-recognition-to-limit-barcode-detection-to-defined-area-of-image.cs
@@ -1,52 +1,86 @@
-// Title: Barcode detection within a specified rectangular region
-// Description: Demonstrates how to limit barcode recognition to a defined area of an image by specifying a target rectangle before scanning.
+// Title: Specify Rectangular Target Region for Barcode Recognition
+// Description: Demonstrates how to limit barcode detection to a defined rectangular area of an image using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode image processing and recognition category. It showcases the use of BarcodeGenerator, BarCodeReader, and related classes to generate a barcode, then restrict recognition to specific regions. Developers often need to focus on a sub‑area of an image to improve performance or avoid false positives, especially when multiple barcodes or visual noise are present.
// Prompt: Specify a rectangular target region before recognition to limit barcode detection to a defined area of the image.
-// Tags: barcode, code128, region, recognition, aspose.barcode
+// Tags: code128, region, recognition, barcode, aspose.barcode, generation, png
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, defines a target region,
-/// and reads barcodes only within that region.
+/// Example program that generates a Code128 barcode, saves it as PNG,
+/// and demonstrates barcode recognition within specific rectangular regions.
///
class Program
{
///
- /// Entry point. Generates a barcode image, sets a rectangular target region,
- /// and uses BarCodeReader to detect barcodes confined to that region.
+ /// Entry point of the example. Generates a barcode image and runs two
+ /// recognition scenarios: one with an empty region and one with a region
+ /// that fully contains the barcode.
///
static void Main()
{
- // Generate a sample Code128 barcode image in memory
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789"))
+ // Path for the generated barcode image
+ string imagePath = "barcode.png";
+
+ // Generate a simple Code128 barcode and save it to a file
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
+ {
+ // Save as PNG format
+ generator.Save(imagePath, BarCodeImageFormat.Png);
+ }
+
+ // Verify that the image was created successfully
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine($"Failed to create barcode image at '{imagePath}'.");
+ return;
+ }
+
+ // Load the generated image into a bitmap for recognition
+ using (var bitmap = new Bitmap(imagePath))
{
- // Set image size using point units (300x150 points)
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 150f;
+ // -------------------------------------------------
+ // Example 1: Define a region that does NOT contain the barcode
+ // -------------------------------------------------
+ // Very small area at the top‑left corner (0,0) with size 10x10 pixels
+ var emptyRegion = new Rectangle(0, 0, 10, 10);
+
+ // Initialize the reader with the empty region and specify Code128 decoding
+ using (var reader = new BarCodeReader(bitmap, emptyRegion, DecodeType.Code128))
+ {
+ // Perform recognition within the defined region
+ var results = reader.ReadBarCodes();
+
+ // Output the number of barcodes found (expected to be 0)
+ Console.WriteLine($"Results in empty region: {reader.FoundCount}");
+ foreach (var result in results)
+ {
+ Console.WriteLine($"Type: {result.CodeTypeName}, Text: {result.CodeText}");
+ }
+ }
+
+ // -------------------------------------------------
+ // Example 2: Define a region that fully contains the barcode
+ // -------------------------------------------------
+ // Region covering the entire image dimensions
+ var fullRegion = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
- // Create the barcode bitmap
- using (var bitmap = generator.GenerateBarCodeImage())
+ // Initialize the reader with the full region and specify Code128 decoding
+ using (var reader = new BarCodeReader(bitmap, fullRegion, DecodeType.Code128))
{
- // Define a rectangular region (top‑left quarter of the image)
- var targetRegion = new Rectangle(0, 0, bitmap.Width / 2, bitmap.Height / 2);
+ // Perform recognition within the full image area
+ var results = reader.ReadBarCodes();
- // Initialize a BarCodeReader that scans only within the specified region
- using (var reader = new BarCodeReader(bitmap, targetRegion, DecodeType.Code128))
+ // Output the number of barcodes found (expected to be 1)
+ Console.WriteLine($"Results in full region: {reader.FoundCount}");
+ foreach (var result in results)
{
- // Iterate through all detected barcodes in the region
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"Detected Type: {result.CodeTypeName}");
- Console.WriteLine($"Code Text: {result.CodeText}");
-
- // Retrieve and display the bounding rectangle of the detected barcode
- var bounds = result.Region.Rectangle;
- Console.WriteLine($"Barcode Region - X:{bounds.X}, Y:{bounds.Y}, Width:{bounds.Width}, Height:{bounds.Height}");
- }
+ Console.WriteLine($"Type: {result.CodeTypeName}, Text: {result.CodeText}");
}
}
}
diff --git a/barcode-recognition-basics/store-detected-barcode-values-into-database-table-after-reading-them-from-each-processed-image-file.cs b/barcode-recognition-basics/store-detected-barcode-values-into-database-table-after-reading-them-from-each-processed-image-file.cs
index 7db7593..90cde4b 100644
--- a/barcode-recognition-basics/store-detected-barcode-values-into-database-table-after-reading-them-from-each-processed-image-file.cs
+++ b/barcode-recognition-basics/store-detected-barcode-values-into-database-table-after-reading-them-from-each-processed-image-file.cs
@@ -1,135 +1,121 @@
-// Title: Barcode detection and CSV export example
-// Description: Demonstrates reading barcodes from image files, collecting their details, and storing the results in a CSV file (as a placeholder for a database).
+// Title: Generate and Detect Barcodes, Store Results in CSV
+// Description: This example generates sample barcode images, reads them back, and stores detected values in a CSV file as a stand‑in for a database table.
+// Category-Description: Demonstrates core Aspose.BarCode operations—barcode generation with BarcodeGenerator and barcode recognition with BarCodeReader. Typical use cases include creating barcodes for inventory, scanning documents, and persisting scan results. Developers often need to generate multiple symbologies, detect them automatically, and store the outcomes using common .NET I/O or database APIs.
// Prompt: Store detected barcode values into a database table after reading them from each processed image file.
-// Tags: barcode, detection, csv, aspnet, aspose.barcoderecognition, file-io
+// Tags: barcode generation,barcode recognition,csv output,aspose.barcode,code128,qr,datamatrix
using System;
-using System.Collections.Generic;
using System.IO;
+using System.Collections.Generic;
using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that reads barcodes from a set of image files,
-/// collects relevant information, and writes the data to a CSV file.
-/// The CSV output serves as a stand‑in for persisting the data to a database.
+/// Demonstrates how to generate barcode images, read them, and persist detection results.
///
class Program
{
///
- /// Simple record to hold barcode information extracted from an image.
+ /// Simple record to hold barcode detection results.
///
private class BarcodeRecord
{
public string FileName { get; set; }
public string CodeType { get; set; }
public string CodeText { get; set; }
- public string Region { get; set; }
}
///
- /// Entry point of the application. Processes each image, extracts barcodes,
- /// and saves the collected data to a CSV file.
+ /// Entry point. Generates sample barcodes, detects them, and writes results to a CSV file.
///
static void Main()
{
- // --------------------------------------------------------------------
- // Define the list of image files to be processed.
- // Adjust the file paths as needed for your environment.
- // --------------------------------------------------------------------
- string[] imageFiles = new string[]
+ // Define folder for generated barcode images.
+ string imagesFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ Directory.CreateDirectory(imagesFolder);
+
+ // Define sample barcodes to generate (type, text, file name).
+ var samples = new (BaseEncodeType type, string text, string file)[]
{
- "sample1.png",
- "sample2.png",
- "sample3.png"
+ (EncodeTypes.Code128, "Sample123", "code128.png"),
+ (EncodeTypes.QR, "https://example.com", "qr.png"),
+ (EncodeTypes.DataMatrix, "DM12345", "datamatrix.png")
};
- // Collection to store barcode records from all images.
- var records = new List();
+ // Generate each sample barcode image and save as PNG.
+ foreach (var sample in samples)
+ {
+ string imagePath = Path.Combine(imagesFolder, sample.file);
+ using (var generator = new BarcodeGenerator(sample.type, sample.text))
+ {
+ // Save image; format inferred from file extension.
+ generator.Save(imagePath);
+ }
+ }
+
+ // Collect detection results in a list.
+ var results = new List();
- // --------------------------------------------------------------------
- // Iterate over each image file, read barcodes, and populate the records.
- // --------------------------------------------------------------------
- foreach (var filePath in imageFiles)
+ // Process each PNG image in the folder.
+ string[] imageFiles = Directory.GetFiles(imagesFolder, "*.png");
+ foreach (string imageFile in imageFiles)
{
- // Verify that the file exists before attempting to read it.
- if (!File.Exists(filePath))
+ if (!File.Exists(imageFile))
{
- Console.WriteLine($"File not found: {filePath}");
+ Console.WriteLine($"File not found: {imageFile}");
continue;
}
- // Create a barcode reader that attempts to detect all supported types.
- using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
+ // Use AllSupportedTypes to detect any barcode present in the image.
+ using (var reader = new BarCodeReader(imageFile, DecodeType.AllSupportedTypes))
{
- // Read all barcodes present in the current image.
foreach (var result in reader.ReadBarCodes())
{
- // Build a record with the extracted information.
- var record = new BarcodeRecord
+ // Store detection details.
+ results.Add(new BarcodeRecord
{
- FileName = Path.GetFileName(filePath),
+ FileName = Path.GetFileName(imageFile),
CodeType = result.CodeTypeName,
- CodeText = result.CodeText,
- // Store region as a simple string representation of the bounding rectangle.
- Region = $"{result.Region.Rectangle.X},{result.Region.Rectangle.Y},{result.Region.Rectangle.Width},{result.Region.Rectangle.Height}"
- };
+ CodeText = result.CodeText
+ });
- // Add the record to the collection and output a console message.
- records.Add(record);
- Console.WriteLine($"Detected {record.CodeType} in {record.FileName}: {record.CodeText}");
+ Console.WriteLine($"Detected {result.CodeTypeName} in {Path.GetFileName(imageFile)}: {result.CodeText}");
}
}
}
- // --------------------------------------------------------------------
- // Write the collected barcode data to a CSV file.
- // This CSV acts as a placeholder for a real database implementation.
- // --------------------------------------------------------------------
- string csvPath = "barcode_results.csv";
+ // Write results to a CSV file (acts as a stand‑in for a database table).
+ string csvPath = Path.Combine(Directory.GetCurrentDirectory(), "barcode_results.csv");
using (var writer = new StreamWriter(csvPath, false))
{
- // Write CSV header.
- writer.WriteLine("FileName,CodeType,CodeText,Region");
-
- // Write each record, escaping fields as necessary.
- foreach (var rec in records)
+ writer.WriteLine("FileName,CodeType,CodeText");
+ foreach (var record in results)
{
- string fileName = EscapeCsv(rec.FileName);
- string codeType = EscapeCsv(rec.CodeType);
- string codeText = EscapeCsv(rec.CodeText);
- string region = EscapeCsv(rec.Region);
- writer.WriteLine($"{fileName},{codeType},{codeText},{region}");
+ // Escape commas in fields to preserve CSV integrity.
+ string fileName = record.FileName.Replace(",", " ");
+ string codeType = record.CodeType.Replace(",", " ");
+ string codeText = record.CodeText.Replace(",", " ");
+ writer.WriteLine($"{fileName},{codeType},{codeText}");
}
}
- Console.WriteLine($"Barcode data saved to {csvPath}");
+ Console.WriteLine($"Detection results written to {csvPath}");
- // --------------------------------------------------------------------
- // Placeholder for a real database implementation (e.g., SQLite).
- // The necessary NuGet package is not referenced in this snippet.
- // --------------------------------------------------------------------
+ // Real database insertion would go here, e.g., using ADO.NET or an ORM.
+ // Example (commented out because the required NuGet packages are not available in the runner):
// using var connection = new SqliteConnection("Data Source=barcodes.db");
// connection.Open();
// var command = connection.CreateCommand();
- // command.CommandText = "CREATE TABLE IF NOT EXISTS Barcodes (FileName TEXT, CodeType TEXT, CodeText TEXT, Region TEXT);";
+ // command.CommandText = "CREATE TABLE IF NOT EXISTS Barcodes (FileName TEXT, CodeType TEXT, CodeText TEXT);";
// command.ExecuteNonQuery();
- // foreach (var rec in records) { ... insert into table ... }
- }
-
- ///
- /// Escapes a CSV field by surrounding it with quotes if it contains commas,
- /// quotes, or line breaks, and doubles any internal quotes.
- ///
- /// The field value to escape.
- /// The escaped field suitable for CSV output.
- private static string EscapeCsv(string field)
- {
- if (field.Contains(",") || field.Contains("\"") || field.Contains("\n"))
- {
- field = field.Replace("\"", "\"\"");
- return $"\"{field}\"";
- }
- return field;
+ // foreach (var record in results)
+ // {
+ // command.CommandText = "INSERT INTO Barcodes (FileName, CodeType, CodeText) VALUES (@file, @type, @text);";
+ // command.Parameters.AddWithValue("@file", record.FileName);
+ // command.Parameters.AddWithValue("@type", record.CodeType);
+ // command.Parameters.AddWithValue("@text", record.CodeText);
+ // command.ExecuteNonQuery();
+ // }
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/test-impact-of-disabling-checksum-verification-on-recognition-speed-for-high-volume-code-39-scans.cs b/barcode-recognition-basics/test-impact-of-disabling-checksum-verification-on-recognition-speed-for-high-volume-code-39-scans.cs
index e82e772..c077687 100644
--- a/barcode-recognition-basics/test-impact-of-disabling-checksum-verification-on-recognition-speed-for-high-volume-code-39-scans.cs
+++ b/barcode-recognition-basics/test-impact-of-disabling-checksum-verification-on-recognition-speed-for-high-volume-code-39-scans.cs
@@ -1,105 +1,80 @@
-// Title: Code 39 checksum validation performance test
-// Description: Demonstrates how disabling checksum verification affects recognition speed when processing multiple Code 39 barcodes.
+// Title: Impact of Checksum Validation on Code 39 Recognition Speed
+// Description: Demonstrates how disabling checksum verification affects the time required to recognize a batch of Code 39 barcodes.
+// Category-Description: This example belongs to the Aspose.BarCode recognition performance category. It shows how to configure the BarCodeReader's ChecksumValidation property (On/Off) while processing multiple images, a common scenario for high‑volume scanning applications where speed is critical. Developers often need to balance validation accuracy against throughput using classes like BarCodeReader, BarcodeGenerator, and Stopwatch.
// Prompt: Test impact of disabling checksum verification on recognition speed for high‑volume Code 39 scans.
-// Tags: code39, checksum, performance, barcode, generation, recognition, aspnet, csharp
+// Tags: code39, checksum, performance, recognition, aspose.barcode, barcodegenerator, barcodereader, stopwatch
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;
///
-/// Program that generates a set of Code 39 barcodes, then measures recognition time with checksum validation enabled and disabled.
+/// Example program that measures the effect of enabling or disabling checksum validation
+/// on the recognition speed of a set of Code 39 barcode images.
///
class Program
{
///
- /// Entry point. Generates barcodes, runs recognition with checksum on/off, and prints timing results.
+ /// Entry point. Generates sample Code 39 barcodes, then times recognition with checksum
+ /// validation turned on and off, outputting the results.
///
static void Main()
{
- // Sample data for Code 39 barcodes
- List samples = new List
- {
- "CODE39A",
- "CODE39B",
- "CODE39C",
- "CODE39D",
- "CODE39E"
- };
+ const int sampleCount = 10; // Number of barcode images to generate
+ string folder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ Directory.CreateDirectory(folder); // Ensure output directory exists
- // Generate barcode images and keep them in memory
- List barcodes = new List();
- foreach (string text in samples)
+ // Generate sample Code 39 barcode images
+ for (int i = 0; i < sampleCount; i++)
{
- using (MemoryStream ms = new MemoryStream())
+ string text = $"CODE{i:D4}";
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code39, text))
{
- // Create a barcode generator for Code 39 and save to memory stream as PNG
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code39, text))
- {
- generator.Save(ms, BarCodeImageFormat.Png);
- }
-
- ms.Position = 0;
-
- // Load bitmap from memory stream and clone it to preserve after disposing the original
- using (Bitmap bmp = new Bitmap(ms))
- {
- barcodes.Add(new Bitmap(bmp));
- }
+ string filePath = Path.Combine(folder, $"code{i}.png");
+ generator.Save(filePath); // Save PNG image to disk
}
}
- // Measure recognition time with checksum validation ON
- Stopwatch swOn = new Stopwatch();
- swOn.Start();
- foreach (Bitmap bmp in barcodes)
- {
- using (BarCodeReader reader = new BarCodeReader(bmp, DecodeType.Code39))
- {
- // Enable checksum validation
- reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
+ // Measure recognition time with checksum validation enabled
+ long timeWithChecksum = MeasureRecognitionTime(folder, ChecksumValidation.On);
- // Read all barcodes in the image
- foreach (BarCodeResult result in reader.ReadBarCodes())
- {
- // Access result to ensure processing
- string code = result.CodeText;
- }
- }
- }
- swOn.Stop();
+ // Measure recognition time with checksum validation disabled
+ long timeWithoutChecksum = MeasureRecognitionTime(folder, ChecksumValidation.Off);
+
+ // Output timing results
+ Console.WriteLine($"Recognition time with checksum ON : {timeWithChecksum} ms");
+ Console.WriteLine($"Recognition time with checksum OFF: {timeWithoutChecksum} ms");
+ }
+
+ ///
+ /// Scans all PNG files in the specified folder using the given checksum setting
+ /// and returns the elapsed time in milliseconds.
+ ///
+ /// Path to the folder containing barcode images.
+ /// Checksum validation mode (On or Off).
+ /// Elapsed time in milliseconds for processing all images.
+ static long MeasureRecognitionTime(string folderPath, ChecksumValidation checksumSetting)
+ {
+ string[] files = Directory.GetFiles(folderPath, "*.png");
+ Stopwatch sw = Stopwatch.StartNew(); // Start timing
- // Measure recognition time with checksum validation OFF
- Stopwatch swOff = new Stopwatch();
- swOff.Start();
- foreach (Bitmap bmp in barcodes)
+ foreach (string file in files)
{
- using (BarCodeReader reader = new BarCodeReader(bmp, DecodeType.Code39))
+ using (BarCodeReader reader = new BarCodeReader(file, DecodeType.Code39))
{
- // Disable checksum validation
- reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.Off;
+ // Apply the requested checksum validation setting
+ reader.BarcodeSettings.ChecksumValidation = checksumSetting;
- // Read all barcodes in the image
- foreach (BarCodeResult result in reader.ReadBarCodes())
- {
- string code = result.CodeText;
- }
+ // ReadBarCodes returns an array; results are ignored for timing purposes
+ _ = reader.ReadBarCodes();
}
}
- swOff.Stop();
-
- // Output the timing results
- Console.WriteLine($"Checksum ON - Total time: {swOn.ElapsedMilliseconds} ms");
- Console.WriteLine($"Checksum OFF - Total time: {swOff.ElapsedMilliseconds} ms");
- // Clean up generated bitmaps
- foreach (Bitmap bmp in barcodes)
- {
- bmp.Dispose();
- }
+ sw.Stop(); // Stop timing
+ return sw.ElapsedMilliseconds;
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/test-recognition-of-rotated-barcodes-by-loading-images-with-varied-orientation-and-verifying-correct-decoding.cs b/barcode-recognition-basics/test-recognition-of-rotated-barcodes-by-loading-images-with-varied-orientation-and-verifying-correct-decoding.cs
index 2ebd4f7..fd00f22 100644
--- a/barcode-recognition-basics/test-recognition-of-rotated-barcodes-by-loading-images-with-varied-orientation-and-verifying-correct-decoding.cs
+++ b/barcode-recognition-basics/test-recognition-of-rotated-barcodes-by-loading-images-with-varied-orientation-and-verifying-correct-decoding.cs
@@ -1,120 +1,140 @@
-// Title: Rotated barcode recognition test
-// Description: Demonstrates generating a Code128 barcode, rotating it at various angles, and verifying that the Aspose.BarCode recognizer correctly decodes each orientation.
+// Title: Rotated barcode generation and recognition example
+// Description: Demonstrates creating Code128 barcodes, rotating them at various angles, and verifying that Aspose.BarCode can correctly decode each orientation.
+// Category-Description: This example belongs to the Aspose.BarCode image processing and recognition category, showcasing the use of BarcodeGenerator for barcode creation, Bitmap manipulation for rotation, and BarCodeReader for decoding. Typical use cases include handling scanned barcodes that may be rotated, ensuring robust recognition in real‑world applications. Developers often need to rotate images, adjust quality settings, and validate decoded values.
// Prompt: Test recognition of rotated barcodes by loading images with varied orientation and verifying correct decoding.
-// Tags: barcode, rotation, recognition, code128, aspose.barcode, csharp
+// Tags: barcode, rotation, code128, generation, recognition, aspose.barcode, bitmap, qualitysettings
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 generates a barcode, creates rotated versions, and validates recognition.
+/// Demonstrates generating Code128 barcodes, rotating them, and recognizing the rotated images.
///
class Program
{
///
- /// Entry point. Generates barcode, rotates images, and reads them back to verify decoding.
+ /// Entry point. Generates rotated barcode images, saves them, and validates recognition.
///
static void Main()
{
- // Define barcode text and output directory
- string codeText = "Test123";
- string outputDir = Directory.GetCurrentDirectory();
-
- // Ensure output directory exists
- if (!Directory.Exists(outputDir))
- {
- Console.WriteLine("Output directory does not exist.");
- return;
- }
-
- // Generate original barcode image
- string originalPath = Path.Combine(outputDir, "barcode_original.png");
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ // Define folder for generated barcode images
+ string folder = Path.Combine(Directory.GetCurrentDirectory(), "RotatedBarcodes");
+ if (!Directory.Exists(folder))
{
- generator.Save(originalPath);
+ Directory.CreateDirectory(folder);
}
- // Verify that the original image was created successfully
- if (!File.Exists(originalPath))
- {
- Console.WriteLine("Failed to create original barcode image.");
- return;
- }
+ // Text to encode in the barcode
+ const string barcodeText = "Test123";
- // Angles to test (in degrees)
+ // Rotation angles to apply (in degrees)
int[] angles = new int[] { 0, 90, 180, 270 };
- // Create rotated versions of the original barcode image
+ // -----------------------------------------------------------------
+ // Generate barcode images and rotate them according to the angles
+ // -----------------------------------------------------------------
foreach (int angle in angles)
{
- string rotatedPath = Path.Combine(outputDir, $"barcode_{angle}.png");
- using (var originalBitmap = new Bitmap(originalPath))
+ string filePath = Path.Combine(folder, $"barcode_{angle}.png");
+
+ // Create a barcode generator for Code128
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, barcodeText))
{
- // Clone original for rotation to avoid modifying the source file
- using (var bitmap = (Bitmap)originalBitmap.Clone())
+ // Set module size (optional, improves readability)
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+
+ // Save the generated barcode to a memory stream
+ using (var ms = new MemoryStream())
{
- if (angle != 0)
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0;
+
+ // Load the image from the stream for rotation
+ using (var bitmap = new Bitmap(ms))
{
- // Apply rotation based on the current angle
- switch (angle)
+ // Apply rotation if required
+ if (angle != 0)
{
- case 90:
- bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
- break;
- case 180:
- bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone);
- break;
- case 270:
- bitmap.RotateFlip(RotateFlipType.Rotate270FlipNone);
- break;
+ bitmap.RotateFlip(GetRotateFlipType(angle));
}
- }
- // Save the rotated image as PNG
- bitmap.Save(rotatedPath, ImageFormat.Png);
+ // Persist the (rotated) image to disk
+ bitmap.Save(filePath, ImageFormat.Png);
+ }
}
}
+
+ Console.WriteLine($"Generated barcode image at angle {angle} degrees: {filePath}");
}
- // Recognize each rotated image and verify decoded text
+ Console.WriteLine();
+ Console.WriteLine("=== Barcode Recognition of Rotated Images ===");
+
+ // -----------------------------------------------------------------
+ // Recognize each rotated image and verify the decoded text matches
+ // -----------------------------------------------------------------
foreach (int angle in angles)
{
- string path = Path.Combine(outputDir, $"barcode_{angle}.png");
- if (!File.Exists(path))
+ string filePath = Path.Combine(folder, $"barcode_{angle}.png");
+
+ if (!File.Exists(filePath))
{
- Console.WriteLine($"File not found: {path}");
+ Console.WriteLine($"Warning: File not found - {filePath}");
continue;
}
- using (var reader = new BarCodeReader(path, DecodeType.AllSupportedTypes))
+ // Initialize the barcode reader for Code128
+ using (var reader = new BarCodeReader(filePath, DecodeType.Code128))
{
- // Use normal quality preset for recognition
+ // Use normal quality preset for balanced performance
reader.QualitySettings = QualitySettings.NormalQuality;
- bool found = false;
+ bool decoded = false;
foreach (var result in reader.ReadBarCodes())
{
- found = true;
- Console.WriteLine($"Image: barcode_{angle}.png");
- Console.WriteLine($"Detected Type: {result.CodeTypeName}");
- Console.WriteLine($"Decoded Text: {result.CodeText}");
- Console.WriteLine($"Orientation Angle: {result.Region.Angle}");
- if (result.CodeText != codeText)
+ decoded = true;
+ Console.WriteLine($"Angle {angle}° - Detected Type: {result.CodeTypeName}, Text: {result.CodeText}");
+ if (result.CodeText != barcodeText)
{
- Console.WriteLine("Warning: Decoded text does not match expected value.");
+ Console.WriteLine($" Mismatch! Expected '{barcodeText}'");
}
- Console.WriteLine();
}
- if (!found)
+ if (!decoded)
{
- Console.WriteLine($"No barcode detected in image: barcode_{angle}.png");
+ Console.WriteLine($"Angle {angle}° - No barcode detected.");
}
}
}
+
+ Console.WriteLine();
+ Console.WriteLine("Processing completed.");
+ }
+
+ ///
+ /// Maps a rotation angle (0, 90, 180, 270) to the corresponding RotateFlipType.
+ ///
+ /// Rotation angle in degrees.
+ /// Corresponding RotateFlipType value.
+ private static RotateFlipType GetRotateFlipType(int angle)
+ {
+ switch (angle)
+ {
+ case 90:
+ return RotateFlipType.Rotate90FlipNone;
+ case 180:
+ return RotateFlipType.Rotate180FlipNone;
+ case 270:
+ return RotateFlipType.Rotate270FlipNone;
+ case 0:
+ return RotateFlipType.RotateNoneFlipNone;
+ default:
+ throw new ArgumentException("Unsupported rotation angle. Use 0, 90, 180, or 270.");
+ }
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/treat-readingquality-100-as-strong-and-automatically-accept-decoded-data-without-additional-verification.cs b/barcode-recognition-basics/treat-readingquality-100-as-strong-and-automatically-accept-decoded-data-without-additional-verification.cs
index bf27a9e..3a14db4 100644
--- a/barcode-recognition-basics/treat-readingquality-100-as-strong-and-automatically-accept-decoded-data-without-additional-verification.cs
+++ b/barcode-recognition-basics/treat-readingquality-100-as-strong-and-automatically-accept-decoded-data-without-additional-verification.cs
@@ -1,7 +1,8 @@
-// Title: QR Code Generation and Strong Quality Barcode Reading
-// Description: Generates a QR code, reads it back, and automatically accepts data when reading quality is 100, demonstrating quality-based validation.
+// Title: QR Code Generation and Reading with Strong ReadingQuality Handling
+// Description: Generates a QR code, saves it as a PNG file, then reads the barcode back and automatically accepts codes with maximum reading quality.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, demonstrating how to use BarcodeGenerator (for creating barcodes) and BarCodeReader (for decoding). Typical use cases include creating QR codes for data exchange and validating them with high confidence. Developers often need to assess reading quality to decide whether additional verification is required.
// Prompt: Treat ReadingQuality 100 as strong and automatically accept the decoded data without additional verification.
-// Tags: qr, barcode, generation, recognition, readingquality, console
+// Tags: qr, generation, recognition, readingquality, aspose.barcode, png
using System;
using System.IO;
@@ -10,60 +11,51 @@
using Aspose.Drawing;
///
-/// Demonstrates creating a QR code, reading it, and handling strong reading quality automatically.
+/// Demonstrates generating a QR code, saving it to a file, and reading it back while
+/// automatically accepting results with a ReadingQuality of 100.
///
class Program
{
///
- /// Entry point of the example. Generates a QR code, reads it, and processes results based on reading quality.
+ /// Entry point of the example. Generates a QR code, saves it, and reads it using
+ /// Aspose.BarCode APIs, applying a strong quality rule.
///
static void Main()
{
- // Define a temporary file path for the generated barcode image
- string imagePath = Path.Combine(Path.GetTempPath(), "sample_barcode.png");
+ // Define the output path for the generated barcode image.
+ string imagePath = "barcode.png";
- // Generate a QR code barcode with known content
+ // Generate a QR code barcode with the text "StrongQualityTest" and save it as PNG.
using (var generator = new BarcodeGenerator(EncodeTypes.QR, "StrongQualityTest"))
{
- // Save the barcode image to the temporary file
generator.Save(imagePath);
}
- // Verify that the image file was created
+ // Ensure the image file was created before attempting to read it.
if (!File.Exists(imagePath))
{
- Console.WriteLine("Failed to create barcode image.");
+ Console.WriteLine($"Image file not found: {imagePath}");
return;
}
- // Read the barcode from the generated image
+ // Initialize a barcode reader that attempts to decode all supported barcode types.
using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
- // Iterate through all detected barcodes
+ // Iterate through each detected barcode in the image.
foreach (var result in reader.ReadBarCodes())
{
- double readingQuality = result.ReadingQuality;
+ double quality = result.ReadingQuality;
- // Treat ReadingQuality of 100 as strong and accept automatically
- if (readingQuality == 100.0)
+ // Accept the result automatically if the reading quality is perfect (100).
+ if (quality == 100.0)
{
- Console.WriteLine($"Accepted (Strong Quality): {result.CodeText}");
+ Console.WriteLine($"Accepted: {result.CodeText}");
}
else
{
- Console.WriteLine($"Detected (Quality {readingQuality}): {result.CodeText}");
+ Console.WriteLine($"Rejected (ReadingQuality {quality}): {result.CodeText}");
}
}
}
-
- // 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-basics/use-asynchronous-barcodereader-methods-to-read-uploaded-files-while-preserving-ui-responsiveness.cs b/barcode-recognition-basics/use-asynchronous-barcodereader-methods-to-read-uploaded-files-while-preserving-ui-responsiveness.cs
index e9068b4..843ebf9 100644
--- a/barcode-recognition-basics/use-asynchronous-barcodereader-methods-to-read-uploaded-files-while-preserving-ui-responsiveness.cs
+++ b/barcode-recognition-basics/use-asynchronous-barcodereader-methods-to-read-uploaded-files-while-preserving-ui-responsiveness.cs
@@ -1,7 +1,8 @@
-// Title: Asynchronous barcode reading demo
-// Description: Demonstrates using Aspose.BarCode's asynchronous pattern to read a barcode image without blocking the UI thread.
+// Title: Asynchronous barcode reading from an image file
+// Description: Demonstrates generating a Code128 barcode image and reading it asynchronously to keep the UI responsive.
+// Category-Description: This example belongs to the Aspose.BarCode reading category, showcasing how to use BarcodeGenerator to create barcodes and BarCodeReader with async patterns for non‑blocking operations. Developers often need to process uploaded images without freezing the UI, using classes like BarcodeGenerator, BarCodeReader, and DecodeType.
// Prompt: Use asynchronous BarCodeReader methods to read uploaded files while preserving UI responsiveness.
-// Tags: barcode symbology, asynchronous operation, console output, aspose.barcode, barcodereader
+// Tags: code128, read, png, barcodegenerator, barcodereader, async, aspose.barcode
using System;
using System.IO;
@@ -9,49 +10,74 @@
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Sample console application that reads a barcode image asynchronously.
+/// Example program that generates a barcode image and reads it asynchronously.
///
class Program
{
///
- /// Entry point. Generates a sample barcode if needed and reads it asynchronously.
+ /// Entry point of the application. Generates a sample barcode, reads it asynchronously,
+ /// and then cleans up the temporary file.
///
- static async Task Main(string[] args)
+ static async Task Main()
{
- // Path to the barcode image file
- const string imagePath = "sample.png";
+ // ------------------------------------------------------------
+ // Generate a temporary barcode image (Code128) and save as PNG
+ // ------------------------------------------------------------
+ string imagePath = Path.Combine(Path.GetTempPath(), "sample.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
+ {
+ generator.Save(imagePath, BarCodeImageFormat.Png);
+ }
- // Ensure the barcode image exists; generate a sample if missing
- if (!File.Exists(imagePath))
+ // ------------------------------------------------------------
+ // Asynchronously read the barcode from the generated image
+ // ------------------------------------------------------------
+ await ReadBarcodeAsync(imagePath);
+
+ // ------------------------------------------------------------
+ // Clean up the temporary file
+ // ------------------------------------------------------------
+ try
{
- // Create a simple Code128 barcode and save it
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "AsyncDemo"))
+ if (File.Exists(imagePath))
{
- generator.Save(imagePath);
+ File.Delete(imagePath);
}
}
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Failed to delete temporary file: {ex.Message}");
+ }
+ }
- // Asynchronously read barcodes from the image to keep the UI thread responsive
- BarCodeResult[] results = await Task.Run(() =>
+ ///
+ /// Reads barcodes from the specified file path using a background thread to avoid blocking the UI.
+ ///
+ /// Full path to the image file containing barcodes.
+ private static async Task ReadBarcodeAsync(string filePath)
+ {
+ // Verify that the file exists before attempting to read
+ if (!File.Exists(filePath))
+ {
+ Console.WriteLine($"File not found: {filePath}");
+ return;
+ }
+
+ // Run the blocking reading operation on a background thread
+ await Task.Run(() =>
{
- // Initialize the reader for all supported symbologies
- using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
{
- // Perform the synchronous read operation (wrapped in Task.Run for asynchrony)
- return reader.ReadBarCodes();
+ // Iterate through all detected barcodes and output their type and text
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($"Detected Text: {result.CodeText}");
+ }
}
});
-
- // Process and display the detection results
- foreach (var result in results)
- {
- 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();
- }
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/use-barcodereader-to-read-barcode-from-byte-array-and-ensure-detectencoding-correctly-decodes-utf16-content.cs b/barcode-recognition-basics/use-barcodereader-to-read-barcode-from-byte-array-and-ensure-detectencoding-correctly-decodes-utf16-content.cs
index e850825..6fffdca 100644
--- a/barcode-recognition-basics/use-barcodereader-to-read-barcode-from-byte-array-and-ensure-detectencoding-correctly-decodes-utf16-content.cs
+++ b/barcode-recognition-basics/use-barcodereader-to-read-barcode-from-byte-array-and-ensure-detectencoding-correctly-decodes-utf16-content.cs
@@ -1,7 +1,8 @@
// Title: Read QR barcode from byte array with UTF-16 detection
-// Description: Demonstrates generating a QR code containing Cyrillic text, saving it to a byte array, and using BarCodeReader with DetectEncoding to correctly decode UTF‑16 content.
+// Description: Demonstrates using BarCodeReader to decode a QR code stored in a byte array, ensuring DetectEncoding correctly interprets UTF-16 encoded text.
+// Category-Description: This example belongs to the Aspose.BarCode barcode reading category, showcasing how to generate a QR code with Unicode content, store it in memory, and read it back using BarCodeReader. Key API classes include BarcodeGenerator, BarCodeReader, and BarcodeSettings. Typical use cases involve processing barcodes in streams without file I/O, handling multilingual data, and verifying encoding detection. Developers often need to read barcodes from network streams, databases, or in-memory buffers while preserving original character encoding.
// Prompt: Use BarCodeReader to read a barcode from a byte array and ensure DetectEncoding correctly decodes UTF16 content.
-// Tags: qr, barcode, utf16, detectencoding, aspose, csharp
+// Tags: qr, barcode, reading, utf16, encoding, memorystream, aspose.barcode
using System;
using System.IO;
@@ -9,61 +10,59 @@
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing.Imaging;
///
-/// Example program that creates a QR barcode with UTF‑16 encoded text,
-/// reads it from a byte array, and demonstrates the effect of the DetectEncoding setting.
+/// Example program that generates a QR code with UTF-16 encoded text,
+/// stores it in a memory stream, and reads it back using BarCodeReader
+/// with encoding detection enabled.
///
class Program
{
///
- /// Entry point. Generates a QR code, saves it to memory, and reads it back with and without encoding detection.
+ /// Entry point of the example. Generates a QR barcode, reads it from a byte array,
+ /// and verifies that DetectEncoding correctly decodes the original UTF-16 text.
///
static void Main()
{
- // Original Unicode text (contains Cyrillic characters)
+ // Sample text containing Unicode characters (will be encoded as UTF-16)
const string originalText = "Привет";
- // Generate a QR barcode with UTF-16 (Unicode) encoding
+ // Generate a QR barcode with UTF-16 encoded text and save it to a memory stream
+ byte[] barcodeBytes;
using (var generator = new BarcodeGenerator(EncodeTypes.QR))
{
- // Encode the text using UTF-16 (little endian)
+ // Encode the text using UTF-16 (Unicode) encoding
generator.SetCodeText(originalText, Encoding.Unicode);
- // Save the barcode image to a memory stream (PNG format)
using (var ms = new MemoryStream())
{
+ // Save the barcode image as PNG into the memory stream
generator.Save(ms, BarCodeImageFormat.Png);
- byte[] barcodeBytes = ms.ToArray();
+ // Retrieve the underlying byte array for later reading
+ barcodeBytes = ms.ToArray();
+ }
+ }
- // ------------------------------------------------------------
- // Read the barcode from the byte array with DetectEncoding enabled
- // ------------------------------------------------------------
- using (var readStream = new MemoryStream(barcodeBytes))
- using (var reader = new BarCodeReader(readStream, DecodeType.QR))
- {
- // Ensure the engine detects the UTF-16 encoding
- reader.BarcodeSettings.DetectEncoding = true;
+ // Read the barcode from the byte array using BarCodeReader
+ using (var ms = new MemoryStream(barcodeBytes))
+ using (var reader = new BarCodeReader(ms, DecodeType.QR))
+ {
+ // Enable automatic detection of the codetext encoding
+ reader.BarcodeSettings.DetectEncoding = true;
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine("Decoded with DetectEncoding = true: " + result.CodeText);
- }
+ // Iterate through all detected barcodes (only one expected)
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine("Detected CodeText: " + result.CodeText);
+ // Verify that the detected text matches the original UTF-16 text
+ if (result.CodeText == originalText)
+ {
+ Console.WriteLine("Encoding detection succeeded.");
}
-
- // ------------------------------------------------------------
- // Demonstrate decoding without DetectEncoding (should be garbled)
- // ------------------------------------------------------------
- using (var readStream = new MemoryStream(barcodeBytes))
- using (var reader = new BarCodeReader(readStream, DecodeType.QR))
+ else
{
- // Disable automatic encoding detection
- reader.BarcodeSettings.DetectEncoding = false;
-
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine("Decoded with DetectEncoding = false: " + result.CodeText);
- }
+ Console.WriteLine("Encoding detection failed.");
}
}
}
diff --git a/barcode-recognition-basics/use-barcodereader-with-decodetype-set-to-ean13-to-exclusively-detect-european-article-number-barcodes.cs b/barcode-recognition-basics/use-barcodereader-with-decodetype-set-to-ean13-to-exclusively-detect-european-article-number-barcodes.cs
index b28489d..25490bd 100644
--- a/barcode-recognition-basics/use-barcodereader-with-decodetype-set-to-ean13-to-exclusively-detect-european-article-number-barcodes.cs
+++ b/barcode-recognition-basics/use-barcodereader-with-decodetype-set-to-ean13-to-exclusively-detect-european-article-number-barcodes.cs
@@ -1,45 +1,50 @@
-// Title: EAN13 Barcode Generation and Recognition Example
-// Description: Demonstrates generating an EAN13 barcode image and using BarCodeReader with DecodeType set to EAN13 to detect only European Article Number barcodes.
+// Title: Detect EAN13 barcodes using BarCodeReader
+// Description: Demonstrates generating an EAN13 barcode image and reading it back with DecodeType set to EAN13, ensuring only European Article Number symbology is detected.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, showcasing the use of BarcodeGenerator for creating barcodes and BarCodeReader with specific DecodeType filtering. Developers often need to generate barcodes for product labeling and then validate or extract them from images, focusing on particular symbologies such as EAN13 for retail applications.
// Prompt: Use BarCodeReader with DecodeType set to EAN13 to exclusively detect European Article Number barcodes.
-// Tags: barcode symbology, ean13, generation, recognition, aspose.barcode, console
+// Tags: ean13, barcode, generation, recognition, decode, 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 an EAN13 barcode and reads it using configured for EAN13 only.
+/// Demonstrates generating an EAN13 barcode image and reading it using with .
///
class Program
{
///
- /// Entry point. Generates a barcode image, configures the reader, and outputs detected barcode information.
+ /// Entry point. Generates an EAN13 barcode, saves it, and reads it back exclusively as EAN13.
///
static void Main()
{
- // Generate a sample EAN13 barcode image
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.EAN13, "123456789012"))
+ // Define the output file path for the generated barcode image.
+ string imagePath = "ean13.png";
+
+ // Create an EAN13 barcode with a valid 13‑digit value (including checksum) and save it as PNG.
+ using (var generator = new BarcodeGenerator(EncodeTypes.EAN13, "1234567890128"))
{
- using (Bitmap barcodeImage = generator.GenerateBarCodeImage())
- {
- // Initialize the reader and configure it to detect only EAN13 barcodes
- using (BarCodeReader reader = new BarCodeReader())
- {
- // Restrict decoding to EAN13 symbology
- reader.BarCodeReadType = DecodeType.EAN13;
+ generator.Save(imagePath, BarCodeImageFormat.Png);
+ }
- // Provide the generated image to the reader
- reader.SetBarCodeImage(barcodeImage);
+ // Ensure the barcode image was successfully created before attempting to read it.
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine($"Error: Barcode image '{imagePath}' was not found.");
+ return;
+ }
- // Perform recognition and output results
- foreach (BarCodeResult result in reader.ReadBarCodes())
- {
- Console.WriteLine("Detected Type: " + result.CodeTypeName);
- Console.WriteLine("Detected CodeText: " + result.CodeText);
- }
- }
+ // Initialize a reader that is configured to decode only EAN13 symbology.
+ using (var reader = new BarCodeReader(imagePath, DecodeType.EAN13))
+ {
+ // Iterate through all detected barcodes (expected to be a single EAN13 entry).
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($"Code Text: {result.CodeText}");
}
}
}
diff --git a/barcode-recognition-basics/validate-that-foundbarcodes-collection-contains-expected-symbology-types-after-processing-mixed-barcode-image.cs b/barcode-recognition-basics/validate-that-foundbarcodes-collection-contains-expected-symbology-types-after-processing-mixed-barcode-image.cs
index 01628e6..882f87b 100644
--- a/barcode-recognition-basics/validate-that-foundbarcodes-collection-contains-expected-symbology-types-after-processing-mixed-barcode-image.cs
+++ b/barcode-recognition-basics/validate-that-foundbarcodes-collection-contains-expected-symbology-types-after-processing-mixed-barcode-image.cs
@@ -1,7 +1,8 @@
-// Title: Mixed Barcode Generation and Validation Example
-// Description: Generates several barcode types, combines them into a single image, then validates that the recognized barcodes match the expected symbology types.
+// Title: Validate detection of multiple barcode symbologies in a combined image
+// Description: Demonstrates generating several barcode types, merging them into one image, and verifying that the Aspose.BarCode reader correctly identifies each symbology.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes, Bitmap handling with Aspose.Drawing, and BarCodeReader for decoding. Developers often need to batch‑process mixed barcode images, validate detection accuracy, or build composite scans; this snippet illustrates those common tasks and the key API classes involved.
// Prompt: Validate that FoundBarCodes collection contains expected symbology types after processing a mixed barcode image.
-// Tags: barcode symbology, generation, recognition, validation, aspnet barcoderecognition, aspnet barcodelibrary
+// Tags: barcode, symbology, generation, recognition, mixed image, aspose.barcode, csharp, aspnet
using System;
using System.Collections.Generic;
@@ -13,106 +14,130 @@
using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating multiple barcode types, combining them into one image, and validating detection of each symbology.
+/// Generates a set of different barcode types, combines them into a single image,
+/// and validates that each expected symbology is detected by the BarCodeReader.
///
class Program
{
///
- /// Entry point. Generates barcodes, creates a composite image, reads it back, and validates expected symbology types.
+ /// Entry point of the example. Performs barcode generation, image composition,
+ /// recognition, and validation of detected symbology types.
///
static void Main()
{
- // Define a set of barcode samples with their encode types and corresponding text.
- var samples = new List<(BaseEncodeType EncodeType, string CodeText)>
+ // Define sample barcodes to generate (type and associated text)
+ var samples = new List<(BaseEncodeType type, string text)>
{
- (EncodeTypes.Code128, "CODE128_SAMPLE"),
- (EncodeTypes.QR, "QR_SAMPLE"),
- (EncodeTypes.DataMatrix, "DM_SAMPLE"),
- (EncodeTypes.Pdf417, "PDF417_SAMPLE"),
- (EncodeTypes.EAN13, "1234567890128")
+ (EncodeTypes.Code128, "CODE128-123"),
+ (EncodeTypes.QR, "https://example.com"),
+ (EncodeTypes.DataMatrix, "DM-456"),
+ (EncodeTypes.Pdf417, "PDF417-789"),
+ (EncodeTypes.Aztec, "AZTEC-ABC")
};
- // Lists to hold generated bitmap images and the expected symbology type names.
- var bitmaps = new List();
- var expectedTypes = new List();
+ // Containers for generated bitmap images and their dimensions
+ var barcodeImages = new List();
+ var widths = new List();
+ var heights = new List();
- // Generate each barcode image and record its expected type.
- foreach (var sample in samples)
+ // Generate individual barcode images using default settings
+ foreach (var (type, text) in samples)
{
- using (BarcodeGenerator generator = new BarcodeGenerator(sample.EncodeType, sample.CodeText))
+ using (var generator = new BarcodeGenerator(type, text))
{
- expectedTypes.Add(generator.BarcodeType.TypeName);
Bitmap bmp = generator.GenerateBarCodeImage();
- bitmaps.Add(bmp);
+ barcodeImages.Add(bmp);
+ widths.Add(bmp.Width);
+ heights.Add(bmp.Height);
}
}
- // Determine canvas size needed to place all barcodes vertically with spacing.
- int canvasWidth = 0;
- int canvasHeight = 0;
- int spacing = 10;
+ // Calculate combined image size for a horizontal layout
+ int totalWidth = 0;
+ int maxHeight = 0;
+ foreach (int w in widths) totalWidth += w;
+ foreach (int h in heights) if (h > maxHeight) maxHeight = h;
- foreach (var bmp in bitmaps)
+ // Create a new bitmap that will hold all barcodes side by side
+ using (var combined = new Bitmap(totalWidth, maxHeight))
{
- if (bmp.Width > canvasWidth) canvasWidth = bmp.Width;
- canvasHeight += bmp.Height + spacing;
- }
-
- // Create a combined image and draw each barcode bitmap onto it.
- using (Bitmap combined = new Bitmap(canvasWidth, canvasHeight))
- {
- using (Graphics graphics = Graphics.FromImage(combined))
+ using (var graphics = Graphics.FromImage(combined))
{
+ // Fill background with white
graphics.Clear(Aspose.Drawing.Color.White);
- int yOffset = 0;
- foreach (var bmp in bitmaps)
+ int offsetX = 0;
+
+ // Draw each barcode image onto the combined bitmap
+ for (int i = 0; i < barcodeImages.Count; i++)
{
- graphics.DrawImage(bmp, 0, yOffset, bmp.Width, bmp.Height);
- yOffset += bmp.Height + spacing;
- bmp.Dispose(); // Release individual bitmap resources.
+ Bitmap src = barcodeImages[i];
+ graphics.DrawImage(src, offsetX, 0, src.Width, src.Height);
+ offsetX += src.Width;
+ src.Dispose(); // Dispose individual bitmap after it has been drawn
}
}
- // Save the combined image to disk.
- string imagePath = "mixed_barcodes.png";
- combined.Save(imagePath, ImageFormat.Png);
- }
-
- // Verify that the combined image file was created successfully.
- string combinedImagePath = "mixed_barcodes.png";
- if (!File.Exists(combinedImagePath))
- {
- Console.WriteLine($"Error: Image file '{combinedImagePath}' not found.");
- return;
- }
-
- // Read all barcodes from the combined image using Aspose.BarCode.
- using (BarCodeReader reader = new BarCodeReader(combinedImagePath, DecodeType.AllSupportedTypes))
- {
- BarCodeResult[] results = reader.ReadBarCodes();
+ // Save the combined image to a temporary file for recognition
+ string tempPath = Path.Combine(Path.GetTempPath(), "mixed_barcodes.png");
+ combined.Save(tempPath, ImageFormat.Png);
- // Collect the types of barcodes that were actually detected.
- var foundTypes = new HashSet(StringComparer.OrdinalIgnoreCase);
- foreach (var result in results)
+ // Build a set of expected symbology type names from the generated samples
+ var expectedTypes = new HashSet();
+ foreach (var (type, _) in samples)
{
- foundTypes.Add(result.CodeTypeName);
- Console.WriteLine($"Detected: {result.CodeTypeName} - Text: {result.CodeText}");
+ expectedTypes.Add(type.TypeName);
}
- // Output validation results comparing expected vs. found symbology types.
- Console.WriteLine();
- Console.WriteLine("Validation Results:");
- foreach (var expected in expectedTypes)
+ // Initialize the reader to decode all supported barcode types
+ using (var reader = new BarCodeReader(tempPath, DecodeType.AllSupportedTypes))
{
- if (foundTypes.Contains(expected))
+ // Perform recognition on the combined image
+ reader.ReadBarCodes();
+
+ // Collect the symbology types that were actually found
+ var foundTypes = new HashSet();
+ foreach (var result in reader.FoundBarCodes)
+ {
+ if (result?.CodeType != null)
+ {
+ foundTypes.Add(result.CodeType.TypeName);
+ }
+ }
+
+ // Verify that each expected type is present in the found collection
+ bool allFound = true;
+ foreach (string expected in expectedTypes)
+ {
+ if (!foundTypes.Contains(expected))
+ {
+ Console.WriteLine($"Missing expected symbology: {expected}");
+ allFound = false;
+ }
+ }
+
+ // Output validation result
+ if (allFound)
{
- Console.WriteLine($"PASS: Expected symbology '{expected}' was found.");
+ Console.WriteLine("All expected symbology types were successfully detected.");
}
else
{
- Console.WriteLine($"FAIL: Expected symbology '{expected}' was NOT found.");
+ Console.WriteLine("Some expected symbology types were not detected.");
+ }
+ }
+
+ // Attempt to delete the temporary file; ignore any errors
+ try
+ {
+ if (File.Exists(tempPath))
+ {
+ File.Delete(tempPath);
}
}
+ catch
+ {
+ // Suppress cleanup exceptions
+ }
}
}
}
\ No newline at end of file
diff --git a/barcode-recognition-basics/validate-that-readingquality-reaches-100-only-when-barcode-image-meets-minimum-resolution-threshold.cs b/barcode-recognition-basics/validate-that-readingquality-reaches-100-only-when-barcode-image-meets-minimum-resolution-threshold.cs
index f4a063e..fa5aacf 100644
--- a/barcode-recognition-basics/validate-that-readingquality-reaches-100-only-when-barcode-image-meets-minimum-resolution-threshold.cs
+++ b/barcode-recognition-basics/validate-that-readingquality-reaches-100-only-when-barcode-image-meets-minimum-resolution-threshold.cs
@@ -1,77 +1,116 @@
-// Title: Validate ReadingQuality based on image resolution
-// Description: Demonstrates generating a QR barcode at a specific DPI, then reading it to ensure ReadingQuality reaches 100 only when the image meets the minimum resolution.
+// Title: Validate ReadingQuality based on barcode image resolution
+// Description: Demonstrates generating low‑ and high‑resolution Code128 barcodes and checking that the ReadingQuality reaches 100 only when the image meets a minimum DPI.
+// Category-Description: This example belongs to the Aspose.BarCode image generation and recognition category. It shows how to use BarcodeGenerator to set image resolution and BarCodeReader to evaluate ReadingQuality, a metric useful for assessing scan reliability. Developers working with barcode scanning often need to ensure sufficient image DPI to achieve optimal recognition quality.
// Prompt: Validate that ReadingQuality reaches 100 only when the barcode image meets a minimum resolution threshold.
-// Tags: qr, barcode, readingquality, resolution, aspose.barcode, image-processing
+// Tags: code128, generation, recognition, readingquality, resolution, 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 QR barcode, checks its image resolution,
-/// and validates that the ReadingQuality reported by the reader is 100 only
-/// when the image meets a defined minimum DPI threshold.
+/// Generates barcode images at different resolutions and validates that
+/// the ReadingQuality reported by BarCodeReader reaches 100
+/// only when the image DPI meets the defined minimum threshold.
///
class Program
{
+ // Minimum DPI required for a ReadingQuality of 100
+ const float MinResolutionDpi = 200f;
+
///
- /// Entry point of the application.
+ /// Entry point of the example. Creates low‑ and high‑resolution barcodes,
+ /// evaluates their reading quality, and cleans up temporary files.
///
static void Main()
{
- const int minResolutionDpi = 300;
- const string barcodePath = "barcode.png";
+ // Paths for temporary barcode images
+ string lowResPath = "barcode_low.png";
+ string highResPath = "barcode_high.png";
- // Generate a QR barcode with the specified resolution (DPI)
- using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Test123"))
- {
- generator.Parameters.Resolution = minResolutionDpi;
- generator.Save(barcodePath, BarCodeImageFormat.Png);
- }
+ // Generate a low‑resolution barcode (100 DPI)
+ GenerateBarcode("1234567890", 100f, lowResPath);
+
+ // Generate a high‑resolution barcode (300 DPI)
+ GenerateBarcode("1234567890", 300f, highResPath);
+
+ // Evaluate low‑resolution image
+ EvaluateBarcode(lowResPath, "Low resolution");
+
+ // Evaluate high‑resolution image
+ EvaluateBarcode(highResPath, "High resolution");
- // Verify that the image file was created successfully
- if (!File.Exists(barcodePath))
+ // Clean up temporary files
+ try { if (File.Exists(lowResPath)) File.Delete(lowResPath); } catch { }
+ try { if (File.Exists(highResPath)) File.Delete(highResPath); } catch { }
+ }
+
+ ///
+ /// Generates a barcode image with the specified DPI resolution.
+ ///
+ /// The text to encode in the barcode.
+ /// Desired image resolution in dots per inch.
+ /// File path where the image will be saved.
+ static void GenerateBarcode(string codeText, float resolutionDpi, string outputPath)
+ {
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
{
- Console.WriteLine("Barcode image was not created.");
- return;
+ // Set image resolution (dots per inch)
+ generator.Parameters.Resolution = resolutionDpi;
+
+ // Keep image size reasonable
+ generator.Parameters.ImageWidth.Point = 300f;
+ generator.Parameters.ImageHeight.Point = 100f;
+
+ // Save the generated image to the specified path
+ generator.Save(outputPath);
}
+ }
- // Load the image to inspect its horizontal and vertical DPI values
- float imageHorizontalDpi;
- float imageVerticalDpi;
- using (var image = Image.FromFile(barcodePath))
+ ///
+ /// Reads a barcode image, prints its inferred resolution and ReadingQuality,
+ /// and validates that full quality (100) is reported only when the resolution
+ /// meets or exceeds .
+ ///
+ /// Path to the barcode image file.
+ /// Label used in console output to identify the test case.
+ static void EvaluateBarcode(string imagePath, string label)
+ {
+ if (!File.Exists(imagePath))
{
- imageHorizontalDpi = image.HorizontalResolution;
- imageVerticalDpi = image.VerticalResolution;
+ Console.WriteLine($"{label}: Image file not found.");
+ return;
}
- // Read the barcode from the image and evaluate the ReadingQuality metric
- using (var reader = new BarCodeReader(barcodePath, DecodeType.QR))
+ using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
+ // Read all barcodes present in the image
foreach (var result in reader.ReadBarCodes())
{
- double readingQuality = result.ReadingQuality;
- Console.WriteLine($"ReadingQuality: {readingQuality}");
- Console.WriteLine($"Image Resolution: {imageHorizontalDpi} DPI (H), {imageVerticalDpi} DPI (V)");
+ // ReadingQuality is a double representing a percentage
+ double quality = result.ReadingQuality;
+
+ // The reader does not expose the source resolution directly,
+ // so we infer it from the file name for demonstration purposes.
+ float usedResolution = imagePath.Contains("high") ? 300f : 100f;
+
+ bool meetsThreshold = usedResolution >= MinResolutionDpi;
+ bool qualityIsFull = Math.Abs(quality - 100.0) < 0.0001;
- // Validate that ReadingQuality is 100 only when both DPI dimensions meet the minimum threshold
- if (readingQuality == 100.0)
+ Console.WriteLine($"{label}: Used DPI = {usedResolution}, ReadingQuality = {quality}");
+
+ if (meetsThreshold && qualityIsFull)
+ {
+ Console.WriteLine($"{label}: PASS – High resolution yields full quality.");
+ }
+ else if (!meetsThreshold && !qualityIsFull)
{
- if (imageHorizontalDpi >= minResolutionDpi && imageVerticalDpi >= minResolutionDpi)
- {
- Console.WriteLine("Validation passed: ReadingQuality is 100 and image meets the minimum resolution.");
- }
- else
- {
- Console.WriteLine("Validation failed: ReadingQuality is 100 but image resolution is below the required threshold.");
- }
+ Console.WriteLine($"{label}: PASS – Low resolution yields reduced quality.");
}
else
{
- Console.WriteLine("ReadingQuality is below 100; no resolution validation required.");
+ Console.WriteLine($"{label}: FAIL – Unexpected quality for the given resolution.");
}
}
}
diff --git a/barcode-recognition-basics/write-unit-test-confirming-manual-decoding-using-encodingutf8-produces-identical-results-to-automatic-detection-for-utf8.cs b/barcode-recognition-basics/write-unit-test-confirming-manual-decoding-using-encodingutf8-produces-identical-results-to-automatic-detection-for-utf8.cs
index 7c1d3f4..3106916 100644
--- a/barcode-recognition-basics/write-unit-test-confirming-manual-decoding-using-encodingutf8-produces-identical-results-to-automatic-detection-for-utf8.cs
+++ b/barcode-recognition-basics/write-unit-test-confirming-manual-decoding-using-encodingutf8-produces-identical-results-to-automatic-detection-for-utf8.cs
@@ -1,77 +1,92 @@
-// Title: UTF-8 Barcode Generation and Decoding Verification
-// Description: Demonstrates generating a QR code with UTF-8 text and verifying that manual UTF-8 decoding matches automatic detection.
+// Title: UTF-8 QR Barcode Encoding and Decoding Comparison
+// Description: Demonstrates generating a QR barcode with UTF-8 text and verifying that automatic encoding detection matches manual UTF-8 decoding.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator for creating QR codes, BarCodeReader for decoding, and the DetectEncoding setting for automatic Unicode handling. Developers working with multilingual data often need to ensure that generated barcodes preserve character encoding and that decoding yields the original text, making this pattern a common requirement in internationalized applications.
// Prompt: Write a unit test confirming manual decoding using Encoding.UTF8 produces identical results to automatic detection for UTF8 barcodes.
-// Tags: qr, encoding, utf8, barcode, generation, recognition, unit-test
+// Tags: qr,utf-8,encoding,barcode,generation,recognition,unit-test
using System;
using System.IO;
using System.Text;
+using System.Linq;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Example program that creates a QR barcode containing UTF‑8 text,
-/// then reads it back using both automatic encoding detection and manual UTF‑8 decoding
-/// to confirm the results are identical.
+/// Generates a QR barcode containing UTF-8 text and validates that automatic encoding detection
+/// yields the same result as manual UTF-8 decoding.
///
class Program
{
///
- /// Entry point of the example. Generates a QR code, reads it, and validates decoding.
+ /// Entry point of the example. Performs barcode generation, automatic detection, manual decoding,
+ /// and prints the verification outcome.
///
static void Main()
{
- // Sample Unicode text (UTF‑8) that will be encoded into the barcode.
- const string originalText = "Привет, мир!";
+ // Sample UTF-8 text (Cyrillic characters)
+ const string originalText = "Привет мир";
- // Create a QR barcode generator and set the code text with explicit UTF‑8 encoding.
+ // Create a QR barcode generator
using (var generator = new BarcodeGenerator(EncodeTypes.QR))
{
+ // Encode the text using UTF-8 (adds BOM if needed)
generator.SetCodeText(originalText, Encoding.UTF8);
- // Save the generated barcode image to a memory stream (PNG format).
+ // Save the barcode to a memory stream in PNG format
using (var ms = new MemoryStream())
{
generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for reading.
+ ms.Position = 0; // Reset stream position for reading
- // Initialize a barcode reader for QR codes with automatic encoding detection enabled.
- using (var reader = new BarCodeReader(ms, DecodeType.QR))
+ // ---------- Automatic detection ----------
+ using (var readerAuto = new BarCodeReader(ms, DecodeType.QR))
{
- reader.BarcodeSettings.DetectEncoding = true;
+ // Enable automatic detection of Unicode encoding
+ readerAuto.BarcodeSettings.DetectEncoding = true;
- // Read all barcodes found in the stream.
- var results = reader.ReadBarCodes();
-
- // If no barcode was detected, report and exit.
- if (results.Length == 0)
+ // Read the first barcode found
+ var resultAuto = readerAuto.ReadBarCodes().FirstOrDefault();
+ if (resultAuto == null)
{
- Console.WriteLine("No barcode detected.");
+ Console.WriteLine("Automatic detection failed: no barcode found.");
return;
}
- // Retrieve the first (and only) result.
- var result = results[0];
-
- // Automatic detection returns the decoded text directly.
- string autoDecoded = result.CodeText;
+ // Retrieve the automatically decoded text
+ string autoDecoded = resultAuto.CodeText;
- // Manual decoding forces UTF‑8 interpretation of the raw bytes.
- string manualDecoded = result.GetCodeText(Encoding.UTF8);
+ // Reset stream for the second read
+ ms.Position = 0;
- // Verify that both decoding methods produce identical output
- // and that they match the original text.
- if (autoDecoded == manualDecoded && autoDecoded == originalText)
- {
- Console.WriteLine("Success: Automatic and manual UTF‑8 decoding match.");
- Console.WriteLine($"Decoded text: {autoDecoded}");
- }
- else
+ // ---------- Manual decoding ----------
+ using (var readerManual = new BarCodeReader(ms, DecodeType.QR))
{
- Console.WriteLine("Failure: Decoding results differ.");
+ // Disable automatic detection to force manual decoding
+ readerManual.BarcodeSettings.DetectEncoding = false;
+
+ // Read the first barcode found
+ var resultManual = readerManual.ReadBarCodes().FirstOrDefault();
+ if (resultManual == null)
+ {
+ Console.WriteLine("Manual decoding failed: no barcode found.");
+ return;
+ }
+
+ // Manually decode using UTF-8
+ string manualDecoded = resultManual.GetCodeText(Encoding.UTF8);
+
+ // Verify that both methods produce the same result and match the original text
+ bool isSuccess = autoDecoded == manualDecoded && autoDecoded == originalText;
+
+ // Output the results
Console.WriteLine($"Original text : {originalText}");
- Console.WriteLine($"Auto decoded : {autoDecoded}");
- Console.WriteLine($"Manual decoded (UTF‑8) : {manualDecoded}");
+ Console.WriteLine($"Auto decoded : {autoDecoded}");
+ Console.WriteLine($"Manual decoded: {manualDecoded}");
+ Console.WriteLine(isSuccess
+ ? "Test passed: automatic detection matches manual UTF-8 decoding."
+ : "Test failed: results differ.");
}
}
}