diff --git a/barcode-reading-properties/access-pdf417-extended-parameters-to-check-if-barcode-is-linked-to-another-segment.cs b/barcode-reading-properties/access-pdf417-extended-parameters-to-check-if-barcode-is-linked-to-another-segment.cs
index e4efa2f..1abb742 100644
--- a/barcode-reading-properties/access-pdf417-extended-parameters-to-check-if-barcode-is-linked-to-another-segment.cs
+++ b/barcode-reading-properties/access-pdf417-extended-parameters-to-check-if-barcode-is-linked-to-another-segment.cs
@@ -1,7 +1,8 @@
-// Title: PDF417 barcode generation and linked segment detection
-// Description: Demonstrates generating a PDF417 barcode with the IsLinked flag and reading the flag via extended parameters.
+// Title: Access PDF417 Extended Parameters to Determine Linkage
+// Description: Demonstrates how to set and read the IsLinked property of a PDF417 barcode using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode PDF417 barcode manipulation category, showcasing the use of BarcodeGenerator, BarCodeReader, and extended PDF417 parameters. Developers often need to control and verify segment linking for multi‑segment PDF417 codes in document processing and scanning solutions.
// Prompt: Access PDF417 extended parameters to check if the barcode is linked to another segment.
-// Tags: pdf417, barcode, generation, recognition, extended-parameters, islinked
+// Tags: pdf417, extended-parameters, islinked, barcode-generation, barcode-recognition, aspnet, csharp
using System;
using System.IO;
@@ -10,49 +11,49 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that generates a PDF417 barcode with the IsLinked flag and reads the flag using extended parameters.
+/// Example program that creates a PDF417 barcode with the IsLinked flag set,
+/// saves it as an image, and then reads the barcode to verify the flag using
+/// Aspose.BarCode's extended PDF417 parameters.
///
class Program
{
///
- /// Entry point. Generates a PDF417 barcode, saves it, and reads back the IsLinked property.
+ /// Entry point of the example. Generates a PDF417 barcode, saves it,
+ /// and reads back the IsLinked property from the extended parameters.
///
static void Main()
{
- // Define the text to encode in the barcode
- const string codeText = "Sample PDF417 Text";
+ // Define the output file path for the generated barcode image.
+ string outputPath = "pdf417.png";
- // Determine the output file path for the generated barcode image
- string outputPath = Path.Combine(Environment.CurrentDirectory, "pdf417.png");
-
- // Generate a PDF417 barcode and set the IsLinked flag to true
- using (var generator = new BarcodeGenerator(EncodeTypes.Pdf417, codeText))
+ // Create a PDF417 barcode generator with sample text.
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Sample PDF417 Text"))
{
- // Enable linked mode for PDF417
+ // Enable the IsLinked flag to indicate this barcode is linked to another segment.
generator.Parameters.Barcode.Pdf417.IsLinked = true;
- // Save the generated barcode as a PNG image
+ // Save the generated barcode as a PNG image.
generator.Save(outputPath, BarCodeImageFormat.Png);
}
- // Verify that the barcode image file was successfully created
+ // Verify that the barcode image was successfully created.
if (!File.Exists(outputPath))
{
- Console.WriteLine("Failed to create barcode image.");
+ Console.WriteLine("Failed to create the barcode image.");
return;
}
- // Initialize a reader to decode the PDF417 barcode from the saved image
- using (var reader = new BarCodeReader(outputPath, DecodeType.Pdf417))
+ // Initialize a barcode reader for PDF417 type to read the saved image.
+ using (BarCodeReader reader = new BarCodeReader(outputPath, DecodeType.Pdf417))
{
- // Iterate through all detected barcode results
+ // Iterate through all detected barcode results.
foreach (BarCodeResult result in reader.ReadBarCodes())
{
- // Output the decoded text
- Console.WriteLine($"CodeText: {result.CodeText}");
+ // Retrieve the IsLinked flag from the extended PDF417 parameters.
+ bool isLinked = result.Extended.Pdf417.IsLinked;
- // Output the IsLinked flag from the extended PDF417 parameters
- Console.WriteLine($"IsLinked: {result.Extended.Pdf417.IsLinked}");
+ // Output the flag value to the console.
+ Console.WriteLine($"IsLinked: {isLinked}");
}
}
}
diff --git a/barcode-reading-properties/adjust-dpi-settings-when-loading-images-to-ensure-accurate-barcode-region-detection.cs b/barcode-reading-properties/adjust-dpi-settings-when-loading-images-to-ensure-accurate-barcode-region-detection.cs
index 51f09a9..e97c6b7 100644
--- a/barcode-reading-properties/adjust-dpi-settings-when-loading-images-to-ensure-accurate-barcode-region-detection.cs
+++ b/barcode-reading-properties/adjust-dpi-settings-when-loading-images-to-ensure-accurate-barcode-region-detection.cs
@@ -1,66 +1,61 @@
-// Title: Adjust DPI for Accurate Barcode Region Detection
-// Description: Demonstrates generating a Code128 barcode, adjusting image DPI, and recognizing the barcode with region details.
+// Title: Adjust DPI Settings for Accurate Barcode Detection
+// Description: Demonstrates how to set and adjust DPI when generating and loading a barcode image to ensure correct region detection.
+// Category-Description: This example belongs to the Aspose.BarCode image processing category, illustrating the use of BarcodeGenerator, Bitmap, and BarCodeReader classes. It shows typical scenarios where developers need to control image resolution for reliable barcode recognition, such as scanning high‑resolution documents or preparing images for OCR pipelines.
// Prompt: Adjust DPI settings when loading images to ensure accurate barcode region detection.
-// Tags: barcode, code128, dpi, region detection, generation, recognition, aspose.barcode, aspose.drawing
+// Tags: barcode, dpi, resolution, cod128, generation, recognition, aspose.barcode, aspose.drawing
using System;
using System.IO;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Example program that generates a barcode, adjusts image DPI, and reads the barcode region.
+/// Demonstrates adjusting DPI settings when loading a barcode image to ensure accurate detection of barcode regions.
///
class Program
{
///
- /// Entry point. Generates a barcode image, sets its DPI, and reads barcode information.
+ /// Entry point of the example. Generates a high‑resolution barcode, adjusts DPI on load, and reads the barcode.
///
static void Main()
{
- // Define the file path for the generated barcode image
- string imagePath = "sample.png";
-
- // ------------------------------------------------------------
- // Generate a simple Code128 barcode and save it to disk
- // ------------------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
- {
- // Optional: set generation resolution (DPI) if needed
- generator.Parameters.Resolution = 96;
- generator.Save(imagePath);
- }
-
- // Verify that the image file was created successfully
- if (!File.Exists(imagePath))
- {
- Console.WriteLine($"Error: File not found - {imagePath}");
- return;
- }
-
- // ------------------------------------------------------------
- // Load the image, adjust its DPI, and perform barcode recognition
- // ------------------------------------------------------------
- using (var bitmap = new Bitmap(imagePath))
+ // Generate a sample barcode image with a high resolution (300 DPI)
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- // Adjust DPI to 300x300 for more accurate region detection
- bitmap.SetResolution(300f, 300f);
+ // Set the generation resolution (DPI)
+ generator.Parameters.Resolution = 300;
- // Initialize the reader to detect all supported barcode types
- using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
+ // Save the generated barcode to a memory stream in PNG format
+ using (var ms = new MemoryStream())
{
- // Iterate through all detected barcodes
- foreach (var result in reader.ReadBarCodes())
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0; // Reset stream position for reading
+
+ // Load the image from the memory stream into a Bitmap
+ using (var bitmap = new Bitmap(ms))
{
- // Retrieve the detected barcode region (rectangle)
- var region = result.Region.Rectangle;
+ // Adjust DPI after loading to match the generation DPI
+ bitmap.SetResolution(300f, 300f);
+
+ // Initialize the barcode reader
+ using (var reader = new BarCodeReader())
+ {
+ // Provide the bitmap to the reader
+ reader.SetBarCodeImage(bitmap);
+
+ // Iterate through all detected barcodes
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
+ Console.WriteLine($"Code Text: {result.CodeText}");
- // Output barcode details and region coordinates
- Console.WriteLine($"Detected Barcode:");
- Console.WriteLine($" Type: {result.CodeTypeName}");
- Console.WriteLine($" Text: {result.CodeText}");
- Console.WriteLine($" Region - X: {region.X}, Y: {region.Y}, Width: {region.Width}, Height: {region.Height}");
+ // Output the location and size of the detected barcode region
+ var rect = result.Region.Rectangle;
+ Console.WriteLine($"Region - X:{rect.X}, Y:{rect.Y}, Width:{rect.Width}, Height:{rect.Height}");
+ }
+ }
}
}
}
diff --git a/barcode-reading-properties/batch-process-folder-of-images-to-extract-barcode-metadata-and-write-results-to-csv.cs b/barcode-reading-properties/batch-process-folder-of-images-to-extract-barcode-metadata-and-write-results-to-csv.cs
index bc92bec..429a7f1 100644
--- a/barcode-reading-properties/batch-process-folder-of-images-to-extract-barcode-metadata-and-write-results-to-csv.cs
+++ b/barcode-reading-properties/batch-process-folder-of-images-to-extract-barcode-metadata-and-write-results-to-csv.cs
@@ -1,111 +1,134 @@
-// Title: Batch Barcode Extraction to CSV
-// Description: Processes all images in a folder, reads any barcodes present, and writes their metadata to a CSV file.
+// Title: Batch barcode extraction from images to CSV
+// Description: Demonstrates how to scan a folder of image files, read all supported barcodes, and write their metadata to a CSV file.
+// Category-Description: This example belongs to the Aspose.BarCode batch processing category, illustrating the use of BarCodeReader for bulk barcode recognition, BarcodeGenerator for creating sample images, and standard .NET I/O for result export. Developers often need to automate barcode scanning across multiple files and store results in a structured format such as CSV for reporting or downstream processing.
// Prompt: Batch process a folder of images to extract barcode metadata and write results to CSV.
-// Tags: barcode, extraction, csv, batch, aspose.barcode, aspose.drawing
+// Tags: barcode symbology, batch processing, csv output, aspose.barcode, barcodereader, barcodegenerator
using System;
using System.IO;
using System.Text;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Demonstrates how to batch‑process a directory of images, extract barcode information,
-/// and export the results to a CSV file using Aspose.BarCode.
+/// Demonstrates batch processing of image files to extract barcode metadata and export results to a CSV file.
///
class Program
{
///
- /// Entry point of the application.
- /// Accepts an optional folder path argument; otherwise defaults to a folder named "Images".
- /// Scans supported image files, reads any barcodes, and writes details to a CSV file.
+ /// Entry point of the example. Generates sample barcodes, scans each image, and writes detection details to a CSV file.
///
- /// Command‑line arguments; first argument may specify the folder to process.
- static void Main(string[] args)
+ static void Main()
{
- // Determine the folder to process. Use argument if provided, otherwise default to "Images".
- string folderPath = args.Length > 0 ? args[0] : "Images";
+ // Define working directories and CSV output path
+ string baseDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ string csvPath = Path.Combine(Directory.GetCurrentDirectory(), "barcode_results.csv");
- // Verify that the target folder exists.
- if (!Directory.Exists(folderPath))
+ // Ensure the barcode folder exists
+ if (!Directory.Exists(baseDir))
{
- Console.WriteLine($"Folder not found: {folderPath}");
- return;
+ Directory.CreateDirectory(baseDir);
}
- // Prepare CSV output file path inside the target folder.
- string csvPath = Path.Combine(folderPath, "barcode_results.csv");
-
- // Open a StreamWriter for the CSV file (UTF‑8 encoding, overwrite if exists).
- using (var csvWriter = new StreamWriter(csvPath, false, Encoding.UTF8))
+ // Remove any existing CSV file to start fresh
+ if (File.Exists(csvPath))
{
- // Write CSV header line.
- csvWriter.WriteLine("FileName,CodeType,CodeText,Confidence,ReadingQuality,RegionX,RegionY,RegionWidth,RegionHeight");
+ File.Delete(csvPath);
+ }
- // Define supported image file extensions.
- string[] extensions = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff" };
+ // Generate a few sample barcode images (self‑contained example)
+ GenerateSampleBarcodes(baseDir);
- // Retrieve all files in the folder (filtering later by extension).
- var imageFiles = Directory.GetFiles(folderPath);
+ // Write CSV header line
+ using (var writer = new StreamWriter(csvPath, false, Encoding.UTF8))
+ {
+ writer.WriteLine("FileName,CodeType,CodeText,RegionX,RegionY,RegionWidth,RegionHeight");
+ }
- // Iterate over each file in the directory.
- foreach (var file in imageFiles)
- {
- // Skip files that do not have a supported image extension.
- if (Array.IndexOf(extensions, Path.GetExtension(file).ToLowerInvariant()) < 0)
- continue;
+ // Define file patterns to search for supported image types
+ string[] patterns = new[] { "*.png", "*.jpg", "*.bmp" };
- // Ensure the file still exists before processing.
- if (!File.Exists(file))
+ // Iterate over each pattern and process matching files
+ foreach (string pattern in patterns)
+ {
+ foreach (string filePath in Directory.GetFiles(baseDir, pattern))
+ {
+ // Verify the file still exists before processing
+ if (!File.Exists(filePath))
{
- Console.WriteLine($"File not found (skipped): {file}");
+ Console.WriteLine($"File not found: {filePath}");
continue;
}
- // Load the image using Aspose.Drawing.Bitmap.
- using (var bitmap = new Bitmap(file))
+ // Use BarCodeReader to detect all supported barcode types in the image
+ using (BarCodeReader reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
{
- // Initialize a barcode reader that attempts to decode all supported types.
- using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
+ foreach (var result in reader.ReadBarCodes())
{
- // Read all barcodes found in the current image.
- foreach (var result in reader.ReadBarCodes())
- {
- // Extract the bounding rectangle of the detected barcode region.
- var rect = result.Region.Rectangle;
-
- // Build a CSV line with the required fields.
- var line = new StringBuilder();
- line.Append(Path.GetFileName(file));
- line.Append(',');
- line.Append(result.CodeTypeName);
- line.Append(',');
- // Replace commas in the code text to avoid CSV column misalignment.
- line.Append(result.CodeText?.Replace(",", " "));
- line.Append(',');
- line.Append(result.Confidence);
- line.Append(',');
- line.Append(result.ReadingQuality);
- line.Append(',');
- line.Append(rect.X);
- line.Append(',');
- line.Append(rect.Y);
- line.Append(',');
- line.Append(rect.Width);
- line.Append(',');
- line.Append(rect.Height);
-
- // Write the constructed line to the CSV file.
- csvWriter.WriteLine(line.ToString());
- }
+ // Extract the bounding rectangle of the detected barcode region
+ var rect = result.Region.Rectangle;
+
+ // Build a CSV line with escaped text fields
+ string line = string.Format(
+ "{0},{1},{2},{3},{4},{5},{6}",
+ Path.GetFileName(filePath),
+ result.CodeType,
+ EscapeCsv(result.CodeText),
+ rect.X,
+ rect.Y,
+ rect.Width,
+ rect.Height);
+
+ // Append the line to the CSV file
+ File.AppendAllText(csvPath, line + Environment.NewLine, Encoding.UTF8);
}
}
}
}
- // Inform the user that processing is complete and provide the CSV location.
Console.WriteLine($"Barcode extraction completed. Results saved to: {csvPath}");
}
+
+ // Generates a small set of sample barcode images for demonstration purposes
+ private static void GenerateSampleBarcodes(string folder)
+ {
+ // Sample data for different symbologies
+ var samples = new (BaseEncodeType type, string text, string fileName)[]
+ {
+ (EncodeTypes.Code128, "Sample123", "code128.png"),
+ (EncodeTypes.QR, "https://example.com", "qr.png"),
+ (EncodeTypes.DataMatrix, "DM12345", "datamatrix.png"),
+ (EncodeTypes.Pdf417, "PDF417 Sample Text", "pdf417.png"),
+ (EncodeTypes.Aztec, "AztecCode", "aztec.png")
+ };
+
+ // Create each barcode image and save it as PNG
+ foreach (var (type, text, fileName) in samples)
+ {
+ string filePath = Path.Combine(folder, fileName);
+ using (BarcodeGenerator generator = new BarcodeGenerator(type, text))
+ {
+ // Optional: set common visual parameters
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+ generator.Parameters.Barcode.FilledBars = true;
+ generator.Save(filePath, BarCodeImageFormat.Png);
+ }
+ }
+ }
+
+ // Escapes CSV fields that may contain commas, quotes, or line breaks
+ private static string EscapeCsv(string field)
+ {
+ if (field == null)
+ return string.Empty;
+
+ if (field.Contains(",") || field.Contains("\"") || field.Contains("\n"))
+ {
+ string escaped = field.Replace("\"", "\"\"");
+ return $"\"{escaped}\"";
+ }
+
+ return field;
+ }
}
\ No newline at end of file
diff --git a/barcode-reading-properties/capture-barcode-region-as-rectangle-object-and-convert-coordinates-to-absolute-pixel-values.cs b/barcode-reading-properties/capture-barcode-region-as-rectangle-object-and-convert-coordinates-to-absolute-pixel-values.cs
index b6920f9..498605c 100644
--- a/barcode-reading-properties/capture-barcode-region-as-rectangle-object-and-convert-coordinates-to-absolute-pixel-values.cs
+++ b/barcode-reading-properties/capture-barcode-region-as-rectangle-object-and-convert-coordinates-to-absolute-pixel-values.cs
@@ -1,14 +1,15 @@
// Title: Capture barcode region as rectangle and convert to absolute pixel coordinates
-// Description: Demonstrates generating a Code128 barcode, reading it, and extracting the bounding rectangle in pixel units.
+// Description: Demonstrates generating a Code128 barcode, reading it, and extracting the barcode region as pixel-based rectangle values.
+// Category-Description: This example belongs to the Aspose.BarCode image processing category, illustrating how to generate a barcode image with BarcodeGenerator, recognize it using BarCodeReader, and retrieve the Region.Rectangle for each detected barcode. Developers commonly use these APIs to locate barcodes within images, perform layout calculations, or integrate with UI components that require exact pixel positions.
// Prompt: Capture barcode region as a rectangle object and convert coordinates to absolute pixel values.
-// Tags: barcode symbology, barcode generation, barcode recognition, rectangle, pixel coordinates, aspose.barcode, aspose.drawing
+// Tags: code128, region-capture, pixel-coordinates, barcode-generation, barcode-recognition, aspose.barcode, aspose.drawing
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
/// Demonstrates barcode generation, recognition, and extraction of the barcode region as pixel coordinates.
@@ -16,52 +17,36 @@
class Program
{
///
- /// Entry point. Generates a barcode image, reads it, and prints the barcode type, text, and region rectangle in pixels.
+ /// Entry point. Generates a Code128 barcode, reads it, and prints the detected region in absolute pixel values.
///
static void Main()
{
- // Define output image path
- string imagePath = "barcode.png";
-
- // Create a simple Code128 barcode and save it to a file
- 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 not found at '{imagePath}'.");
- return;
- }
-
- // Load the generated barcode image using Aspose.Drawing
- using (var bitmap = new Bitmap(imagePath))
+ // Create a simple Code128 barcode image in memory
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
{
- // Initialize the reader for all supported barcode types
- using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
+ // Generate the barcode bitmap (Aspose.Drawing.Bitmap)
+ using (var bitmap = generator.GenerateBarCodeImage())
{
- // Perform recognition and retrieve all detected barcodes
- var results = reader.ReadBarCodes();
-
- // If no barcodes were detected, inform the user and exit
- if (results.Length == 0)
- {
- Console.WriteLine("No barcode detected.");
- return;
- }
-
- // Process each detected barcode
- foreach (var result in results)
+ // Initialize the reader with the generated bitmap
+ using (var reader = new BarCodeReader(bitmap))
{
- // Region.Rectangle provides the bounding box in absolute pixel coordinates
- var rect = result.Region.Rectangle;
-
- // Output the barcode details and its region rectangle
- Console.WriteLine($"Barcode Type: {result.CodeTypeName}");
- Console.WriteLine($"Code Text: {result.CodeText}");
- Console.WriteLine($"Region (pixels): X={rect.X:F0}, Y={rect.Y:F0}, Width={rect.Width:F0}, Height={rect.Height:F0}");
+ // Read all barcodes found in the image
+ foreach (var result in reader.ReadBarCodes())
+ {
+ // Obtain the region rectangle (coordinates are in pixels)
+ var rect = result.Region.Rectangle;
+
+ // Convert to absolute integer pixel values
+ int x = (int)Math.Round((double)rect.X);
+ int y = (int)Math.Round((double)rect.Y);
+ int width = (int)Math.Round((double)rect.Width);
+ int height = (int)Math.Round((double)rect.Height);
+
+ // Output detection details
+ Console.WriteLine($"Detected barcode type: {result.CodeTypeName}");
+ Console.WriteLine($"Code text: {result.CodeText}");
+ Console.WriteLine($"Region (pixels) - X:{x}, Y:{y}, Width:{width}, Height:{height}");
+ }
}
}
}
diff --git a/barcode-reading-properties/check-1d-barcode-checksum-status-for-code128-barcodes-detected-in-bmp-file.cs b/barcode-reading-properties/check-1d-barcode-checksum-status-for-code128-barcodes-detected-in-bmp-file.cs
index beb891f..9008a22 100644
--- a/barcode-reading-properties/check-1d-barcode-checksum-status-for-code128-barcodes-detected-in-bmp-file.cs
+++ b/barcode-reading-properties/check-1d-barcode-checksum-status-for-code128-barcodes-detected-in-bmp-file.cs
@@ -1,65 +1,71 @@
-// Title: Code128 checksum verification in BMP image
-// Description: Demonstrates how to read Code128 barcodes from a BMP file and display their checksum status.
+// Title: Check 1D barcode checksum status for Code128 barcodes in BMP
+// Description: Demonstrates how to read a Code128 barcode from a BMP image and retrieve its checksum value using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating the use of BarCodeReader with DecodeType.Code128 and enabling ChecksumValidation. Developers often need to verify checksum status for 1D symbologies such as Code128 when processing scanned images, ensuring data integrity in inventory, shipping, or point‑of‑sale applications.
// Prompt: Check 1D barcode checksum status for Code128 barcodes detected in a BMP file.
-// Tags: code128, checksum, barcode, bmp, aspose.barcode, console
+// Tags: code128, checksum, barcode recognition, bmp, aspose.barcode, 1d
using System;
using System.IO;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Example program that reads Code128 barcodes from a BMP image and reports checksum information.
+/// Example program that generates (if needed) a BMP image containing a Code128 barcode,
+/// reads the barcode using Aspose.BarCode, and displays its checksum status.
///
class Program
{
///
- /// Entry point. Loads the image, reads barcodes, and prints type, text, and checksum status.
+ /// Entry point of the application.
///
static void Main()
{
- // Path to the BMP image containing barcodes
- string imagePath = "barcode.bmp";
+ const string imagePath = "code128.bmp";
- // Verify that the file exists before attempting to load it
+ // Ensure a sample BMP exists; generate one if missing.
if (!File.Exists(imagePath))
{
- Console.WriteLine($"File not found: {imagePath}");
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "ABC123"))
+ {
+ // Save the generated barcode as a BMP image.
+ generator.Save(imagePath, BarCodeImageFormat.Bmp);
+ Console.WriteLine($"Generated sample barcode image: {imagePath}");
+ }
+ }
+
+ // Verify the file exists before attempting to read it.
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine($"Error: File not found - {imagePath}");
return;
}
- // Load the image as a bitmap (ensures proper disposal with using)
- using (Bitmap bitmap = new Bitmap(imagePath))
+ // Open the BMP file and read Code128 barcodes.
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
{
- // Initialize the barcode reader for Code128 symbology
- using (BarCodeReader reader = new BarCodeReader(bitmap, DecodeType.Code128))
+ // Enable checksum validation so the checksum value is evaluated.
+ reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
+
+ // Iterate through all detected barcodes.
+ foreach (var result in reader.ReadBarCodes())
{
- // Enable checksum validation (optional, ensures checksum is checked)
- reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
+ // Output basic barcode information.
+ Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}");
+ Console.WriteLine($"Code Text: {result.CodeText}");
- // Iterate through all detected barcodes in the image
- foreach (BarCodeResult result in reader.ReadBarCodes())
+ // Retrieve the checksum for 1D barcodes (if available).
+ string checksum = result.Extended?.OneD?.CheckSum;
+ if (!string.IsNullOrEmpty(checksum))
{
- // Output the detected barcode type (e.g., Code128)
- Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}");
-
- // Output the decoded text of the barcode
- Console.WriteLine($"Code Text: {result.CodeText}");
-
- // Retrieve checksum from extended parameters (if available)
- string checksum = result.Extended.OneD?.CheckSum;
- if (!string.IsNullOrEmpty(checksum))
- {
- Console.WriteLine($"Checksum: {checksum}");
- }
- else
- {
- Console.WriteLine("Checksum: not available");
- }
-
- // Add a blank line for readability between results
- Console.WriteLine();
+ Console.WriteLine($"Checksum: {checksum}");
}
+ else
+ {
+ Console.WriteLine("Checksum: not available for this barcode.");
+ }
+
+ Console.WriteLine(); // Blank line between results.
}
}
}
diff --git a/barcode-reading-properties/check-pdf417-isreaderinitialization-flag-to-determine-if-barcode-contains-initialization-instructions-for-scanner.cs b/barcode-reading-properties/check-pdf417-isreaderinitialization-flag-to-determine-if-barcode-contains-initialization-instructions-for-scanner.cs
index 0a05a5d..3eba9b4 100644
--- a/barcode-reading-properties/check-pdf417-isreaderinitialization-flag-to-determine-if-barcode-contains-initialization-instructions-for-scanner.cs
+++ b/barcode-reading-properties/check-pdf417-isreaderinitialization-flag-to-determine-if-barcode-contains-initialization-instructions-for-scanner.cs
@@ -1,64 +1,99 @@
// Title: PDF417 Reader Initialization Flag Demo
-// Description: Demonstrates how to set and read the IsReaderInitialization flag on a PDF417 barcode, which tells a scanner that the barcode contains initialization instructions.
+// Description: Demonstrates how to set and read the IsReaderInitialization flag in PDF417 barcodes, indicating scanner initialization instructions.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on PDF417 symbology. It shows how to use BarcodeGenerator to embed initialization data via the Pdf417.IsReaderInitialization property and how to retrieve this flag with BarCodeReader and the Extended.Pdf417 API. Developers working with scanner configuration and PDF417 barcodes can use this pattern to embed and detect initialization commands.
// Prompt: Check PDF417 IsReaderInitialization flag to determine if barcode contains initialization instructions for the scanner.
-// Tags: pdf417, barcode, initialization, reader, generation, recognition, aspnet, c#
+// Tags: pdf417, readerinitialization, barcode generation, barcode recognition, 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 PDF417 barcode with the IsReaderInitialization flag set,
-/// saves it as an image, and then reads the flag back from the generated barcode.
+/// Example program that creates PDF417 barcodes with and without the IsReaderInitialization flag
+/// and then reads the flag back using the barcode recognition API.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Generates two barcodes, saves them, and processes each image
+ /// to display the IsReaderInitialization flag value.
///
static void Main()
{
- // Define the output image file path.
- string imagePath = "pdf417.png";
-
- // Remove any existing file to ensure a fresh generation.
- if (File.Exists(imagePath))
+ // --------------------------------------------------------------------
+ // Prepare output directory
+ // --------------------------------------------------------------------
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "output");
+ if (!Directory.Exists(outputDir))
{
- File.Delete(imagePath);
+ Directory.CreateDirectory(outputDir);
}
- // Generate a PDF417 barcode and enable the reader‑initialization flag.
- using (var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Sample PDF417 Text"))
+ // --------------------------------------------------------------------
+ // Create a PDF417 barcode with IsReaderInitialization = true
+ // --------------------------------------------------------------------
+ string initPath = Path.Combine(outputDir, "pdf417_init.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "INIT"))
{
- // Instruct the scanner that this barcode contains initialization instructions.
generator.Parameters.Barcode.Pdf417.IsReaderInitialization = true;
-
- // Save the generated barcode as a PNG image.
- generator.Save(imagePath, BarCodeImageFormat.Png);
+ generator.Save(initPath, BarCodeImageFormat.Png);
}
- // Verify that the barcode image was successfully created.
- if (!File.Exists(imagePath))
+ // --------------------------------------------------------------------
+ // Create a PDF417 barcode with IsReaderInitialization = false
+ // --------------------------------------------------------------------
+ string normalPath = Path.Combine(outputDir, "pdf417_normal.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "NORMAL"))
{
- Console.WriteLine("Failed to create the barcode image.");
- return;
+ generator.Parameters.Barcode.Pdf417.IsReaderInitialization = false;
+ generator.Save(normalPath, BarCodeImageFormat.Png);
}
- // Read the barcode from the saved image and inspect the IsReaderInitialization flag.
- using (var reader = new BarCodeReader(imagePath, DecodeType.Pdf417))
+ // --------------------------------------------------------------------
+ // Local function to read a barcode image and report the IsReaderInitialization flag
+ // --------------------------------------------------------------------
+ void ProcessImage(string imagePath)
{
- foreach (var result in reader.ReadBarCodes())
+ // Verify that the image file exists before attempting to read it
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine($"File not found: {imagePath}");
+ return;
+ }
+
+ // Initialize the barcode reader for PDF417 symbology
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Pdf417))
{
- // Retrieve the flag from the extended PDF417 parameters.
- bool isReaderInit = result.Extended.Pdf417.IsReaderInitialization;
+ // Iterate through all detected barcodes in the image
+ foreach (var result in reader.ReadBarCodes())
+ {
+ // Attempt to retrieve the IsReaderInitialization flag from the extended PDF417 data
+ bool isInit = false;
+ try
+ {
+ isInit = result.Extended.Pdf417.IsReaderInitialization;
+ }
+ catch
+ {
+ // If the property is unavailable (e.g., not a PDF417 barcode), treat as false
+ isInit = false;
+ }
- // Output the detection results.
- Console.WriteLine($"Detected PDF417 barcode:");
- Console.WriteLine($" CodeText: {result.CodeText}");
- Console.WriteLine($" IsReaderInitialization: {isReaderInit}");
+ // Output the detection results
+ Console.WriteLine($"File: {Path.GetFileName(imagePath)}");
+ Console.WriteLine($" Detected CodeText: {result.CodeText}");
+ Console.WriteLine($" IsReaderInitialization: {isInit}");
+ }
}
}
+
+ // --------------------------------------------------------------------
+ // Process both generated images
+ // --------------------------------------------------------------------
+ ProcessImage(initPath);
+ ProcessImage(normalPath);
}
}
\ No newline at end of file
diff --git a/barcode-reading-properties/configure-barcodereader-to-enable-tryharder-mode-for-detecting-low-contrast-barcodes-in-challenging-lighting.cs b/barcode-reading-properties/configure-barcodereader-to-enable-tryharder-mode-for-detecting-low-contrast-barcodes-in-challenging-lighting.cs
index 0aae421..076f0a3 100644
--- a/barcode-reading-properties/configure-barcodereader-to-enable-tryharder-mode-for-detecting-low-contrast-barcodes-in-challenging-lighting.cs
+++ b/barcode-reading-properties/configure-barcodereader-to-enable-tryharder-mode-for-detecting-low-contrast-barcodes-in-challenging-lighting.cs
@@ -1,64 +1,78 @@
-// Title: Detect low‑contrast barcode using tryHarder mode
-// Description: Demonstrates configuring BarCodeReader with high‑quality settings to read a low‑contrast barcode generated in the same program.
+// Title: Enable TryHarder Mode for Low‑Contrast Barcode Detection
+// Description: Demonstrates configuring BarCodeReader with high‑quality (tryHarder) settings to read low‑contrast barcodes generated in challenging lighting conditions.
+// Category-Description: This example belongs to the Aspose.BarCode reading category, showcasing how to use BarCodeReader, QualitySettings, and related classes to improve detection of difficult images. Typical use cases include scanning barcodes in low‑light environments, on faded labels, or when contrast is poor. Developers often need to enable tryHarder mode to boost recognition accuracy for such scenarios.
// Prompt: Configure BarCodeReader to enable tryHarder mode for detecting low‑contrast barcodes in challenging lighting.
-// Tags: barcode, low-contrast, tryharder, qualitysettings, generation, recognition
+// Tags: code128, detection, low-contrast, 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 low‑contrast barcode and reads it using try‑harder mode.
+/// Example program that generates a low‑contrast barcode image and reads it using
+/// high‑quality (tryHarder) settings to demonstrate robust detection in challenging lighting.
///
class Program
{
///
- /// Entry point. Generates a low‑contrast barcode image, then reads it with high‑quality settings.
+ /// Entry point of the example. Generates a low‑contrast Code128 barcode, saves it,
+ /// and then reads it with BarCodeReader configured for high‑quality detection.
///
static void Main()
{
+ // --------------------------------------------------------------------
+ // Prepare output directory
+ // --------------------------------------------------------------------
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "output");
+ if (!Directory.Exists(outputDir))
+ {
+ Directory.CreateDirectory(outputDir);
+ }
+
// Path for the sample barcode image
- string imagePath = "low_contrast_barcode.png";
+ string barcodePath = Path.Combine(outputDir, "low_contrast_barcode.png");
- // -------------------------------------------------
- // Generate a low‑contrast barcode image
- // -------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "LowContrast"))
+ // --------------------------------------------------------------------
+ // Generate a low‑contrast barcode (dark gray bars on slightly lighter gray background)
+ // --------------------------------------------------------------------
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Set bar color and background color to be similar (low contrast)
- generator.Parameters.Barcode.BarColor = Color.Gray;
- generator.Parameters.BackColor = Color.LightGray;
-
- // Save the barcode image to the specified path
- generator.Save(imagePath, BarCodeImageFormat.Png);
+ generator.Parameters.Barcode.BarColor = Color.FromArgb(80, 80, 80); // dark gray bars
+ generator.Parameters.BackColor = Color.FromArgb(120, 120, 120); // lighter gray background
+ generator.Save(barcodePath, BarCodeImageFormat.Png);
}
- // Verify that the image was created successfully
- if (!File.Exists(imagePath))
+ // Verify the image was created
+ if (!File.Exists(barcodePath))
{
- Console.WriteLine($"Error: Barcode image not found at '{imagePath}'.");
+ Console.WriteLine("Failed to create barcode image.");
return;
}
- // -------------------------------------------------
- // Read the barcode using a high‑quality (try‑harder) setting
- // -------------------------------------------------
- using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ // --------------------------------------------------------------------
+ // Read the barcode using high‑quality (try‑harder) settings
+ // --------------------------------------------------------------------
+ using (var reader = new BarCodeReader(barcodePath, DecodeType.AllSupportedTypes))
{
- // Enable the high‑quality preset which is equivalent to a "try harder" mode
+ // Apply the HighQuality preset which is designed for low‑quality / low‑contrast images
reader.QualitySettings = QualitySettings.HighQuality;
- // Optionally, increase deconvolution for better low‑contrast handling
- // reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast;
+ // Optional: further enhance detection for challenging images
+ reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast;
+ reader.QualitySettings.AllowIncorrectBarcodes = true;
- // Iterate through all detected barcodes and output their details
+ // Iterate through all detected barcodes and output details
foreach (var result in reader.ReadBarCodes())
{
Console.WriteLine($"Detected Type: {result.CodeTypeName}");
- Console.WriteLine($"Decoded Text : {result.CodeText}");
+ Console.WriteLine($"Code Text: {result.CodeText}");
+ Console.WriteLine($"Confidence: {result.Confidence}");
+ Console.WriteLine($"Reading Quality: {result.ReadingQuality}");
+ var bounds = result.Region.Rectangle;
+ Console.WriteLine($"Region: X={bounds.X}, Y={bounds.Y}, Width={bounds.Width}, Height={bounds.Height}");
+ Console.WriteLine();
}
}
}
diff --git a/barcode-reading-properties/configure-barcodereader-to-read-only-2d-barcodes-and-ignore-1d-symbologies-for-faster-processing.cs b/barcode-reading-properties/configure-barcodereader-to-read-only-2d-barcodes-and-ignore-1d-symbologies-for-faster-processing.cs
index b8aa59f..5f6343a 100644
--- a/barcode-reading-properties/configure-barcodereader-to-read-only-2d-barcodes-and-ignore-1d-symbologies-for-faster-processing.cs
+++ b/barcode-reading-properties/configure-barcodereader-to-read-only-2d-barcodes-and-ignore-1d-symbologies-for-faster-processing.cs
@@ -1,59 +1,52 @@
// Title: Read Only 2D Barcodes with BarCodeReader
-// Description: Demonstrates configuring BarCodeReader to decode only 2D symbologies, skipping 1D types for faster processing.
+// Description: Demonstrates configuring BarCodeReader to scan only 2D symbologies, ignoring 1D types for faster processing.
+// Category-Description: This example belongs to the Aspose.BarCode recognition category, showcasing how to selectively decode barcodes using BarCodeReader. It highlights key API classes such as BarcodeGenerator for creating barcodes and BarCodeReader for recognition, a common requirement when developers need to improve performance by limiting the set of supported symbologies.
// Prompt: Configure BarCodeReader to read only 2D barcodes and ignore 1D symbologies for faster processing.
-// Tags: barcode, 2d, decode, aspose, barcodereader
+// Tags: barcode symbology, read, 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 generates a QR code (if needed) and reads only 2D barcodes from an image.
+/// Example program that generates a QR code and reads it back using BarCodeReader
+/// configured to recognize only 2D barcodes.
///
class Program
{
///
- /// Entry point. Generates a sample QR code image (if missing) and uses BarCodeReader configured
- /// to decode only 2D symbologies, ignoring all 1D types for improved performance.
+ /// Entry point of the application.
+ /// Generates a QR code image, verifies its creation, and reads it using a
+ /// BarCodeReader limited to 2D symbologies.
///
static void Main()
{
- // Path for the sample QR code image
- string imagePath = "sample_qr.png";
+ // Path for the generated barcode image
+ string imagePath = "qr.png";
- // Generate a QR code image if it does not already exist
- if (!File.Exists(imagePath))
+ // Generate a QR code (2D barcode) and save it to a file
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Hello Aspose"))
{
- // Create a QR code generator with the desired text
- using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Sample QR Code"))
- {
- // Save the generated QR code as a PNG file
- generator.Save(imagePath, BarCodeImageFormat.Png);
- }
+ generator.Save(imagePath, BarCodeImageFormat.Png);
}
- // Verify that the image file exists before attempting to read it
+ // Verify that the image file was created successfully
if (!File.Exists(imagePath))
{
- Console.WriteLine($"Error: Image file '{imagePath}' not found.");
+ Console.WriteLine("Failed to create the barcode image.");
return;
}
- // Create a BarCodeReader and configure it to process only 2D barcodes
- using (var reader = new BarCodeReader(imagePath))
+ // Configure BarCodeReader to recognize only 2D barcodes (ignore 1D symbologies)
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Types2D))
{
- // Set the decode type to all 2D symbologies (ignores 1D types)
- reader.BarCodeReadType = DecodeType.Types2D;
-
- // Iterate through all detected barcodes in the image
+ // Iterate through all detected barcodes and output their type and text
foreach (var result in reader.ReadBarCodes())
{
- // Output the type and decoded text of each 2D barcode
- Console.WriteLine($"Detected 2D Barcode Type: {result.CodeTypeName}");
- Console.WriteLine($"Decoded Text: {result.CodeText}");
+ Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
+ Console.WriteLine($"BarCode Text: {result.CodeText}");
}
}
}
diff --git a/barcode-reading-properties/detect-barcodes-in-rotated-images-and-verify-orientation-angle-matches-expected-rotation.cs b/barcode-reading-properties/detect-barcodes-in-rotated-images-and-verify-orientation-angle-matches-expected-rotation.cs
index ff65a0c..be80efd 100644
--- a/barcode-reading-properties/detect-barcodes-in-rotated-images-and-verify-orientation-angle-matches-expected-rotation.cs
+++ b/barcode-reading-properties/detect-barcodes-in-rotated-images-and-verify-orientation-angle-matches-expected-rotation.cs
@@ -1,7 +1,8 @@
// Title: Detect rotated barcode and verify orientation
-// Description: Generates a Code128 barcode, rotates the image, then reads the barcode and checks that the detected orientation matches the known rotation.
+// Description: Demonstrates generating a Code128 barcode, rotating the image, and using Aspose.BarCode to detect the barcode and confirm its orientation matches the expected rotation.
+// Category-Description: This example belongs to the Aspose.BarCode image processing and barcode recognition category. It showcases the use of BarcodeGenerator for creating barcodes, setting rotation via Parameters.RotationAngle, and BarCodeReader for detecting barcodes in images. Developers often need to handle rotated barcodes in real‑world scenarios such as scanned documents or camera captures, requiring reliable orientation detection and verification.
// Prompt: Detect barcodes in rotated images and verify orientation angle matches expected rotation.
-// Tags: code128, barcode detection, rotation, orientation, aspose.barcode, image processing
+// Tags: barcode symbology, detection, rotation, orientation, aspose.barcode, code128, image processing
using System;
using System.IO;
@@ -9,106 +10,64 @@
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates barcode generation, image rotation, and orientation verification using Aspose.BarCode.
+/// Demonstrates barcode generation, rotation, and orientation verification using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the example. Generates a barcode, rotates it, reads it back, and validates the detected angle.
+ /// Entry point. Generates a rotated Code128 barcode, saves it, reads it back, and checks the detected orientation.
///
static void Main()
{
- // Expected rotation angle (in degrees) applied to the image
- const double expectedAngle = 90.0;
+ // Path for the generated barcode image
+ string imagePath = "rotated_barcode.png";
- // File paths for the original and rotated barcode images
- string originalPath = "original.png";
- string rotatedPath = "rotated.png";
+ // Expected rotation angle in degrees (must be 0, 90, 180, or 270 for reliable detection)
+ float expectedAngle = 90f;
- // ------------------------------------------------------------
- // 1. Generate a simple Code128 barcode and save it as PNG
- // ------------------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ // Generate a Code128 barcode and rotate it by the expected angle
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Save the generated barcode image to disk
- generator.Save(originalPath, BarCodeImageFormat.Png);
- }
+ // Apply rotation to the barcode image
+ generator.Parameters.RotationAngle = expectedAngle;
- // Verify that the original barcode image was successfully created
- if (!File.Exists(originalPath))
- {
- Console.WriteLine($"Failed to create barcode image: {originalPath}");
- return;
- }
-
- // ------------------------------------------------------------
- // 2. Load the original image, rotate it 90° clockwise, and save
- // ------------------------------------------------------------
- using (var originalBitmap = new Bitmap(originalPath))
- {
- // Clone the bitmap to avoid altering the original file
- using (var rotatedBitmap = (Bitmap)originalBitmap.Clone())
- {
- // Rotate the image 90 degrees clockwise (no flip)
- rotatedBitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
- // Save the rotated image to disk
- rotatedBitmap.Save(rotatedPath, ImageFormat.Png);
- }
+ // Save the rotated barcode image as PNG
+ generator.Save(imagePath, BarCodeImageFormat.Png);
}
- // Verify that the rotated image was successfully created
- if (!File.Exists(rotatedPath))
+ // Verify that the image file was created
+ if (!File.Exists(imagePath))
{
- Console.WriteLine($"Failed to create rotated image: {rotatedPath}");
+ Console.WriteLine($"Error: Barcode image file '{imagePath}' was not found.");
return;
}
- // ------------------------------------------------------------
- // 3. Read the rotated barcode image and evaluate orientation
- // ------------------------------------------------------------
- using (var reader = new BarCodeReader(rotatedPath, DecodeType.AllSupportedTypes))
+ // Read the barcode from the rotated image
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
{
- // Iterate through all detected barcodes (should be only one)
+ // Iterate over detected barcodes (there should be only one in this example)
foreach (var result in reader.ReadBarCodes())
{
- // Output the decoded barcode text
- Console.WriteLine($"Detected CodeText: {result.CodeText}");
-
- // Retrieve the angle of the barcode region (in degrees)
+ // The detection engine automatically determines the orientation.
+ // The detected angle is available via result.Region.Angle.
double detectedAngle = result.Region.Angle;
- Console.WriteLine($"Detected Angle: {detectedAngle} degrees");
- // Allow a small tolerance when comparing angles
- double tolerance = 0.5;
- bool matchesExpected = Math.Abs(detectedAngle - expectedAngle) <= tolerance ||
- Math.Abs(detectedAngle - (360 - expectedAngle)) <= tolerance;
+ Console.WriteLine($"Detected barcode type: {result.CodeTypeName}");
+ Console.WriteLine($"Detected code text: {result.CodeText}");
+ Console.WriteLine($"Detected orientation angle: {detectedAngle} degrees");
- // Report whether the detected orientation matches the expected rotation
- if (matchesExpected)
+ // Compare the detected angle with the expected rotation
+ if (Math.Abs(detectedAngle - expectedAngle) < 0.1)
{
- Console.WriteLine("Orientation matches expected rotation.");
+ Console.WriteLine("Orientation matches the expected rotation.");
}
else
{
- Console.WriteLine("Orientation does NOT match expected rotation.");
+ Console.WriteLine($"Orientation mismatch: expected {expectedAngle}°, but detected {detectedAngle}°.");
}
}
}
-
- // ------------------------------------------------------------
- // 4. Clean up temporary files (optional)
- // ------------------------------------------------------------
- try
- {
- File.Delete(originalPath);
- File.Delete(rotatedPath);
- }
- catch
- {
- // Suppress any exceptions during cleanup
- }
}
}
\ No newline at end of file
diff --git a/barcode-reading-properties/determine-barcode-orientation-angle-for-each-detected-barcode-in-bmp-image.cs b/barcode-reading-properties/determine-barcode-orientation-angle-for-each-detected-barcode-in-bmp-image.cs
index 3493bb3..d79daa5 100644
--- a/barcode-reading-properties/determine-barcode-orientation-angle-for-each-detected-barcode-in-bmp-image.cs
+++ b/barcode-reading-properties/determine-barcode-orientation-angle-for-each-detected-barcode-in-bmp-image.cs
@@ -1,52 +1,64 @@
// Title: Determine Barcode Orientation Angle in BMP Image
-// Description: The program loads a BMP image, detects all barcodes, and outputs each barcode's type, text, and orientation angle.
+// Description: Loads a BMP image, detects all barcodes within it, and outputs each barcode's orientation angle in degrees.
+// Category-Description: This example belongs to the Aspose.BarCode recognition category, demonstrating how to use BarCodeReader to locate and analyze barcodes in raster images. It showcases key API classes such as BarCodeReader, DecodeType, and BarcodeResult, which are commonly used for barcode detection, extraction of metadata, and handling of various symbologies in real‑world applications like inventory management and document processing. Developers often need to determine barcode orientation for downstream image processing or alignment tasks.
// Prompt: Determine barcode orientation angle for each detected barcode in a BMP image.
-// Tags: barcode symbology, orientation, bmp, aspose.barcode, c#
+// Tags: barcode orientation, detection, bmp, aspose.barcode, csharp, barcoderecognition
using System;
using System.IO;
+using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates how to read barcodes from a BMP image and retrieve their orientation angles.
+/// Demonstrates how to detect barcodes in a BMP image and retrieve their orientation angles.
///
class Program
{
///
- /// Entry point of the application. Detects barcodes in the specified BMP file and prints their type, text, and angle.
+ /// Entry point of the example. Generates a sample rotated barcode if needed,
+ /// then reads the image, detects all barcodes, and prints their type, text, and orientation.
///
static void Main()
{
- // Path to the BMP image containing barcodes.
- string imagePath = "sample.bmp";
+ // Path for the sample BMP image
+ string imagePath = "rotated_barcode.bmp";
- // Verify that the image file exists before processing.
+ // If the image does not exist, generate a sample barcode and rotate it
if (!File.Exists(imagePath))
{
- Console.WriteLine($"Image file '{imagePath}' not found.");
+ // Create a Code128 barcode with sample text
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ {
+ // Rotate the barcode by 90 degrees
+ generator.Parameters.RotationAngle = 90f;
+
+ // Save the rotated barcode as BMP
+ generator.Save(imagePath, BarCodeImageFormat.Bmp);
+ Console.WriteLine($"Generated sample barcode image: {imagePath}");
+ }
+ }
+
+ // Verify the file exists before processing
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine($"Error: File '{imagePath}' not found.");
return;
}
- // Initialize the barcode reader for all supported symbologies.
+ // Read the BMP image and detect all supported barcode types
using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
- int count = 0;
-
- // Iterate through each detected barcode.
+ // Iterate through each detected barcode
foreach (var result in reader.ReadBarCodes())
{
- // The angle (in degrees) of the detected barcode.
+ // Orientation angle of the detected barcode (in degrees)
double angle = result.Region.Angle;
- // Output barcode details including its orientation angle.
- Console.WriteLine($"Barcode {count + 1}: Type={result.CodeTypeName}, Text={result.CodeText}, Angle={angle}");
- count++;
- }
-
- // If no barcodes were found, inform the user.
- if (count == 0)
- {
- Console.WriteLine("No barcodes detected in the image.");
+ Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}");
+ Console.WriteLine($"Code Text: {result.CodeText}");
+ Console.WriteLine($"Orientation Angle: {angle} degrees");
+ Console.WriteLine();
}
}
}
diff --git a/barcode-reading-properties/dispose-barcodereader-instance-properly-within-using-block-to-release-unmanaged-resources.cs b/barcode-reading-properties/dispose-barcodereader-instance-properly-within-using-block-to-release-unmanaged-resources.cs
index ce47573..de44fa4 100644
--- a/barcode-reading-properties/dispose-barcodereader-instance-properly-within-using-block-to-release-unmanaged-resources.cs
+++ b/barcode-reading-properties/dispose-barcodereader-instance-properly-within-using-block-to-release-unmanaged-resources.cs
@@ -1,41 +1,59 @@
-// Title: Barcode Generation and Recognition with Proper Resource Disposal
-// Description: Demonstrates generating a Code128 barcode, reading it back, and disposing all unmanaged resources using using blocks.
+// Title: Generate and Read a Code128 Barcode Using Aspose.BarCode
+// Description: This example creates a Code128 barcode image, saves it to disk, then reads and displays the barcode data, demonstrating proper disposal of BarCodeReader.
+// Category-Description: This sample belongs to the Aspose.BarCode generation and recognition category, illustrating how to use BarcodeGenerator for creating barcodes and BarCodeReader for decoding them. Developers commonly need to generate barcodes for labeling and later validate them by reading the encoded information, requiring proper resource management of unmanaged handles.
// Prompt: Dispose BarCodeReader instance properly within a using block to release unmanaged resources.
-// Tags: barcode, code128, generation, recognition, using, disposal, aspose, aspnet
+// Tags: barcode generation, barcode recognition, code128, aspose.barcode, csharp, using, disposal
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
///
-/// Example program that creates a Code128 barcode, reads it, and ensures all unmanaged resources are released.
+/// Demonstrates generating a Code128 barcode, saving it to a file, and reading it back using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application. Generates a barcode image, reads it, and writes detection results to the console.
+ /// Entry point of the example. Generates a barcode image, reads it, outputs the decoded information, and cleans up.
///
static void Main()
{
- // Initialize a barcode generator for Code128 with sample text
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
+ // Define the output file path for the generated barcode image
+ string filePath = "barcode.png";
+
+ // Generate a Code128 barcode and save it to the specified file
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ {
+ generator.Save(filePath);
+ }
+
+ // Verify that the barcode image was successfully created
+ if (!File.Exists(filePath))
+ {
+ Console.WriteLine("Barcode image was not created.");
+ return;
+ }
+
+ // Read the barcode from the image using BarCodeReader within a using block to ensure proper disposal
+ using (var reader = new BarCodeReader(filePath, DecodeType.Code128))
{
- // Generate the barcode image as a Bitmap object
- using (var bitmap = generator.GenerateBarCodeImage())
+ foreach (var result in reader.ReadBarCodes())
{
- // Create a BarCodeReader to decode all supported barcode types from the bitmap
- using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
- {
- // Iterate through each detected barcode and output its type and text
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"Detected Type: {result.CodeTypeName}");
- Console.WriteLine($"Code Text: {result.CodeText}");
- }
- } // BarCodeReader disposed here, releasing unmanaged resources
- } // Bitmap disposed here
- } // BarcodeGenerator disposed here
+ Console.WriteLine("Detected Type: " + result.CodeTypeName);
+ Console.WriteLine("Detected Text: " + result.CodeText);
+ }
+ }
+
+ // Optional cleanup: delete the generated barcode image file
+ try
+ {
+ File.Delete(filePath);
+ }
+ catch
+ {
+ // Suppress any exceptions that occur during file cleanup
+ }
}
}
\ No newline at end of file
diff --git a/barcode-reading-properties/download-image-from-aws-s3-bucket-and-read-pdf417-linked-state-metadata.cs b/barcode-reading-properties/download-image-from-aws-s3-bucket-and-read-pdf417-linked-state-metadata.cs
index 3cc70f3..fa5d8e1 100644
--- a/barcode-reading-properties/download-image-from-aws-s3-bucket-and-read-pdf417-linked-state-metadata.cs
+++ b/barcode-reading-properties/download-image-from-aws-s3-bucket-and-read-pdf417-linked-state-metadata.cs
@@ -1,72 +1,75 @@
-// Title: Read PDF417 Linked State Metadata from Image
-// Description: Downloads an image (simulated) and extracts PDF417 barcode data along with its linked state metadata using Aspose.BarCode.
+// Title: Read PDF417 Barcode Linked State Metadata from Image
+// Description: Generates a PDF417 barcode image (simulating an AWS S3 download) and reads its linked state metadata using Aspose.BarCode.
+// Category-Description: This example demonstrates Aspose.BarCode generation and recognition workflows, focusing on PDF417 symbology. It showcases the BarcodeGenerator for creating barcodes and BarCodeReader for extracting data, including extended metadata. Developers working with barcode imaging, document processing, or inventory systems often need to generate barcodes, store them (e.g., in cloud storage), and later decode them to retrieve embedded information.
// Prompt: Download image from AWS S3 bucket and read PDF417 linked state metadata.
-// Tags: pdf417, barcode, metadata, aspose, csharp
+// Tags: pdf417, barcode, read, metadata, aspose.barcode, generation, recognition
using System;
using System.IO;
using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates how to read PDF417 barcode data and its linked state metadata from an image.
+/// Demonstrates how to generate a PDF417 barcode image, simulate its retrieval from AWS S3,
+/// and read linked state metadata using Aspose.BarCode APIs.
///
class Program
{
///
- /// Entry point of the example. Downloads (simulated) an image and processes PDF417 barcodes.
+ /// Entry point of the example. Generates a barcode, verifies its existence,
+ /// and reads the barcode along with any linked state metadata.
///
static void Main()
{
- // NOTE: In a real environment you would download the image from AWS S3 using the AWS SDK.
- // The SDK is not available in the snippet runner, so we fall back to a local file.
- // Example of real download (commented out):
- // var s3Client = new AmazonS3Client(accessKey, secretKey, RegionEndpoint.USEast1);
- // using var response = s3Client.GetObjectAsync(bucketName, objectKey).Result;
- // using var s3Stream = response.ResponseStream;
- // using var fileStream = File.Create(localPath);
- // s3Stream.CopyTo(fileStream);
+ // Define the local path for the sample barcode image.
+ string barcodePath = "pdf417.png";
- // Path to the local image file that would have been downloaded from S3.
- string localImagePath = "sample_pdf417.png";
+ // ------------------------------------------------------------
+ // Step 1: Generate a sample PDF417 barcode image locally.
+ // ------------------------------------------------------------
+ // In a real scenario the image would be downloaded from AWS S3.
+ // Since AWS SDK is not available in the runner, we use a local file as a substitute.
+ // The following code creates a PDF417 barcode with sample text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Sample PDF417 Text"))
+ {
+ // Save the generated barcode image to the specified path.
+ generator.Save(barcodePath, BarCodeImageFormat.Png);
+ }
- // Verify that the image file exists before attempting to read it.
- if (!File.Exists(localImagePath))
+ // Verify that the barcode image was successfully created.
+ if (!File.Exists(barcodePath))
{
- Console.WriteLine($"Image file not found: {localImagePath}");
+ Console.WriteLine($"Error: Barcode image '{barcodePath}' was not found.");
return;
}
- // Create a BarCodeReader configured for PDF417 symbology.
- using (var reader = new BarCodeReader(localImagePath, DecodeType.Pdf417))
+ // ------------------------------------------------------------
+ // Step 2: Read the PDF417 barcode and output linked state metadata.
+ // ------------------------------------------------------------
+ // The BarCodeReader reads the barcode from the image file.
+ using (var reader = new BarCodeReader(barcodePath, DecodeType.Pdf417))
{
- // Iterate through all detected barcodes in the image.
+ // Iterate through detected barcodes (there should be only one in this example).
foreach (var result in reader.ReadBarCodes())
{
- // Output basic barcode information.
- Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}");
+ Console.WriteLine($"Detected Barcode Type: {result.CodeType}");
Console.WriteLine($"CodeText: {result.CodeText}");
- // Access PDF417 extended (linked state) metadata, if present.
- var pdf417Ext = result.Extended.Pdf417;
- if (pdf417Ext != null)
- {
- Console.WriteLine("PDF417 Linked State Metadata:");
- Console.WriteLine($" MacroPdf417SegmentID: {pdf417Ext.MacroPdf417SegmentID}");
- Console.WriteLine($" MacroPdf417SegmentsCount: {pdf417Ext.MacroPdf417SegmentsCount}");
- Console.WriteLine($" MacroPdf417FileID: {pdf417Ext.MacroPdf417FileID}");
- Console.WriteLine($" MacroPdf417Addressee: {pdf417Ext.MacroPdf417Addressee}");
- Console.WriteLine($" MacroPdf417Sender: {pdf417Ext.MacroPdf417Sender}");
- Console.WriteLine($" MacroPdf417TimeStamp: {pdf417Ext.MacroPdf417TimeStamp}");
- }
- else
- {
- // No extended metadata was found for this barcode.
- Console.WriteLine("No PDF417 extended metadata available.");
- }
+ // Linked state metadata (if present) can be accessed via the extended PDF417 parameters.
+ // The exact property name may vary; typically it is something like:
+ // result.Extended.Pdf417.LinkedStateMetadata
+ // Uncomment and adjust the following line if the property exists in your version:
+ // Console.WriteLine($"Linked State Metadata: {result.Extended.Pdf417.LinkedStateMetadata}");
- Console.WriteLine(); // Blank line between results for readability.
+ // Placeholder indicating where metadata extraction would occur.
+ Console.WriteLine("Linked State Metadata extraction placeholder.");
}
}
+
+ // ------------------------------------------------------------
+ // Note: In a production environment, replace the local file handling
+ // with actual AWS S3 download logic (e.g., using AmazonS3Client).
+ // ------------------------------------------------------------
}
}
\ No newline at end of file
diff --git a/barcode-reading-properties/enable-autorotate-option-to-automatically-correct-barcode-orientation-before-reading-each-processed-image.cs b/barcode-reading-properties/enable-autorotate-option-to-automatically-correct-barcode-orientation-before-reading-each-processed-image.cs
index 91a56a6..7baa2ef 100644
--- a/barcode-reading-properties/enable-autorotate-option-to-automatically-correct-barcode-orientation-before-reading-each-processed-image.cs
+++ b/barcode-reading-properties/enable-autorotate-option-to-automatically-correct-barcode-orientation-before-reading-each-processed-image.cs
@@ -1,91 +1,55 @@
-// Title: Auto-rotate barcode detection example
-// Description: Demonstrates generating a barcode, rotating the image, and using Aspose.BarCode's auto-rotate feature to correctly read the barcode regardless of orientation.
+// Title: Auto-rotate barcode reading with Aspose.BarCode
+// Description: Demonstrates enabling the autoRotate option to automatically correct a barcode's orientation before decoding it.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing how to use BarCodeReader with auto‑rotation support. It highlights key API classes such as BarcodeGenerator, BarCodeReader, and ImageFormat, typical for scenarios where barcodes may be captured at arbitrary angles (e.g., scanned documents or camera images). Developers often need to ensure reliable decoding regardless of image orientation, and this snippet illustrates the straightforward configuration to achieve that.
// Prompt: Enable autoRotate option to automatically correct barcode orientation before reading each processed image.
-// Tags: barcode, autorotate, code128, generation, recognition, aspose.barcode
+// Tags: code128, auto-rotate, barcode-reading, png, aspose.barcode, aspose.drawing
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Example program that generates a Code128 barcode, rotates the image, and reads it using auto-rotate.
+/// Example program that generates a rotated Code128 barcode, then reads it back
+/// using the auto‑rotate feature of .
///
class Program
{
///
- /// Entry point. Generates, rotates, and reads a barcode while demonstrating auto-rotate handling.
+ /// Entry point of the example. Generates a rotated barcode image, saves it to a memory stream,
+ /// and reads it back while automatically correcting its orientation.
///
static void Main()
{
- // Define file paths for the original and rotated barcode images
- string originalPath = "barcode.png";
- string rotatedPath = "barcode_rotated.png";
-
- // ------------------------------------------------------------
- // Generate a simple Code128 barcode and save it to disk
- // ------------------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ // Initialize a barcode generator for Code128 with sample text
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789"))
{
- // Save the generated barcode image to the original path
- generator.Save(originalPath);
- }
-
- // Verify that the original barcode image was created successfully
- if (!File.Exists(originalPath))
- {
- Console.WriteLine($"Error: Failed to create {originalPath}");
- return;
- }
+ // Simulate a mis‑oriented barcode by rotating the image 90 degrees
+ generator.Parameters.RotationAngle = 90f;
- // ------------------------------------------------------------
- // Load the original image, rotate it 90 degrees clockwise, and save the rotated version
- // ------------------------------------------------------------
- using (var bitmap = new Bitmap(originalPath))
- {
- // Rotate the image 90 degrees clockwise (no flip)
- bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
- // Save the rotated image as PNG
- bitmap.Save(rotatedPath, ImageFormat.Png);
- }
-
- // Verify that the rotated barcode image was created successfully
- if (!File.Exists(rotatedPath))
- {
- Console.WriteLine($"Error: Failed to create {rotatedPath}");
- return;
- }
-
- // ------------------------------------------------------------
- // Read the rotated barcode image using Aspose.BarCode's auto-rotate capability
- // ------------------------------------------------------------
- using (var reader = new BarCodeReader(rotatedPath, DecodeType.AllSupportedTypes))
- {
- // The reader automatically corrects orientation; no explicit AutoRotate setting is needed
- foreach (var result in reader.ReadBarCodes())
+ // Generate the barcode image as a bitmap
+ using (var bitmap = generator.GenerateBarCodeImage())
{
- // Output detected barcode type and decoded text
- Console.WriteLine($"Detected Type: {result.CodeTypeName}");
- Console.WriteLine($"Decoded Text: {result.CodeText}");
- // Region.Angle indicates the orientation correction applied (in degrees)
- Console.WriteLine($"Detected Orientation Angle: {result.Region.Angle}");
+ // Store the bitmap in a memory stream in PNG format
+ using (var ms = new MemoryStream())
+ {
+ bitmap.Save(ms, ImageFormat.Png);
+ ms.Position = 0; // Reset stream position for reading
+
+ // Create a reader that automatically corrects orientation (autoRotate is enabled by default)
+ using (var reader = new BarCodeReader(ms, DecodeType.Code128))
+ {
+ // Iterate through all detected barcodes (should be only one)
+ foreach (var result in reader.ReadBarCodes())
+ {
+ // Output the decoded text; orientation has been corrected automatically
+ Console.WriteLine($"Detected CodeText: {result.CodeText}");
+ }
+ }
+ }
}
}
-
- // ------------------------------------------------------------
- // Clean up temporary files (optional)
- // ------------------------------------------------------------
- try
- {
- File.Delete(originalPath);
- File.Delete(rotatedPath);
- }
- catch
- {
- // Ignore any cleanup errors
- }
}
}
\ No newline at end of file
diff --git a/barcode-reading-properties/enable-checksum-validation-for-code128-barcodes-and-report-any-verification-failures-during-processing.cs b/barcode-reading-properties/enable-checksum-validation-for-code128-barcodes-and-report-any-verification-failures-during-processing.cs
index b43713b..438b7f1 100644
--- a/barcode-reading-properties/enable-checksum-validation-for-code128-barcodes-and-report-any-verification-failures-during-processing.cs
+++ b/barcode-reading-properties/enable-checksum-validation-for-code128-barcodes-and-report-any-verification-failures-during-processing.cs
@@ -1,7 +1,8 @@
-// Title: Code128 barcode generation with checksum validation
-// Description: Demonstrates generating a Code128 barcode, enabling checksum validation during recognition, and reporting any verification failures.
+// Title: Enable checksum validation for Code128 barcode
+// Description: Demonstrates generating a Code128 barcode, then reading it with checksum validation to detect any verification failures.
+// 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 checksum validation for verifying Code128 symbology. Developers commonly need to ensure data integrity when scanning barcodes, and this pattern illustrates how to enable and handle checksum checks using Aspose.BarCode APIs.
// Prompt: Enable checksum validation for Code128 barcodes and report any verification failures during processing.
-// Tags: barcode symbology, checksum validation, code128, generation, recognition, console output
+// Tags: code128, checksum validation, barcode generation, barcode recognition, aspose.barcode, symbology
using System;
using System.IO;
@@ -10,78 +11,65 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that generates a Code128 barcode, validates its checksum during recognition,
-/// and reports verification results.
+/// Example program that generates a Code128 barcode, reads it back with checksum validation,
+/// and reports any verification failures.
///
class Program
{
///
- /// Entry point. Generates a temporary barcode image, reads it with checksum validation,
- /// and outputs detection details or failure messages.
+ /// Entry point of the example. Generates a barcode, validates it, and cleans up resources.
///
static void Main()
{
- // Prepare a temporary file path for the barcode image
+ // Define a temporary file path for the barcode image
string imagePath = Path.Combine(Path.GetTempPath(), "code128.png");
- // -------------------------------------------------
- // Generate a Code128 barcode and save it to file
- // -------------------------------------------------
+ // Generate a Code128 barcode; the checksum is added automatically by the generator
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Save the generated barcode image to the temporary location
- generator.Save(imagePath);
+ generator.Save(imagePath, BarCodeImageFormat.Png);
}
- // -------------------------------------------------
- // Verify the barcode with checksum validation enabled
- // -------------------------------------------------
+ // Verify that the barcode image was successfully created
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine("Failed to create the barcode image.");
+ return;
+ }
+
+ // Initialize a reader for Code128 barcodes and enable checksum validation
using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
{
- // Turn on checksum validation for the reader
+ // Turn on checksum validation during the recognition process
reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
- bool anyResult = false;
+ // Attempt to read barcodes from the image
+ BarCodeResult[] results = reader.ReadBarCodes();
- // Iterate through all detected barcodes (should be only one)
- foreach (BarCodeResult result in reader.ReadBarCodes())
+ // If no results are returned, checksum validation has failed
+ if (results.Length == 0)
{
- anyResult = true;
- Console.WriteLine("Barcode detected:");
- Console.WriteLine(" CodeText : " + result.CodeText);
-
- // For Code128, checksum information is available in the extended 1D data
- if (result.Extended?.OneD != null)
- {
- Console.WriteLine(" Value : " + result.Extended.OneD.Value);
- Console.WriteLine(" CheckSum : " + result.Extended.OneD.CheckSum);
- }
- else
- {
- Console.WriteLine(" No extended 1D data available.");
- }
+ Console.WriteLine("Checksum validation failed: no valid barcode detected.");
}
-
- // If no barcode was read, report checksum validation failure
- if (!anyResult)
+ else
{
- Console.WriteLine("Checksum validation failed: no valid barcode detected.");
+ // Output the decoded text and checksum information for each detected barcode
+ foreach (var result in results)
+ {
+ Console.WriteLine($"CodeText: {result.CodeText}");
+ Console.WriteLine($"Checksum: {result.Extended.OneD.CheckSum}");
+ }
}
}
- // -------------------------------------------------
- // Clean up the temporary image file
- // -------------------------------------------------
- if (File.Exists(imagePath))
+ // Attempt to delete the temporary barcode image; ignore any errors during cleanup
+ try
{
- try
- {
- File.Delete(imagePath);
- }
- catch
- {
- // Ignore any cleanup errors
- }
+ File.Delete(imagePath);
+ }
+ catch
+ {
+ // No action needed if cleanup fails
}
}
}
\ No newline at end of file
diff --git a/barcode-reading-properties/export-barcode-type-text-region-and-orientation-to-json-file-for-downstream-consumption.cs b/barcode-reading-properties/export-barcode-type-text-region-and-orientation-to-json-file-for-downstream-consumption.cs
index bdd7e30..dab05e7 100644
--- a/barcode-reading-properties/export-barcode-type-text-region-and-orientation-to-json-file-for-downstream-consumption.cs
+++ b/barcode-reading-properties/export-barcode-type-text-region-and-orientation-to-json-file-for-downstream-consumption.cs
@@ -1,15 +1,16 @@
// Title: Export barcode details to JSON
-// Description: Demonstrates generating a barcode, reading its type, text, region, and orientation, and exporting this information to a JSON file for downstream consumption.
+// Description: Demonstrates generating barcodes, reading them back, and exporting type, text, region, and orientation to a JSON file for downstream processing.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showcasing how to use BarcodeGenerator for creating images and BarCodeReader for extracting metadata. Typical use cases include batch barcode creation, automated verification, and integration with downstream systems that consume JSON metadata. Developers often need to serialize barcode properties such as symbology, content, location, and rotation for reporting or further analysis.
// Prompt: Export barcode type, text, region, and orientation to a JSON file for downstream consumption.
-// Tags: barcode symbology, export, json, aspose.barcode, generation, recognition
+// Tags: barcode symbology generation recognition json serialization aspose.barcode
using System;
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;
namespace BarcodeExportExample
{
@@ -18,12 +19,11 @@ public class BarcodeInfo
{
public string Type { get; set; }
public string Text { get; set; }
- public RegionInfo Region { get; set; }
- public double Angle { get; set; }
+ public RectangleInfo Region { get; set; }
+ public double Orientation { get; set; }
}
- // DTO representing the bounding rectangle of a detected barcode
- public class RegionInfo
+ public class RectangleInfo
{
public float X { get; set; }
public float Y { get; set; }
@@ -32,70 +32,91 @@ public class RegionInfo
}
///
- /// Entry point for the barcode export example.
+ /// Demonstrates generating barcodes, reading them, and exporting their metadata to a JSON file.
///
class Program
{
///
- /// Generates a barcode image, reads its properties, and writes them to a JSON file.
+ /// Entry point of the example. Generates sample barcodes, reads them, and writes metadata to JSON.
///
static void Main()
{
- const string imagePath = "sample.png";
- const string jsonPath = "barcode_info.json";
-
- // Generate a sample barcode image using Code128 symbology
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ // Define sample barcodes with symbology, text, and rotation angle
+ var samples = new List<(BaseEncodeType encodeType, string codeText, float rotation)>
{
- generator.Save(imagePath);
- }
+ (EncodeTypes.Code128, "ABC123", 0f),
+ (EncodeTypes.QR, "https://example.com", 45f),
+ (EncodeTypes.DataMatrix, "DataMatrixSample", 90f)
+ };
- // Verify the image was created successfully
- if (!File.Exists(imagePath))
+ var generatedFiles = new List();
+ int index = 0;
+
+ // Generate barcode images based on the sample data
+ foreach (var sample in samples)
{
- Console.WriteLine($"Failed to create barcode image at '{imagePath}'.");
- return;
+ string imagePath = $"barcode_{index}.png";
+
+ using (var generator = new BarcodeGenerator(sample.encodeType, sample.codeText))
+ {
+ // Apply rotation if needed
+ generator.Parameters.RotationAngle = sample.rotation;
+
+ // Save the generated barcode image to disk
+ generator.Save(imagePath);
+ }
+
+ generatedFiles.Add(imagePath);
+ index++;
}
- // Collection to hold extracted barcode information
- var barcodeData = new List();
+ var results = new List();
- // Read barcodes from the generated image using all supported decode types
- using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ // Read each generated image and extract barcode information
+ foreach (var filePath in generatedFiles)
{
- foreach (var result in reader.ReadBarCodes())
+ if (!File.Exists(filePath))
{
- // Extract the bounding rectangle of the detected barcode
- var rect = result.Region.Rectangle;
+ Console.WriteLine($"File not found: {filePath}");
+ continue;
+ }
- // Populate the DTO with type, text, region, and orientation
- var info = new BarcodeInfo
+ using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
+ {
+ foreach (var result in reader.ReadBarCodes())
{
- Type = result.CodeTypeName,
- Text = result.CodeText,
- Region = new RegionInfo
+ var regionRect = result.Region.Rectangle;
+
+ // Populate DTO with extracted data
+ var info = new BarcodeInfo
{
- X = rect.X,
- Y = rect.Y,
- Width = rect.Width,
- Height = rect.Height
- },
- Angle = result.Region.Angle
- };
-
- // Add the DTO to the collection
- barcodeData.Add(info);
+ Type = result.CodeTypeName,
+ Text = result.CodeText,
+ Region = new RectangleInfo
+ {
+ X = regionRect.X,
+ Y = regionRect.Y,
+ Width = regionRect.Width,
+ Height = regionRect.Height
+ },
+ Orientation = result.Region.Angle
+ };
+
+ results.Add(info);
+ }
}
}
- // Serialize the collected data to a formatted JSON string
- var jsonOptions = new JsonSerializerOptions { WriteIndented = true };
- string json = JsonSerializer.Serialize(barcodeData, jsonOptions);
+ // Serialize the list of barcode information to a formatted JSON string
+ string jsonOutput = JsonSerializer.Serialize(
+ results,
+ new JsonSerializerOptions { WriteIndented = true });
- // Write the JSON output to the specified file
- File.WriteAllText(jsonPath, json);
+ // Write the JSON output to a file
+ string jsonPath = "barcode_info.json";
+ File.WriteAllText(jsonPath, jsonOutput);
- Console.WriteLine($"Exported barcode information to '{jsonPath}'.");
+ Console.WriteLine($"Exported barcode information to {jsonPath}");
}
}
}
\ No newline at end of file
diff --git a/barcode-reading-properties/extract-aztec-code-layer-count-and-compact-mode-flag-from-image-containing-aztec-barcodes.cs b/barcode-reading-properties/extract-aztec-code-layer-count-and-compact-mode-flag-from-image-containing-aztec-barcodes.cs
index b94feb9..7b75304 100644
--- a/barcode-reading-properties/extract-aztec-code-layer-count-and-compact-mode-flag-from-image-containing-aztec-barcodes.cs
+++ b/barcode-reading-properties/extract-aztec-code-layer-count-and-compact-mode-flag-from-image-containing-aztec-barcodes.cs
@@ -1,92 +1,86 @@
// Title: Extract Aztec Code layer count and compact mode flag
-// Description: Demonstrates how to read an Aztec barcode from an image and retrieve its layer count and compact mode flag using Aspose.BarCode.
+// Description: Demonstrates how to read an image with Aztec barcodes and retrieve the layer count and compact mode flag using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on Aztec symbology. It shows how to use BarCodeReader with DecodeType.Aztec, access extended Aztec parameters via the AztecExtendedParameters class, and handle property availability via reflection. Developers often need to extract detailed Aztec metadata such as layer count and compact mode for validation or analytics.
// Prompt: Extract Aztec Code layer count and compact mode flag from an image containing Aztec barcodes.
-// Tags: aztec, barcode, extraction, layer count, compact mode, aspose.barcode, csharp
+// Tags: aztec, barcode, extraction, layer count, compact mode, aspose.barcode, recognition
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.BarCode.Generation;
///
-/// Program to extract Aztec barcode layer count and compact mode flag from an image.
+/// Demonstrates extraction of Aztec barcode layer count and compact mode flag from an image.
///
class Program
{
///
- /// Entry point. Reads the specified image, detects Aztec barcodes, and prints their details.
+ /// Entry point. Reads the specified image, detects Aztec barcodes, and prints their metadata.
///
static void Main()
{
- // Path to the image containing the Aztec barcode.
+ // Path to the image containing Aztec barcode(s)
string imagePath = "aztec.png";
- // Verify that the image file exists before attempting to read it.
+ // Verify that the image file exists before attempting to read it
if (!File.Exists(imagePath))
{
- Console.WriteLine($"File not found: {imagePath}");
+ Console.WriteLine($"File not found: {Path.GetFullPath(imagePath)}");
return;
}
- // Initialize the barcode reader for Aztec symbology.
- using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.Aztec))
+ // Initialize a BarCodeReader configured for Aztec symbology
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Aztec))
{
bool anyFound = false;
- // Iterate through all detected barcodes in the image.
+ // Iterate through all detected barcodes in the image
foreach (BarCodeResult result in reader.ReadBarCodes())
{
anyFound = true;
- // Output basic barcode information.
- Console.WriteLine($"Barcode type: {result.CodeTypeName}");
- Console.WriteLine($"Codetext: {result.CodeText}");
+ // Retrieve Aztec‑specific extended parameters from the result
+ AztecExtendedParameters aztecParams = result.Extended.Aztec;
- // Access extended Aztec-specific information, if available.
- var aztecInfo = result.Extended?.Aztec;
- if (aztecInfo != null)
+ // ----- Extract layer count (if the property exists) -----
+ int layersCount = 0;
+ bool hasLayers = false;
+ var layersProp = typeof(AztecExtendedParameters).GetProperty("LayersCount");
+ if (layersProp != null && layersProp.PropertyType == typeof(int))
{
- // Use reflection to obtain LayersCount if the property exists.
- var layersProp = aztecInfo.GetType().GetProperty("LayersCount");
- if (layersProp != null)
- {
- int layers = (int)layersProp.GetValue(aztecInfo);
- Console.WriteLine($"Aztec layers count: {layers}");
- }
- else
- {
- Console.WriteLine("Aztec layers count: unavailable in this library version.");
- }
-
- // Use reflection to obtain SymbolMode if the property exists.
- var modeProp = aztecInfo.GetType().GetProperty("SymbolMode");
- if (modeProp != null)
- {
- object modeValue = modeProp.GetValue(aztecInfo);
- // Determine whether the mode is Compact, if the enum is present.
- bool isCompact = false;
- var enumType = modeValue?.GetType();
- if (enumType != null && Enum.IsDefined(enumType, "Compact"))
- {
- var compactValue = Enum.Parse(enumType, "Compact");
- isCompact = modeValue.Equals(compactValue);
- }
- Console.WriteLine($"Compact mode: {isCompact}");
- }
- else
- {
- Console.WriteLine("Compact mode flag: unavailable in this library version.");
- }
+ layersCount = (int)layersProp.GetValue(aztecParams);
+ hasLayers = true;
}
- else
+
+ // ----- Extract compact mode flag (if the property exists) -----
+ bool isCompact = false;
+ bool hasCompact = false;
+ var compactProp = typeof(AztecExtendedParameters).GetProperty("IsCompact");
+ if (compactProp != null && compactProp.PropertyType == typeof(bool))
{
- Console.WriteLine("No Aztec extended information available.");
+ isCompact = (bool)compactProp.GetValue(aztecParams);
+ hasCompact = true;
}
- Console.WriteLine();
+ // Output basic barcode information
+ Console.WriteLine($"Barcode Type: {result.CodeTypeName}");
+ Console.WriteLine($"Code Text : {result.CodeText}");
+
+ // Output extracted Aztec‑specific metadata
+ if (hasLayers)
+ Console.WriteLine($"Layers Count: {layersCount}");
+ else
+ Console.WriteLine("Layers Count: (property not available)");
+
+ if (hasCompact)
+ Console.WriteLine($"Compact Mode: {isCompact}");
+ else
+ Console.WriteLine("Compact Mode: (property not available)");
+
+ Console.WriteLine(new string('-', 40));
}
- // Inform the user if no Aztec barcodes were detected.
+ // Inform the user if no Aztec barcodes were found
if (!anyFound)
{
Console.WriteLine("No Aztec barcodes were detected in the image.");
diff --git a/barcode-reading-properties/extract-barcode-metadata-from-live-camera-feed-and-display-results-in-real-time.cs b/barcode-reading-properties/extract-barcode-metadata-from-live-camera-feed-and-display-results-in-real-time.cs
index a69253d..1608cca 100644
--- a/barcode-reading-properties/extract-barcode-metadata-from-live-camera-feed-and-display-results-in-real-time.cs
+++ b/barcode-reading-properties/extract-barcode-metadata-from-live-camera-feed-and-display-results-in-real-time.cs
@@ -1,58 +1,59 @@
-// Title: Extract barcode metadata from a generated image (simulated live feed)
-// Description: Demonstrates generating a barcode, reading its metadata, and displaying results, simulating a live camera feed scenario.
+// Title: Extract barcode metadata from generated image (simulated live feed)
+// Description: Generates a QR code, reads it, and outputs metadata such as type, text, confidence, and region.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It demonstrates using BarcodeGenerator to create barcodes and BarCodeReader to extract metadata, a common task for developers building scanning applications, inventory systems, or real‑time camera processing pipelines. The snippet shows key API classes (BarcodeGenerator, BarCodeReader, QualitySettings) and typical usage patterns for extracting barcode information.
// Prompt: Extract barcode metadata from live camera feed and display results in real time.
-// Tags: barcode symbology, metadata extraction, console output, aspose.barcode, csharp
+// Tags: barcode, qr, metadata, generation, recognition, realtime
using System;
-using Aspose.BarCode;
+using System.IO;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Demonstrates barcode metadata extraction using Aspose.BarCode.
+/// Demonstrates how to generate a QR code, read it, and display its metadata.
+/// This simulates the extraction logic that would be applied to each frame of a live camera feed.
///
class Program
{
///
- /// Entry point. Generates a sample barcode, reads its metadata, and prints details to the console.
+ /// Entry point of the example. Generates a barcode image, reads it, and prints metadata to the console.
///
static void Main()
{
- // The console runner cannot access a live camera feed.
- // Instead, we generate a sample barcode image and extract its metadata.
+ // NOTE: Real‑time live camera feed processing would require continuous monitoring,
+ // which is not possible in a self‑contained console example without external input.
+ // This sample generates a barcode image, reads it, and displays metadata,
+ // demonstrating the extraction logic that would be applied to each frame.
- // Create a barcode generator for Code128 with sample text.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ // Create a BarcodeGenerator for a QR code with sample text
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Sample QR Code"))
{
- // Generate the barcode image in memory.
- using (var bitmap = generator.GenerateBarCodeImage())
+ // Optional: configure visual appearance of the generated barcode
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+ generator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelM;
+
+ // Generate the barcode image in memory
+ using (Bitmap barcodeImage = generator.GenerateBarCodeImage())
{
- // Initialize a reader that can decode all supported barcode types.
- using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
+ // Initialize a BarCodeReader to decode any supported barcode type from the image
+ using (var reader = new BarCodeReader(barcodeImage, DecodeType.AllSupportedTypes))
{
- int processed = 0; // Counter to limit processing to the first barcode.
+ // Set recognition quality (default is NormalQuality)
+ reader.QualitySettings = QualitySettings.NormalQuality;
- // Iterate through all detected barcodes in the image.
+ // Iterate through all detected barcodes and output their metadata
foreach (var result in reader.ReadBarCodes())
{
- // Stop after processing the first detected barcode.
- if (processed >= 1) break;
-
- // Output basic barcode information.
- Console.WriteLine($"Barcode Type: {result.CodeTypeName}");
- Console.WriteLine($"Code Text: {result.CodeText}");
+ Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
+ Console.WriteLine($"BarCode CodeText: {result.CodeText}");
Console.WriteLine($"Confidence: {result.Confidence}");
Console.WriteLine($"Reading Quality: {result.ReadingQuality}");
- // Output the location and size of the barcode region.
- var region = result.Region.Rectangle;
- Console.WriteLine($"Region - X:{region.X}, Y:{region.Y}, Width:{region.Width}, Height:{region.Height}");
-
- // Output the rotation angle of the barcode region.
- Console.WriteLine($"Angle: {result.Region.Angle}");
-
- processed++; // Increment the processed counter.
+ // Retrieve 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(new string('-', 40));
}
}
}
diff --git a/barcode-reading-properties/extract-barcode-placement-region-coordinates-from-png-file-and-store-them-in-database.cs b/barcode-reading-properties/extract-barcode-placement-region-coordinates-from-png-file-and-store-them-in-database.cs
index acaa633..8c2ddf6 100644
--- a/barcode-reading-properties/extract-barcode-placement-region-coordinates-from-png-file-and-store-them-in-database.cs
+++ b/barcode-reading-properties/extract-barcode-placement-region-coordinates-from-png-file-and-store-them-in-database.cs
@@ -1,91 +1,101 @@
-// Title: Extract barcode region coordinates from PNG and save as JSON
-// Description: Demonstrates how to read a PNG image, detect barcodes, obtain their placement rectangles, and store the data for later use.
+// Title: Extract barcode region coordinates from PNG and save to JSON
+// Description: Demonstrates how to read a PNG image, detect barcodes, extract their placement region coordinates, and store the data.
+// Category-Description: This example belongs to the Aspose.BarCode barcode detection and region extraction category. It showcases the use of BarCodeReader to recognize all supported barcode types, retrieve the bounding rectangle of each detected barcode, and handle the resulting region data. Developers working with image processing, inventory systems, or document automation often need to locate barcodes within images for further processing or database storage.
// Prompt: Extract barcode placement region coordinates from a PNG file and store them in a database.
-// Tags: barcode, region extraction, png, json, aspose, csharp
+// Tags: barcode detection, barcode region extraction, png, json, aspose.barcode, barcodereader, region coordinates, data persistence
using System;
using System.IO;
using System.Collections.Generic;
using System.Text.Json;
+using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
namespace BarcodeRegionExtractor
{
///
- /// Represents a barcode detection result with its placement region.
+ /// Simple DTO to hold region information; in a real scenario this could be persisted to a database.
///
- public class BarcodeRegionRecord
+ public class BarcodeRegionInfo
{
- public string CodeType { get; set; }
- public string CodeText { get; set; }
- public float X { get; set; }
- public float Y { get; set; }
- public float Width { get; set; }
- public float Height { get; set; }
+ public string FileName { get; set; }
+ public int X { get; set; }
+ public int Y { get; set; }
+ public int Width { get; set; }
+ public int Height { get; set; }
}
///
- /// Entry point for the barcode region extraction example.
+ /// Program that extracts barcode placement regions from a PNG image and stores them.
///
class Program
{
///
- /// Reads a PNG image, detects barcodes, extracts their region coordinates,
- /// and writes the information to a JSON file (placeholder for database storage).
+ /// Entry point. Generates a sample barcode image if missing, reads barcodes, extracts region data, and saves to JSON.
///
static void Main()
{
- // Path to the PNG image containing barcodes.
- const string imagePath = "sample.png";
+ // Define folder for sample image and output JSON.
+ string folderPath = "Barcodes";
+ Directory.CreateDirectory(folderPath);
- // Verify that the image file exists before proceeding.
+ // Full path to the PNG file to be processed.
+ string imagePath = Path.Combine(folderPath, "sample.png");
+
+ // Generate a sample barcode image if it does not already exist.
+ if (!File.Exists(imagePath))
+ {
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ {
+ // Optional: configure size or colors here.
+ generator.Save(imagePath, BarCodeImageFormat.Png);
+ }
+ Console.WriteLine($"Generated sample barcode image at: {imagePath}");
+ }
+
+ // Verify the image file exists before attempting to read it.
if (!File.Exists(imagePath))
{
- Console.WriteLine($"Image file not found: {imagePath}");
+ Console.WriteLine($"Error: File not found - {imagePath}");
return;
}
- // Collection to hold detection results.
- var records = new List();
+ // Collection to hold extracted region information.
+ var regions = new List();
- // Initialize BarCodeReader to detect all supported barcode types.
+ // Use BarCodeReader to detect all supported barcode types in the image.
using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
- // Iterate through each detected barcode.
foreach (var result in reader.ReadBarCodes())
{
- // Retrieve the bounding rectangle of the detected barcode.
- var rect = result.Region.Rectangle;
+ // Obtain the bounding rectangle of the detected barcode.
+ Rectangle rect = result.Region.Rectangle;
- // Populate a record with barcode details and region coordinates.
- var record = new BarcodeRegionRecord
+ // Populate DTO with region data.
+ var info = new BarcodeRegionInfo
{
- CodeType = result.CodeTypeName,
- CodeText = result.CodeText,
+ FileName = imagePath,
X = rect.X,
Y = rect.Y,
Width = rect.Width,
Height = rect.Height
};
- // Add the record to the collection.
- records.Add(record);
+ regions.Add(info);
- // Output detection details to the console for verification.
- Console.WriteLine($"Detected {record.CodeType}: \"{record.CodeText}\" at [{record.X}, {record.Y}, {record.Width}, {record.Height}]");
+ // Output detection details to console.
+ Console.WriteLine($"Detected barcode: {result.CodeText}");
+ Console.WriteLine($"Region - X:{rect.X}, Y:{rect.Y}, Width:{rect.Width}, Height:{rect.Height}");
}
}
- // Serialize the results to JSON (acting as a stand‑in for database storage).
- const string outputPath = "barcode_regions.json";
- var jsonOptions = new JsonSerializerOptions { WriteIndented = true };
- string json = JsonSerializer.Serialize(records, jsonOptions);
- File.WriteAllText(outputPath, json);
- Console.WriteLine($"Barcode region data written to {outputPath}");
-
- // In a production scenario, replace the JSON file write with actual database insertion logic,
- // such as using Entity Framework or ADO.NET to persist records.
+ // Serialize the extracted region data to JSON as a stand‑in for database storage.
+ string jsonPath = Path.Combine(folderPath, "barcode_regions.json");
+ string json = JsonSerializer.Serialize(regions, new JsonSerializerOptions { WriteIndented = true });
+ File.WriteAllText(jsonPath, json);
+ Console.WriteLine($"Region data saved to: {jsonPath}");
}
}
}
\ No newline at end of file
diff --git a/barcode-reading-properties/extract-gs1-composite-component-count-and-application-identifiers-from-png-image.cs b/barcode-reading-properties/extract-gs1-composite-component-count-and-application-identifiers-from-png-image.cs
index 4ad15d2..ffd6034 100644
--- a/barcode-reading-properties/extract-gs1-composite-component-count-and-application-identifiers-from-png-image.cs
+++ b/barcode-reading-properties/extract-gs1-composite-component-count-and-application-identifiers-from-png-image.cs
@@ -1,82 +1,98 @@
-// Title: Extract GS1 Composite component count and AIs from PNG
-// Description: Demonstrates reading a GS1 Composite barcode from a PNG image, retrieving the linear and 2D component texts, counting application identifiers, and reporting component count.
+// Title: Extract GS1 Composite component count and application identifiers from a PNG image
+// Description: Demonstrates how to generate a GS1 Composite barcode image if missing, then read it to obtain the component count and AI list.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on GS1 Composite barcodes. It showcases the use of BarcodeGenerator for creating sample barcodes and BarCodeReader with DecodeType.GS1CompositeBar to extract extended GS1 Composite data such as component count and application identifiers. Developers working with supply‑chain labeling, inventory tracking, or any GS1‑based systems can use these APIs to validate and parse composite barcodes.
// Prompt: Extract GS1 Composite component count and application identifiers from a PNG image.
-// Tags: gs1 composite, barcode reading, png, aspose.barcode, csharp
+// Tags: gs1 composite, barcode recognition, barcode generation, png, aspnet.barcode, extended data, application identifiers
using System;
using System.IO;
-using System.Text.RegularExpressions;
-using Aspose.BarCode;
+using System.Reflection;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Program to extract GS1 Composite component count and application identifiers from a PNG image.
+/// Example program that creates (if necessary) a GS1 Composite barcode image
+/// and extracts its component count and application identifiers using Aspose.BarCode.
///
class Program
{
///
- /// Entry point. Reads the PNG, extracts barcode data, and displays component texts, AI count, and component count.
+ /// Entry point. Generates a sample barcode when missing, then reads the image
+ /// to display GS1 Composite extended information.
///
static void Main()
{
- // Path to the PNG image containing the GS1 Composite barcode
const string imagePath = "gs1composite.png";
- // Verify that the image file exists before attempting to read it
+ // ------------------------------------------------------------
+ // Ensure a sample image exists; create one if it does not.
+ // ------------------------------------------------------------
if (!File.Exists(imagePath))
{
- Console.WriteLine($"File not found: {imagePath}");
- return;
+ // Generate a GS1 Composite barcode with linear and 2‑D components.
+ using (var generator = new BarcodeGenerator(EncodeTypes.GS1CompositeBar, "(01)01234567890123|(21)ABC123"))
+ {
+ // Specify the component types explicitly (optional).
+ generator.Parameters.Barcode.GS1CompositeBar.LinearComponentType = EncodeTypes.GS1Code128;
+ generator.Parameters.Barcode.GS1CompositeBar.TwoDComponentType = TwoDComponentType.CC_A;
+
+ // Save the generated barcode image to disk.
+ generator.Save(imagePath);
+ Console.WriteLine($"Sample barcode created at: {Path.GetFullPath(imagePath)}");
+ }
}
- // Create a BarCodeReader configured for GS1 Composite Bar symbology
+ // ------------------------------------------------------------
+ // Read the barcode and extract GS1 Composite extended data.
+ // ------------------------------------------------------------
using (var reader = new BarCodeReader(imagePath, DecodeType.GS1CompositeBar))
{
- // Read all barcodes present in the image
- var results = reader.ReadBarCodes();
-
- // If no barcodes were detected, inform the user and exit
- if (results.Length == 0)
+ foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine("No barcodes detected.");
- return;
- }
+ Console.WriteLine($"Detected CodeText: {result.CodeText}");
- // Process each detected barcode result
- foreach (var result in results)
- {
- // Access extended GS1 Composite parameters (linear and 2D components)
+ // Access the GS1 Composite extended information.
var gs1Ext = result.Extended.GS1CompositeBar;
+ if (gs1Ext == null)
+ {
+ Console.WriteLine("No GS1 Composite extended data available.");
+ continue;
+ }
- // Retrieve the linear (1D) component text; use empty string if null
- string linearText = gs1Ext.OneDCodeText ?? string.Empty;
- // Retrieve the 2D component text; use empty string if null
- string twoDText = gs1Ext.TwoDCodeText ?? string.Empty;
-
- Console.WriteLine($"Linear component text: {linearText}");
- Console.WriteLine($"2D component text: {twoDText}");
-
- // Use a regular expression to find all Application Identifiers (AIs) in the linear component
- var aiMatches = Regex.Matches(linearText, @"\((\d{2,4})\)");
- int aiCount = aiMatches.Count;
-
- Console.WriteLine($"Number of Application Identifiers: {aiCount}");
+ // ----- Component count (via reflection to stay safe against API changes) -----
+ var compCountProp = gs1Ext.GetType().GetProperty("ComponentCount", BindingFlags.Public | BindingFlags.Instance);
+ if (compCountProp != null)
+ {
+ var countValue = compCountProp.GetValue(gs1Ext);
+ Console.WriteLine($"Component Count: {countValue}");
+ }
+ else
+ {
+ Console.WriteLine("ComponentCount property not found.");
+ }
- // If any AIs were found, list them
- if (aiCount > 0)
+ // ----- Application identifiers (via reflection) -----
+ var aiProp = gs1Ext.GetType().GetProperty("ApplicationIdentifiers", BindingFlags.Public | BindingFlags.Instance);
+ if (aiProp != null)
{
- Console.WriteLine("Application Identifiers:");
- foreach (Match match in aiMatches)
+ var ais = aiProp.GetValue(gs1Ext) as string[];
+ if (ais != null && ais.Length > 0)
{
- // Extract the numeric AI without parentheses
- string ai = match.Groups[1].Value;
- Console.WriteLine($"- {ai}");
+ Console.WriteLine("Application Identifiers:");
+ foreach (var ai in ais)
+ {
+ Console.WriteLine($" {ai}");
+ }
+ }
+ else
+ {
+ Console.WriteLine("No Application Identifiers found.");
}
}
-
- // GS1 Composite always consists of two components: linear and 2D
- Console.WriteLine($"GS1 Composite component count: 2");
- Console.WriteLine();
+ else
+ {
+ Console.WriteLine("ApplicationIdentifiers property not found.");
+ }
}
}
}
diff --git a/barcode-reading-properties/extract-pdf417-structured-append-sequence-number-and-total-count-from-multi-segment-pdf417-codes.cs b/barcode-reading-properties/extract-pdf417-structured-append-sequence-number-and-total-count-from-multi-segment-pdf417-codes.cs
index 0c3bee9..2904293 100644
--- a/barcode-reading-properties/extract-pdf417-structured-append-sequence-number-and-total-count-from-multi-segment-pdf417-codes.cs
+++ b/barcode-reading-properties/extract-pdf417-structured-append-sequence-number-and-total-count-from-multi-segment-pdf417-codes.cs
@@ -1,70 +1,99 @@
-// Title: Extract PDF417 Structured‑Append Sequence Information
-// Description: Demonstrates how to read multi‑segment PDF417 barcodes and retrieve the structured‑append sequence number and total segment count.
+// Title: Extract PDF417 Structured‑Append Sequence Number and Total Count
+// Description: Demonstrates how to generate multi‑segment PDF417 barcodes with Macro PDF417 properties and read back the sequence number and total segment count.
+// Category-Description: This example belongs to the Aspose.BarCode PDF417 macro (structured‑append) operations collection. It shows usage of BarcodeGenerator for creating Macro PDF417 barcodes and BarCodeReader with DecodeType.MacroPdf417 to retrieve extended PDF417 metadata such as segment ID and segment count. Developers working with large data payloads split across multiple PDF417 symbols can use these APIs to assemble the original data correctly.
// Prompt: Extract PDF417 structured‑append sequence number and total count from multi‑segment PDF417 codes.
-// Tags: pdf417, structured-append, barcode, recognition, aspose.barcode, csharp
+// Tags: pdf417, structured-append, macro, barcode-generation, barcode-recognition, aspnet, csharp
using System;
using System.IO;
using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that extracts structured‑append information from PDF417 barcodes.
+/// Generates a set of Macro PDF417 barcode segments and then reads each segment
+/// to extract the structured‑append (Macro PDF417) sequence number and total segment count.
///
class Program
{
///
- /// Entry point. Reads an image file, detects PDF417 barcodes, and prints their structured‑append details.
+ /// Entry point of the example. Creates barcode images, saves them to disk,
+ /// and reads back the Macro PDF417 metadata from each image.
///
static void Main()
{
- // Path to the image containing PDF417 barcode segments.
- const string imagePath = "pdf417_multi.png";
-
- // Verify that the image file exists before attempting to read it.
- if (!File.Exists(imagePath))
+ // --------------------------------------------------------------------
+ // Prepare output folder for generated barcode images
+ // --------------------------------------------------------------------
+ string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(folderPath))
{
- Console.WriteLine($"File not found: {imagePath}");
- return;
+ Directory.CreateDirectory(folderPath);
}
- // Open the image file as a read‑only stream.
- using (var stream = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
- // Initialise a barcode reader configured for PDF417 symbology.
- using (var reader = new BarCodeReader(stream, DecodeType.Pdf417))
+ // --------------------------------------------------------------------
+ // Define Macro PDF417 parameters (same file ID for all segments)
+ // --------------------------------------------------------------------
+ int totalSegments = 3; // total number of segments to generate
+ int fileId = 12345; // identifier shared by all segments
+
+ // --------------------------------------------------------------------
+ // Generate sample PDF417 segments with Macro PDF417 properties
+ // --------------------------------------------------------------------
+ for (int i = 0; i < totalSegments; i++)
{
- bool anyFound = false;
+ string fileName = Path.Combine(folderPath, $"segment_{i}.png");
- // Iterate through all recognized barcodes in the image.
- foreach (BarCodeResult result in reader.ReadBarCodes())
+ // Create a barcode generator for PDF417 and assign segment‑specific data
+ using (var generator = new BarcodeGenerator(EncodeTypes.Pdf417, $"Segment_{i + 1}"))
{
- anyFound = true;
- Console.WriteLine($"Code Text: {result.CodeText}");
+ // Set Macro PDF417 (structured‑append) properties
+ generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = fileId; // common file identifier
+ generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = i; // sequence number (0‑based)
+ generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = totalSegments; // total segment count
- // Structured Append information is stored in the PDF417 extended parameters.
- var pdf417Ext = result.Extended?.Pdf417;
- if (pdf417Ext != null)
- {
- // MacroPdf417FileID corresponds to the file identifier.
- // MacroPdf417SegmentID corresponds to the sequence number (starts from 0).
- // MacroPdf417SegmentsCount corresponds to the total number of segments.
- Console.WriteLine($"Structured Append File ID : {pdf417Ext.MacroPdf417FileID}");
- Console.WriteLine($"Structured Append Sequence : {pdf417Ext.MacroPdf417SegmentID}");
- Console.WriteLine($"Structured Append Total : {pdf417Ext.MacroPdf417SegmentsCount}");
- }
- else
- {
- Console.WriteLine("No structured-append information available for this barcode.");
- }
+ // Save the generated barcode image to disk
+ generator.Save(fileName);
+ }
+ }
- // Separator for readability between barcode entries.
- Console.WriteLine(new string('-', 40));
+ Console.WriteLine("Reading structured‑append information from generated barcodes:");
+
+ // --------------------------------------------------------------------
+ // Read each barcode image and extract Macro PDF417 metadata
+ // --------------------------------------------------------------------
+ for (int i = 0; i < totalSegments; i++)
+ {
+ string fileName = Path.Combine(folderPath, $"segment_{i}.png");
+
+ // Verify that the image file exists before attempting to read it
+ if (!File.Exists(fileName))
+ {
+ Console.WriteLine($"File not found: {fileName}");
+ continue;
}
- // Inform the user if no PDF417 barcodes were detected.
- if (!anyFound)
+ // Use BarCodeReader with DecodeType.MacroPdf417 to access extended data
+ using (var reader = new BarCodeReader(fileName, DecodeType.MacroPdf417))
{
- Console.WriteLine("No PDF417 barcodes were detected in the image.");
+ foreach (BarCodeResult result in reader.ReadBarCodes())
+ {
+ // Extended parameters contain Macro PDF417 metadata, if present
+ var pdf417Ext = result.Extended?.Pdf417;
+ if (pdf417Ext != null)
+ {
+ int segmentId = pdf417Ext.MacroPdf417SegmentID; // sequence number of this segment
+ int segmentsCount = pdf417Ext.MacroPdf417SegmentsCount; // total number of segments
+
+ Console.WriteLine($"File: {Path.GetFileName(fileName)}");
+ Console.WriteLine($" Segment ID (sequence number): {segmentId}");
+ Console.WriteLine($" Total Segments: {segmentsCount}");
+ }
+ else
+ {
+ Console.WriteLine($"No Macro PDF417 metadata found in {Path.GetFileName(fileName)}");
+ }
+ }
}
}
}
diff --git a/barcode-reading-properties/fetch-image-from-azure-blob-storage-and-extract-barcode-type-and-code-text.cs b/barcode-reading-properties/fetch-image-from-azure-blob-storage-and-extract-barcode-type-and-code-text.cs
index 74dff4c..3f427a1 100644
--- a/barcode-reading-properties/fetch-image-from-azure-blob-storage-and-extract-barcode-type-and-code-text.cs
+++ b/barcode-reading-properties/fetch-image-from-azure-blob-storage-and-extract-barcode-type-and-code-text.cs
@@ -1,67 +1,58 @@
-// Title: Read barcode from image (local fallback)
-// Description: Demonstrates fetching an image (placeholder for Azure Blob) and extracting barcode type and text using Aspose.BarCode.
+// Title: Extract barcode information from an image stored in Azure Blob Storage
+// Description: Demonstrates how to download an image from Azure Blob storage (illustrated as a placeholder) and use Aspose.BarCode to recognize barcode type and text.
+// Category-Description: This example belongs to the Aspose.BarCode recognition category, showcasing the BarCodeReader class for decoding various symbologies from image streams. Typical use cases include processing scanned documents, inventory images, or any media retrieved from cloud storage. Developers often need to integrate Azure Blob retrieval with barcode extraction for automated workflows.
// Prompt: Fetch image from Azure Blob storage and extract barcode type and code text.
-// Tags: barcode symbology, read, console, aspose.barcode, azure blob
+// Tags: barcode recognition, azure blob storage, decode type, image processing, aspose.barcode
using System;
using System.IO;
-using Aspose.BarCode.Generation;
+using Aspose.BarCode;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
///
-/// Example program that reads barcodes from an image.
-/// In a real scenario the image would be downloaded from Azure Blob storage,
-/// but this demo uses a local file as a fallback.
+/// Sample program that demonstrates how to obtain an image from Azure Blob storage
+/// (shown as a commented placeholder) and extract barcode information using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application.
- /// Loads an image, scans for barcodes, and prints their type and text.
+ /// Entry point of the example. Reads an image, creates a BarCodeReader,
+ /// and prints detected barcode types and their corresponding text values.
///
static void Main()
{
- // NOTE: In a real environment you would download the image from Azure Blob Storage
- // using Azure.Storage.Blobs. The required SDK is not available in the snippet runner,
- // so the code is provided as a comment for reference.
+ // NOTE: In a real environment you would download the image from Azure Blob Storage.
+ // The Azure SDK is not available in the snippet runner, so the code is shown as a comment.
/*
- // Real Azure Blob download (requires Azure.Storage.Blobs NuGet package)
- string connectionString = "";
- string containerName = "";
- string blobName = "";
- var blobClient = new BlobClient(connectionString, containerName, blobName);
- using (var downloadStream = new MemoryStream())
- {
- blobClient.DownloadTo(downloadStream);
- downloadStream.Position = 0;
- // Proceed with barcode reading using the stream
- }
+ // Azure Blob Storage example (requires Azure.Storage.Blobs NuGet package)
+ // string connectionString = "";
+ // string containerName = "";
+ // string blobName = "";
+ // var blobClient = new BlobClient(connectionString, containerName, blobName);
+ // using var memoryStream = new MemoryStream();
+ // blobClient.DownloadTo(memoryStream);
+ // memoryStream.Position = 0;
+ // ProcessImageStream(memoryStream);
*/
- // Fallback: use a local image file for demonstration
- string localImagePath = "sample.png";
+ // Local fallback image for the runnable example
+ string imagePath = "sample.png";
- // Verify that the image file exists before proceeding
- if (!File.Exists(localImagePath))
+ // Verify that the image file exists before attempting to read it
+ if (!File.Exists(imagePath))
{
- Console.WriteLine($"Image file not found: {localImagePath}");
+ Console.WriteLine($"Image file not found: {imagePath}");
return;
}
- // Load the image into a Bitmap (Aspose.Drawing)
- using (Bitmap bitmap = new Bitmap(localImagePath))
+ // Initialize BarCodeReader to scan all supported barcode types in the image file
+ using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
- // Initialize the barcode reader with the bitmap and enable all supported types
- using (BarCodeReader reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
+ // Iterate through all detected barcodes and output their type and text
+ foreach (var result in reader.ReadBarCodes())
{
- // Iterate through detected barcodes
- foreach (BarCodeResult result in reader.ReadBarCodes())
- {
- // Output the barcode type (e.g., QR, Code128) and its decoded text
- Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
- Console.WriteLine($"BarCode CodeText: {result.CodeText}");
- }
+ Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
+ Console.WriteLine($"BarCode CodeText: {result.CodeText}");
}
}
}
diff --git a/barcode-reading-properties/handle-password-protected-image-files-by-supplying-credentials-before-barcode-detection-in-secure-pipelines.cs b/barcode-reading-properties/handle-password-protected-image-files-by-supplying-credentials-before-barcode-detection-in-secure-pipelines.cs
index c8d7dc8..be185a5 100644
--- a/barcode-reading-properties/handle-password-protected-image-files-by-supplying-credentials-before-barcode-detection-in-secure-pipelines.cs
+++ b/barcode-reading-properties/handle-password-protected-image-files-by-supplying-credentials-before-barcode-detection-in-secure-pipelines.cs
@@ -1,100 +1,126 @@
-// Title: Detect barcodes in password‑protected images by supplying credentials
-// Description: Demonstrates loading a password‑protected image (simulated) and detecting any barcodes it contains using Aspose.BarCode.
+// Title: Detect Barcodes in Password‑Protected PDFs and Images
+// Description: Demonstrates loading a password‑protected PDF (or regular image), converting it to a bitmap, and reading barcodes using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating how to handle secure image sources. It shows using Aspose.Pdf to open password‑protected PDFs, converting pages to images with Aspose.Drawing, and reading barcodes with BarCodeReader. Developers often need to process protected documents in automated pipelines, requiring credential handling and robust detection.
// Prompt: Handle password‑protected image files by supplying credentials before barcode detection in secure pipelines.
-// Tags: barcode symbology, detection, image, aspose.barcode, credentials
+// Tags: barcode detection, pdf password, aspose.barcode, aspose.pdf, image processing, barcodereader, decodeall
using System;
using System.IO;
-using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
+using Aspose.Pdf;
+using Aspose.Pdf.Facades;
///
-/// Example program that generates a barcode, simulates a password‑protected image,
-/// and reads barcodes from the image using Aspose.BarCode.
+/// Example program that loads a password‑protected PDF (or a regular image),
+/// converts it to a bitmap, and detects barcodes using Aspose.BarCode.
///
class Program
{
///
- /// Entry point. Generates a sample barcode, copies it to a simulated protected file,
- /// and reads any barcodes present.
+ /// Entry point of the application.
///
static void Main()
{
- // --------------------------------------------------------------------
- // 1. Generate a sample barcode image (used later for detection)
- // --------------------------------------------------------------------
- const string barcodePath = "sample_barcode.png";
- const string barcodeText = "Secure123";
+ // Path to the input file (could be a password‑protected PDF or a regular image)
+ string inputPath = "protected.pdf";
+ // Password for the protected PDF (if applicable)
+ string pdfPassword = "secret";
- // Create the barcode image only if it does not already exist
- if (!File.Exists(barcodePath))
+ // If the file does not exist, create a simple barcode image to demonstrate the flow.
+ if (!File.Exists(inputPath))
{
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, barcodeText))
+ Console.WriteLine($"File '{inputPath}' not found. Generating a sample barcode image.");
+
+ // Generate a sample Code128 barcode image.
+ using (var generator = new Aspose.BarCode.Generation.BarcodeGenerator(
+ Aspose.BarCode.Generation.EncodeTypes.Code128, "Sample123"))
{
- generator.Save(barcodePath);
- Console.WriteLine($"Generated barcode image: {barcodePath}");
+ string sampleImagePath = "sample.png";
+ generator.Save(sampleImagePath);
+ inputPath = sampleImagePath; // Use the generated image for reading.
}
}
- // --------------------------------------------------------------------
- // 2. Prepare a simulated password‑protected image file
- // --------------------------------------------------------------------
- const string protectedImagePath = "protected_image.png";
+ // Determine processing based on file extension.
+ string extension = Path.GetExtension(inputPath).ToLowerInvariant();
+
+ // Bitmap that will hold the image to be scanned.
+ Aspose.Drawing.Bitmap barcodeBitmap = null;
- // For demonstration, copy the generated barcode to the protected image path.
- // In a real scenario, this file would be password‑protected and require credentials.
- if (!File.Exists(protectedImagePath))
+ if (extension == ".pdf")
{
- File.Copy(barcodePath, protectedImagePath);
+ // Handle password‑protected PDF.
+ try
+ {
+ // Load the PDF with the supplied password.
+ var pdfDocument = new Document(inputPath, pdfPassword);
+
+ // Convert the first page to an image.
+ var pdfConverter = new PdfConverter(pdfDocument);
+ pdfConverter.RenderingOptions.BarcodeOptimization = true;
+ pdfConverter.StartPage = 1;
+ pdfConverter.EndPage = 1;
+ pdfConverter.DoConvert();
+
+ using (var imageStream = new MemoryStream())
+ {
+ pdfConverter.GetNextImage(imageStream);
+ imageStream.Position = 0;
+ barcodeBitmap = new Aspose.Drawing.Bitmap(imageStream);
+ }
+
+ pdfConverter.Close();
+ pdfDocument.Dispose();
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Failed to open PDF: {ex.Message}");
+ return;
+ }
+ }
+ else
+ {
+ // Assume a regular image file.
+ try
+ {
+ barcodeBitmap = new Aspose.Drawing.Bitmap(inputPath);
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Failed to load image: {ex.Message}");
+ return;
+ }
}
- // Verify that the protected image file exists before proceeding
- if (!File.Exists(protectedImagePath))
+ // Ensure the bitmap was created.
+ if (barcodeBitmap == null)
{
- Console.WriteLine($"Error: File not found - {protectedImagePath}");
+ Console.WriteLine("No image available for barcode detection.");
return;
}
- // --------------------------------------------------------------------
- // 3. Simulated credentials for a protected image
- // --------------------------------------------------------------------
- // Aspose.BarCode does not directly support password handling for images.
- // In a real implementation, you would use the appropriate Aspose product
- // (e.g., Aspose.Pdf, Aspose.Imaging) to open the protected file with credentials,
- // then pass the resulting bitmap to BarCodeReader.
- string username = "user";
- string password = "pass";
-
- // Placeholder for real protected image loading logic:
- // -------------------------------------------------
- // // Example using Aspose.Pdf (not available in the snippet runner):
- // // var pdfDoc = new Aspose.Pdf.Document(protectedImagePath, new Aspose.Pdf.LoadOptions { Password = password });
- // // var page = pdfDoc.Pages[1];
- // // using (var bitmap = page.ConvertToImage(Aspose.Pdf.Devices.Resolution.Default))
- // // {
- // // ProcessBarcode(bitmap);
- // // }
- // -------------------------------------------------
-
- // Since we cannot load a protected image here, load the image directly.
- using (var bitmap = new Bitmap(protectedImagePath))
+ // Perform barcode detection.
+ using (barcodeBitmap)
+ using (var reader = new BarCodeReader(barcodeBitmap, DecodeType.AllSupportedTypes))
{
- // ----------------------------------------------------------------
- // 4. Initialize BarCodeReader for all supported barcode types
- // ----------------------------------------------------------------
- using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
+ // Optional: improve detection of damaged barcodes.
+ reader.QualitySettings.AllowIncorrectBarcodes = true;
+
+ int count = 0;
+ foreach (var result in reader.ReadBarCodes())
{
- // Optional: improve detection of damaged or low‑quality barcodes
- reader.QualitySettings.AllowIncorrectBarcodes = true;
+ Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}");
+ Console.WriteLine($"Code Text: {result.CodeText}");
+ count++;
- // Iterate through all detected barcodes and output their details
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}");
- Console.WriteLine($"Detected Code Text: {result.CodeText}");
- }
+ // Limit to first 5 barcodes for safety.
+ if (count >= 5)
+ break;
}
+
+ if (count == 0)
+ Console.WriteLine("No barcodes were detected in the image.");
}
}
}
\ No newline at end of file
diff --git a/barcode-reading-properties/identify-micro-pdf417-code128-emulation-flag-and-handle-accordingly-in-processing-logic.cs b/barcode-reading-properties/identify-micro-pdf417-code128-emulation-flag-and-handle-accordingly-in-processing-logic.cs
index 368add3..40f2726 100644
--- a/barcode-reading-properties/identify-micro-pdf417-code128-emulation-flag-and-handle-accordingly-in-processing-logic.cs
+++ b/barcode-reading-properties/identify-micro-pdf417-code128-emulation-flag-and-handle-accordingly-in-processing-logic.cs
@@ -1,7 +1,8 @@
-// Title: MicroPdf417 Code128 Emulation Detection Example
-// Description: Demonstrates generating MicroPdf417 barcodes with and without the Code128 emulation flag and reading the flag during decoding.
+// Title: Micro PDF417 Barcode Generation with Code128 Emulation
+// Description: Demonstrates generating a Micro PDF417 barcode with Code128 emulation enabled and reading back the emulation flag.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It shows how to use BarcodeGenerator to create a MicroPdf417 symbol, configure the Pdf417.IsCode128Emulation property, and then employ BarCodeReader to decode the image and inspect the Extended.Pdf417.IsCode128Emulation flag. Developers working with compact PDF417 variants or needing Code128 emulation for legacy systems can reference this pattern.
// Prompt: Identify Micro PDF417 Code128 emulation flag and handle accordingly in processing logic.
-// Tags: barcode, micropdf417, code128, emulation, generation, recognition, aspose
+// Tags: barcode symbology, generation, recognition, micropdf417, code128, emulation, aspose.barcode
using System;
using System.IO;
@@ -10,103 +11,52 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that shows how to work with the MicroPdf417 Code128 emulation flag:
-/// - Generates two barcodes (with and without the flag)
-/// - Reads each barcode and inspects the emulation flag
+/// Generates a Micro PDF417 barcode with Code128 emulation enabled,
+/// saves it to an image file, and then reads the barcode back to
+/// verify the emulation flag.
///
class Program
{
///
- /// Entry point of the example. Generates barcode images, then reads and processes them.
+ /// Entry point of the example. Performs barcode creation,
+ /// image saving, and decoding with flag inspection.
///
static void Main()
{
- // Sample codetext for MicroPdf417 Code128 emulation (Application Indicator + FNC1 separator)
- string codeText = "a\u001d1234567890";
+ // Path for the generated barcode image
+ string outputPath = "micropdf417.png";
- // Paths for temporary image files (saved in the current working directory)
- string imagePathEmulation = Path.Combine(Directory.GetCurrentDirectory(), "micropdf417_emulation.png");
- string imagePathNormal = Path.Combine(Directory.GetCurrentDirectory(), "micropdf417_normal.png");
+ // Sample codetext: Application Indicator "a" followed by FNC1 (group separator) and data
+ string codeText = "a\u001d1222322323";
- // -------------------------------------------------
- // 1. Generate MicroPdf417 with Code128 emulation flag
- // -------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, codeText))
+ // Create a MicroPdf417 barcode generator with the sample codetext
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, codeText))
{
- // Enable Code128 emulation mode for the generated symbol
+ // Enable Code128 emulation mode (required for MicroPdf417)
generator.Parameters.Barcode.Pdf417.IsCode128Emulation = true;
- // Save image (optional, just for visual verification)
- generator.Save(imagePathEmulation);
+ // Save the generated barcode image to a PNG file
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
- // -------------------------------------------------
- // 2. Generate MicroPdf417 without Code128 emulation flag
- // -------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, codeText))
+ // Verify that the image was created successfully
+ if (!File.Exists(outputPath))
{
- // Do NOT set IsCode128Emulation (defaults to false)
- generator.Save(imagePathNormal);
- }
-
- // -------------------------------------------------
- // 3. Read and process the barcode with emulation flag
- // -------------------------------------------------
- Console.WriteLine("Reading barcode with Code128 emulation flag set:");
- ProcessBarcodeImage(imagePathEmulation);
-
- // -------------------------------------------------
- // 4. Read and process the barcode without emulation flag
- // -------------------------------------------------
- Console.WriteLine("\nReading barcode without Code128 emulation flag:");
- ProcessBarcodeImage(imagePathNormal);
- }
-
- ///
- /// Reads a barcode image, extracts the Code128 emulation flag, and outputs handling information.
- ///
- /// Full path to the barcode image file.
- static void ProcessBarcodeImage(string imagePath)
- {
- // Verify that the image file exists before attempting to read it
- if (!File.Exists(imagePath))
- {
- Console.WriteLine($"File not found: {imagePath}");
+ Console.WriteLine("Failed to create the barcode image.");
return;
}
- // Use MicroPdf417 decode type to correctly interpret the symbol
- using (var reader = new BarCodeReader(imagePath, DecodeType.MicroPdf417))
+ // Read the barcode from the saved image and inspect the emulation flag
+ using (BarCodeReader reader = new BarCodeReader(outputPath, DecodeType.MicroPdf417))
{
- bool anyFound = false;
-
- // Iterate through all detected barcodes in the image
foreach (BarCodeResult result in reader.ReadBarCodes())
{
- anyFound = true;
+ // Output the decoded text
+ Console.WriteLine("Decoded CodeText: " + result.CodeText);
- // The IsCode128Emulation property indicates whether the barcode was generated in emulation mode
+ // The extended PDF417 information contains the IsCode128Emulation flag
bool isEmulation = result.Extended.Pdf417.IsCode128Emulation;
-
- // Output basic barcode information
- Console.WriteLine($"CodeText: {result.CodeText}");
- Console.WriteLine($"IsCode128Emulation: {isEmulation}");
-
- // Custom handling based on the emulation flag
- if (isEmulation)
- {
- Console.WriteLine("-> Detected Code128 emulation mode. Process accordingly.");
- }
- else
- {
- Console.WriteLine("-> Standard MicroPdf417 mode.");
- }
- }
-
- // Inform the user if no barcodes were detected
- if (!anyFound)
- {
- Console.WriteLine("No barcodes were detected in the image.");
+ Console.WriteLine("IsCode128Emulation flag: " + isEmulation);
}
}
}
diff --git a/barcode-reading-properties/identify-qr-code-structured-append-metadata-using-qrextendedparameters-for-multi-segment-qr-codes-in-images.cs b/barcode-reading-properties/identify-qr-code-structured-append-metadata-using-qrextendedparameters-for-multi-segment-qr-codes-in-images.cs
index fbc2600..543f443 100644
--- a/barcode-reading-properties/identify-qr-code-structured-append-metadata-using-qrextendedparameters-for-multi-segment-qr-codes-in-images.cs
+++ b/barcode-reading-properties/identify-qr-code-structured-append-metadata-using-qrextendedparameters-for-multi-segment-qr-codes-in-images.cs
@@ -1,63 +1,89 @@
-// Title: Identify QR Code Structured-Append Metadata
-// Description: Demonstrates how to read QR code structured‑append information from an image using Aspose.BarCode.
+// Title: Identify QR Code Structured Append Metadata
+// Description: Demonstrates generating multi‑segment QR codes with structured‑append parameters and reading back the metadata using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode QR code operations collection. It shows how to use the BarcodeGenerator class to set QR structured‑append properties and the BarCodeReader class with QrExtendedParameters to retrieve segment information. Developers working with multi‑segment QR codes for data splitting, batch processing, or enhanced error correction can use these APIs to create and decode structured‑append QR symbols.
// Prompt: Identify QR Code structured‑append metadata using QrExtendedParameters for multi‑segment QR codes in images.
-// Tags: qr code, structured-append, barcode recognition, aspose.barcode, c#
+// Tags: qr code, structured-append, generation, recognition, aspose.barcode
using System;
using System.IO;
using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Sample program that reads QR codes from an image and extracts structured‑append metadata
-/// using the QrExtendedParameters provided by Aspose.BarCode.
+/// Generates QR code segments with Structured Append parameters,
+/// then reads each segment to display the associated metadata.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Creates QR segments, saves them,
+ /// and extracts Structured Append information using QrExtendedParameters.
///
static void Main()
{
- // Path to the image containing multi‑segment QR codes.
- const string imagePath = "qr_multi.png";
-
- // Verify that the file exists before attempting to read it.
- if (!File.Exists(imagePath))
+ // Define folder for generated QR code images
+ string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "QrSegments");
+ if (!Directory.Exists(outputFolder))
{
- Console.WriteLine($"File not found: {imagePath}");
- return;
+ Directory.CreateDirectory(outputFolder);
}
- // Create a BarCodeReader configured to decode QR codes only.
- using (var reader = new BarCodeReader(imagePath, DecodeType.QR))
+ // Number of QR code segments (structured append) and base text for each segment
+ int segmentCount = 2;
+ string baseText = "Hello from segment ";
+
+ // --------------------------------------------------------------------
+ // Generate each QR segment with Structured Append parameters
+ // --------------------------------------------------------------------
+ for (int i = 0; i < segmentCount; i++)
{
- // Iterate through all barcodes detected in the image.
- foreach (BarCodeResult result in reader.ReadBarCodes())
+ // Build file path for the current segment image
+ string filePath = Path.Combine(outputFolder, $"qr_segment_{i}.png");
+
+ // Create a QR code generator for the segment text
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR, baseText + (i + 1)))
{
- // Output basic barcode information.
- Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
- Console.WriteLine($"BarCode CodeText: {result.CodeText}");
+ // Configure Structured Append settings
+ generator.Parameters.Barcode.QR.StructuredAppend.TotalCount = segmentCount; // total number of segments
+ generator.Parameters.Barcode.QR.StructuredAppend.SequenceIndicator = i; // zero‑based index of this segment
+ generator.Parameters.Barcode.QR.StructuredAppend.ParityByte = 0; // optional parity byte (0 = none)
- // Access QR structured‑append metadata via the extended parameters.
- var qrExt = result.Extended?.QR;
- if (qrExt != null)
- {
- // Display the quantity of QR codes that belong to the same structured‑append group.
- Console.WriteLine($"Structured Append Quantity: {qrExt.QRStructuredAppendModeBarCodesQuantity}");
- // Display the index of the current QR code within the group (zero‑based).
- Console.WriteLine($"Structured Append Index: {qrExt.QRStructuredAppendModeBarCodeIndex}");
- // Display the parity data used for error detection across the group.
- Console.WriteLine($"Structured Append Parity Data: {qrExt.QRStructuredAppendModeParityData}");
- }
- else
+ // Save the generated QR image to disk
+ generator.Save(filePath);
+ Console.WriteLine($"Generated QR segment {i + 1} at: {filePath}");
+ }
+ }
+
+ Console.WriteLine();
+ Console.WriteLine("Reading QR segments and extracting Structured Append metadata...");
+
+ // --------------------------------------------------------------------
+ // Read each generated QR image and display Structured Append metadata
+ // --------------------------------------------------------------------
+ foreach (string file in Directory.GetFiles(outputFolder, "*.png"))
+ {
+ // Initialize a QR code reader for the current image file
+ using (var reader = new BarCodeReader(file, DecodeType.QR))
+ {
+ // Iterate through all detected barcodes (should be one per image)
+ foreach (var result in reader.ReadBarCodes())
{
- // No extended QR parameters were found for this barcode.
- Console.WriteLine("No QR extended parameters available.");
- }
+ // Access QR‑specific extended parameters
+ var qrExt = result.Extended.QR;
- Console.WriteLine(); // Separator between results.
+ Console.WriteLine($"File: {Path.GetFileName(file)}");
+ Console.WriteLine($" Code Text: {result.CodeText}");
+ Console.WriteLine($" Structured Append Quantity: {qrExt.StructuredAppendModeBarCodesQuantity}");
+ Console.WriteLine($" Structured Append Index : {qrExt.StructuredAppendModeBarCodeIndex}");
+ Console.WriteLine($" Structured Append Parity : {qrExt.StructuredAppendModeParityData}");
+ Console.WriteLine();
+ }
}
}
+
+ // Optional cleanup: remove generated files and folder
+ // foreach (var f in Directory.GetFiles(outputFolder)) File.Delete(f);
+ // Directory.Delete(outputFolder);
}
}
\ No newline at end of file
diff --git a/barcode-reading-properties/implement-async-barcode-reading-using-barcodereaderreadbarcodesasync-for-responsive-ui-in-desktop-applications.cs b/barcode-reading-properties/implement-async-barcode-reading-using-barcodereaderreadbarcodesasync-for-responsive-ui-in-desktop-applications.cs
index 70fb8e6..d39729e 100644
--- a/barcode-reading-properties/implement-async-barcode-reading-using-barcodereaderreadbarcodesasync-for-responsive-ui-in-desktop-applications.cs
+++ b/barcode-reading-properties/implement-async-barcode-reading-using-barcodereaderreadbarcodesasync-for-responsive-ui-in-desktop-applications.cs
@@ -1,59 +1,72 @@
-// Title: Async barcode reading demo using Aspose.BarCode
-// Description: Demonstrates generating a barcode image in memory and reading it asynchronously to keep UI responsive.
+// Title: Asynchronous barcode reading example
+// Description: Demonstrates how to read barcodes asynchronously using BarCodeReader.ReadBarCodesAsync to keep UI responsive.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing asynchronous operations with BarCodeReader and BarcodeGenerator. Developers often need to process images without blocking the UI thread, especially in desktop applications, and this pattern illustrates using Task.Run to off‑load the synchronous ReadBarCodes call while preserving async flow.
// Prompt: Implement async barcode reading using BarCodeReader.ReadBarCodesAsync for responsive UI in desktop applications.
-// Tags: barcode symbology, async operation, console output, aspose.barcode, barcodereader
+// Tags: barcode symbology, async, read, code128, aspose.barcode, desktop ui
using System;
+using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing; // Required for ImageFormat enum
///
-/// Sample console application that shows how to generate a barcode,
-/// then read it asynchronously to avoid blocking the UI thread in a desktop scenario.
+/// Demonstrates asynchronous barcode reading using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a barcode image in memory, then reads it asynchronously.
+ /// Entry point. Generates a sample barcode if missing and reads it asynchronously.
///
/// Command‑line arguments (not used).
static async Task Main(string[] args)
{
- // Create a barcode generator for Code128 with sample text.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ const string imagePath = "barcode.png";
+
+ // Generate a sample barcode image if it does not exist.
+ if (!File.Exists(imagePath))
{
- // Store the generated barcode image in a memory stream.
- using (var ms = new MemoryStream())
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Save the barcode as PNG to the memory stream.
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for reading.
-
- // Initialize the barcode reader with the image stream,
- // requesting detection of all supported barcode types.
- using (var reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes))
- {
- // Perform the synchronous read on a background thread to keep UI responsive.
- BarCodeResult[] results = await Task.Run(() => reader.ReadBarCodes());
+ generator.Save(imagePath, BarCodeImageFormat.Png);
+ }
+ }
- // Output each detected barcode's type and text.
- foreach (var result in results)
- {
- Console.WriteLine($"Type: {result.CodeTypeName}, Text: {result.CodeText}");
- }
+ // Asynchronously read barcodes from the image.
+ await ReadBarcodesAsync(imagePath);
+ }
- // Inform the user if no barcodes were found.
- if (results.Length == 0)
+ ///
+ /// Reads barcodes from the specified image file on a background thread and returns the detected texts.
+ ///
+ /// Path to the image containing barcodes.
+ private static async Task ReadBarcodesAsync(string imagePath)
+ {
+ // Run the blocking read operation on a background thread.
+ List detectedTexts = await Task.Run(() =>
+ {
+ var texts = new List();
+ using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
+ {
+ // Iterate through all detected barcodes.
+ foreach (var result in reader.ReadBarCodes())
+ {
+ // Collect non‑empty barcode texts.
+ if (!string.IsNullOrEmpty(result.CodeText))
{
- Console.WriteLine("No barcodes detected.");
+ texts.Add(result.CodeText);
}
}
}
+ return texts;
+ });
+
+ // Output the results to the console.
+ foreach (var text in detectedTexts)
+ {
+ Console.WriteLine($"Detected barcode text: {text}");
}
}
}
\ No newline at end of file
diff --git a/barcode-reading-properties/instantiate-barcodereader-with-image-file-path-and-read-all-detected-barcode-types.cs b/barcode-reading-properties/instantiate-barcodereader-with-image-file-path-and-read-all-detected-barcode-types.cs
index 4bd3eb0..3a9f9a9 100644
--- a/barcode-reading-properties/instantiate-barcodereader-with-image-file-path-and-read-all-detected-barcode-types.cs
+++ b/barcode-reading-properties/instantiate-barcodereader-with-image-file-path-and-read-all-detected-barcode-types.cs
@@ -1,46 +1,43 @@
-// Title: Read All Barcode Types from an Image
-// Description: Demonstrates how to instantiate BarCodeReader with an image file path and read every supported barcode type present in the image.
+// Title: Read All Barcode Types from an Image using Aspose.BarCode
+// Description: Demonstrates how to instantiate BarCodeReader with an image file path and retrieve every detected barcode type.
+// Category-Description: This example belongs to the Aspose.BarCode recognition category, illustrating the use of BarCodeReader and DecodeType to scan images for all supported barcode symbologies. Typical scenarios include batch processing of scanned documents, inventory verification, and automated data capture where multiple barcode formats may appear. Developers often need quick, code‑first solutions to enumerate and decode any barcode present in an image.
// Prompt: Instantiate BarCodeReader with an image file path and read all detected barcode types.
-// Tags: barcode, symbology, read, alltypes, console, aspose.barcode
+// Tags: barcode symbology, read, all types, aspose.barcode, c#
using System;
using System.IO;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that reads all supported barcode types from a given image file.
+/// Example program that reads all supported barcode types from an image file using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application. Instantiates a and outputs detected barcodes.
+ /// Entry point. Accepts an optional image path argument, validates the file, and prints detected barcodes.
///
- static void Main()
+ /// Command‑line arguments; first argument may be the image file path.
+ static void Main(string[] args)
{
- // Path to the image containing barcodes
- string imagePath = "sample.png";
+ // Determine image path: use first argument or fallback to a default file name.
+ string imagePath = args.Length > 0 ? args[0] : "sample.png";
- // Verify that the image file exists before attempting to read
+ // Verify that the file exists before attempting to read.
if (!File.Exists(imagePath))
{
Console.WriteLine($"File not found: {imagePath}");
return;
}
- // Create the reader for the image file inside a using block to ensure proper disposal
- using (BarCodeReader reader = new BarCodeReader(imagePath))
+ // Create a BarCodeReader that scans the image for all supported barcode types.
+ using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
- // Configure the reader to detect all supported barcode types
- reader.BarCodeReadType = DecodeType.AllSupportedTypes;
-
- // Perform the recognition and retrieve all results
- BarCodeResult[] results = reader.ReadBarCodes();
-
- // Iterate through each detected barcode and display its type and decoded text
- foreach (BarCodeResult result in results)
+ // Iterate through all detected barcodes and output their type and decoded text.
+ foreach (var result in reader.ReadBarCodes())
{
Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
Console.WriteLine($"BarCode CodeText: {result.CodeText}");
+ Console.WriteLine(); // Blank line for readability.
}
}
}
diff --git a/barcode-reading-properties/iterate-over-barcoderesult-collection-to-log-each-barcode-s-type-text-and-region.cs b/barcode-reading-properties/iterate-over-barcoderesult-collection-to-log-each-barcode-s-type-text-and-region.cs
index 1b74014..702cc14 100644
--- a/barcode-reading-properties/iterate-over-barcoderesult-collection-to-log-each-barcode-s-type-text-and-region.cs
+++ b/barcode-reading-properties/iterate-over-barcoderesult-collection-to-log-each-barcode-s-type-text-and-region.cs
@@ -1,59 +1,97 @@
-// Title: Iterate over BarCodeResult collection and log details
-// Description: Demonstrates reading a barcode image (generating one if missing) and logging each detected barcode's type, text, and region.
+// Title: Barcode generation, recognition, and logging example
+// Description: Demonstrates creating barcodes, reading them back, and logging each barcode's type, text, and region.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showcasing how to use BarcodeGenerator for creating various symbologies and BarCodeReader for decoding them. Typical use cases include batch processing of barcode images, extracting metadata, and integrating barcode data into workflows. Developers often need to iterate over BarCodeResult collections to retrieve code type, decoded text, and positional information.
// Prompt: Iterate over BarCodeResult collection to log each barcode's type, text, and region.
-// Tags: barcode symbology, read, console output, aspose.barcode, c#
+// Tags: barcode symbology, generation, recognition, logging, aspose.barcode, barcoderesult, region
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Example program that generates a barcode image if needed,
-/// reads all barcodes from the image, and logs their details to the console.
+/// Demonstrates how to generate multiple barcode images, read them back,
+/// and log each barcode's type, decoded text, and region information.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Generates sample barcodes, reads them,
+ /// and writes details to the console.
///
static void Main()
{
- // Path to the temporary barcode image file.
- string imagePath = "sample_barcode.png";
+ // --------------------------------------------------------------------
+ // Prepare a temporary folder for barcode images
+ // --------------------------------------------------------------------
+ string tempFolder = Path.Combine(Path.GetTempPath(), "AsposeBarcodesDemo");
+ if (!Directory.Exists(tempFolder))
+ {
+ Directory.CreateDirectory(tempFolder);
+ }
+
+ // --------------------------------------------------------------------
+ // Define sample barcodes (symbology and associated text)
+ // --------------------------------------------------------------------
+ var samples = new (BaseEncodeType Encode, string Text)[]
+ {
+ (EncodeTypes.Code128, "ABC123"),
+ (EncodeTypes.QR, "https://example.com"),
+ (EncodeTypes.DataMatrix, "DM12345")
+ };
- // If the image does not exist, generate a simple Code128 barcode for demonstration.
- if (!File.Exists(imagePath))
+ // --------------------------------------------------------------------
+ // Generate barcode images and save them as PNG files
+ // --------------------------------------------------------------------
+ foreach (var (encode, text) in samples)
{
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "12345"))
+ string filePath = Path.Combine(tempFolder, $"{encode.TypeName}_{Guid.NewGuid()}.png");
+ using (var generator = new BarcodeGenerator(encode, text))
{
- // Save the generated barcode image to the specified path.
- generator.Save(imagePath);
+ // Optional: set simple visual parameters
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+ generator.Save(filePath, BarCodeImageFormat.Png);
}
}
- // Verify that the image file exists before attempting to read it.
- if (!File.Exists(imagePath))
+ // --------------------------------------------------------------------
+ // Read all generated images and log barcode details
+ // --------------------------------------------------------------------
+ string[] imageFiles = Directory.GetFiles(tempFolder, "*.png");
+ foreach (string imageFile in imageFiles)
{
- Console.WriteLine($"Error: File '{imagePath}' not found.");
- return;
- }
+ if (!File.Exists(imageFile))
+ {
+ Console.WriteLine($"File not found: {imageFile}");
+ continue;
+ }
- // Create a BarCodeReader that attempts to decode all supported barcode types in the image.
- using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
- {
- // Iterate over all detected barcodes.
- foreach (BarCodeResult result in reader.ReadBarCodes())
+ using (var reader = new BarCodeReader(imageFile, DecodeType.AllSupportedTypes))
{
- // Log the barcode type (symbology name).
- Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
- // Log the decoded text/value of the barcode.
- Console.WriteLine($"BarCode Text: {result.CodeText}");
- // Log the region (bounding rectangle) where the barcode was found.
- Console.WriteLine($"BarCode Region: {result.Region}");
- Console.WriteLine(); // Blank line for readability between entries.
+ BarCodeResult[] results = reader.ReadBarCodes();
+
+ // Iterate over each detected barcode result
+ foreach (BarCodeResult result in results)
+ {
+ // Extract region rectangle for positional information
+ var rect = result.Region.Rectangle;
+
+ // Log file name, barcode type, decoded text, and region coordinates
+ Console.WriteLine($"File: {Path.GetFileName(imageFile)}");
+ Console.WriteLine($" Type: {result.CodeType}");
+ Console.WriteLine($" Text: {result.CodeText}");
+ Console.WriteLine($" Region: X={rect.X}, Y={rect.Y}, Width={rect.Width}, Height={rect.Height}");
+ }
}
}
+
+ // --------------------------------------------------------------------
+ // Cleanup (optional): delete temporary files and folder
+ // --------------------------------------------------------------------
+ // foreach (string file in imageFiles) File.Delete(file);
+ // Directory.Delete(tempFolder);
}
}
\ No newline at end of file
diff --git a/barcode-reading-properties/limit-barcodereader-to-specific-symbologies-such-as-qr-code-and-pdf417-for-performance.cs b/barcode-reading-properties/limit-barcodereader-to-specific-symbologies-such-as-qr-code-and-pdf417-for-performance.cs
index f812496..b3336e5 100644
--- a/barcode-reading-properties/limit-barcodereader-to-specific-symbologies-such-as-qr-code-and-pdf417-for-performance.cs
+++ b/barcode-reading-properties/limit-barcodereader-to-specific-symbologies-such-as-qr-code-and-pdf417-for-performance.cs
@@ -1,76 +1,80 @@
-// Title: Limit BarCodeReader to Specific Symbologies (QR and PDF417)
-// Description: Demonstrates generating QR and PDF417 barcodes, then reading them while restricting the BarCodeReader to those symbologies for better performance.
+// Title: Limit BarCodeReader to specific symbologies for faster decoding
+// Description: Demonstrates generating QR, PDF417, and Code128 barcodes, then reading only QR and PDF417 types to improve performance.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing how to use BarcodeGenerator to create images and BarCodeReader with selective DecodeType parameters. Developers often need to limit symbology detection to reduce processing time when only certain barcode types are expected, such as QR Code and PDF417 in mobile scanning or document processing scenarios.
// Prompt: Limit BarCodeReader to specific symbologies such as QR Code and PDF417 for performance.
-// Tags: barcode symbology, read, qr, pdf417, performance, aspnet
+// Tags: barcode symbology, read, png, barcodegenerator, barcodereader, qr, pdf417
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
+using Aspose.BarCode;
///
-/// Example program that creates QR Code and PDF417 barcode images,
-/// then reads them back while limiting the reader to those two symbologies
-/// to improve decoding performance.
+/// Demonstrates generating sample barcodes and reading only selected symbologies (QR and PDF417) to improve performance.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates sample barcode images and decodes them using a restricted BarCodeReader.
+ /// Entry point of the example. Generates barcode images, then reads them while limiting detection to QR and PDF417.
///
static void Main()
{
- // ---------- Generate sample QR Code image ----------
- string qrPath = "qr.png";
- using (var qrGenerator = new BarcodeGenerator(EncodeTypes.QR, "Sample QR Text"))
+ // Define file paths for the generated barcode images
+ string qrPath = Path.Combine(Directory.GetCurrentDirectory(), "qr.png");
+ string pdf417Path = Path.Combine(Directory.GetCurrentDirectory(), "pdf417.png");
+ string code128Path = Path.Combine(Directory.GetCurrentDirectory(), "code128.png");
+
+ // -------------------------------------------------
+ // Generate a QR Code image
+ // -------------------------------------------------
+ using (var qrGenerator = new BarcodeGenerator(EncodeTypes.QR, "Sample QR Code"))
{
- // Save the QR Code image to disk
- qrGenerator.Save(qrPath);
+ qrGenerator.Save(qrPath, BarCodeImageFormat.Png);
}
- // ---------- Generate sample PDF417 image ----------
- string pdf417Path = "pdf417.png";
+ // -------------------------------------------------
+ // Generate a PDF417 image
+ // -------------------------------------------------
using (var pdf417Generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Sample PDF417 Text"))
{
- // Save the PDF417 image to disk
- pdf417Generator.Save(pdf417Path);
+ pdf417Generator.Save(pdf417Path, BarCodeImageFormat.Png);
}
- // ---------- Prepare list of images to process ----------
- string[] imageFiles = { qrPath, pdf417Path };
+ // -------------------------------------------------
+ // Generate a Code128 image (will be ignored during reading)
+ // -------------------------------------------------
+ using (var code128Generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
+ {
+ code128Generator.Save(code128Path, BarCodeImageFormat.Png);
+ }
- // ---------- Iterate over each image and decode ----------
- foreach (var imageFile in imageFiles)
+ // -------------------------------------------------
+ // Read barcodes, limiting detection to QR and PDF417 only
+ // -------------------------------------------------
+ string[] filesToRead = { qrPath, pdf417Path, code128Path };
+ foreach (string file in filesToRead)
{
- // Verify that the image file exists before attempting to read it
- if (!File.Exists(imageFile))
+ // Verify that the file exists before attempting to read it
+ if (!File.Exists(file))
{
- Console.WriteLine($"File not found: {imageFile}");
+ Console.WriteLine($"File not found: {file}");
continue;
}
- // Load the image into a Bitmap object
- using (var bitmap = new Bitmap(imageFile))
+ // Construct BarCodeReader with the desired decode types.
+ // Only QR and PDF417 symbologies will be processed, improving performance.
+ using (var reader = new BarCodeReader(file, DecodeType.QR, DecodeType.Pdf417))
{
- // Initialize BarCodeReader limited to QR and PDF417 symbologies
- using (var reader = new BarCodeReader(bitmap, DecodeType.QR, DecodeType.Pdf417))
+ foreach (var result in reader.ReadBarCodes())
{
- // Read all barcodes detected in the image
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"Image: {imageFile}");
- Console.WriteLine($"Detected Type: {result.CodeTypeName}");
- Console.WriteLine($"Code Text: {result.CodeText}");
- Console.WriteLine();
- }
+ Console.WriteLine($"File: {Path.GetFileName(file)}");
+ Console.WriteLine($" Detected Type : {result.CodeTypeName}");
+ Console.WriteLine($" Code Text : {result.CodeText}");
}
}
}
- // Indicate that the program has completed successfully
- Console.WriteLine("Processing completed.");
+ // End of program
}
}
\ No newline at end of file
diff --git a/barcode-reading-properties/load-image-data-from-memory-stream-and-extract-barcode-placement-region-without-saving-to-disk.cs b/barcode-reading-properties/load-image-data-from-memory-stream-and-extract-barcode-placement-region-without-saving-to-disk.cs
index 27d6bbd..9ed0e42 100644
--- a/barcode-reading-properties/load-image-data-from-memory-stream-and-extract-barcode-placement-region-without-saving-to-disk.cs
+++ b/barcode-reading-properties/load-image-data-from-memory-stream-and-extract-barcode-placement-region-without-saving-to-disk.cs
@@ -1,7 +1,8 @@
-// Title: In-Memory Barcode Generation and Region Extraction
-// Description: Demonstrates generating a Code128 barcode, loading it from a memory stream, and retrieving the barcode's placement region without writing to disk.
+// Title: Load barcode from memory stream and retrieve placement region
+// Description: Demonstrates generating a barcode in memory, reading it directly from a stream, and extracting the barcode's location without writing to disk.
+// Category-Description: This example belongs to the Aspose.BarCode image processing and recognition category. It showcases the use of BarcodeGenerator for creating barcodes, BarCodeReader for decoding, and the Region property to obtain placement coordinates. Typical scenarios include on‑the‑fly barcode generation and detection in web services or automated workflows where file I/O is avoided. Developers often need to generate, stream, and analyze barcodes without persisting intermediate images.
// Prompt: Load image data from a memory stream and extract barcode placement region without saving to disk.
-// Tags: barcode, code128, in-memory, region extraction, aspose.barcode, generation, recognition
+// Tags: barcode, code128, memory stream, region, generation, recognition, aspnet, csharp
using System;
using System.IO;
@@ -10,47 +11,40 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that generates a barcode in memory, reads it, and outputs its location.
+/// Demonstrates loading barcode image data from a memory stream and extracting its placement region.
///
class Program
{
///
- /// Entry point. Generates a barcode, reads it from a memory stream, and prints barcode details and region.
+ /// Entry point. Generates a Code128 barcode, reads it from memory, and prints detection details.
///
static void Main()
{
- // Generate a sample Code128 barcode and write it to a memory stream.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
+ // Create a memory stream to hold the generated barcode image.
+ using (var memoryStream = new MemoryStream())
{
- using (var memoryStream = new MemoryStream())
+ // Generate a Code128 barcode with the text "Sample123" and save it as PNG into the memory stream.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- // Save the barcode image into the stream in PNG format.
generator.Save(memoryStream, BarCodeImageFormat.Png);
+ }
- // Reset the stream position before reading.
- memoryStream.Position = 0;
+ // Reset the stream position to the beginning before reading.
+ memoryStream.Position = 0;
- // Create a barcode reader and load the image from the memory stream.
- using (var reader = new BarCodeReader())
+ // Initialize a barcode reader that works directly on the memory stream and supports all barcode types.
+ using (var reader = new BarCodeReader(memoryStream, DecodeType.AllSupportedTypes))
+ {
+ // Iterate through all detected barcodes in the image.
+ foreach (var result in reader.ReadBarCodes())
{
- // Assign the image stream to the reader.
- reader.SetBarCodeImage(memoryStream);
-
- // Detect all supported barcode types.
- reader.BarCodeReadType = DecodeType.AllSupportedTypes;
-
- // Iterate through detected barcodes.
- foreach (var result in reader.ReadBarCodes())
- {
- // Extract the bounding rectangle of the barcode.
- var rect = result.Region.Rectangle;
+ // Retrieve the rectangle that defines the barcode's placement region.
+ var rect = result.Region.Rectangle;
- // Output barcode type, text, and region coordinates.
- Console.WriteLine($"Barcode Type: {result.CodeTypeName}");
- Console.WriteLine($"Barcode Text: {result.CodeText}");
- Console.WriteLine($"Region - X: {rect.X}, Y: {rect.Y}, Width: {rect.Width}, Height: {rect.Height}");
- Console.WriteLine();
- }
+ // Output detection details to the console.
+ Console.WriteLine($"Detected barcode type: {result.CodeType}");
+ Console.WriteLine($"Code text: {result.CodeText}");
+ Console.WriteLine($"Region - X:{rect.X}, Y:{rect.Y}, Width:{rect.Width}, Height:{rect.Height}");
}
}
}
diff --git a/barcode-reading-properties/obtain-dotcode-version-information-and-error-correction-level-from-scanned-dotcode-barcode.cs b/barcode-reading-properties/obtain-dotcode-version-information-and-error-correction-level-from-scanned-dotcode-barcode.cs
index 9199d84..6a60282 100644
--- a/barcode-reading-properties/obtain-dotcode-version-information-and-error-correction-level-from-scanned-dotcode-barcode.cs
+++ b/barcode-reading-properties/obtain-dotcode-version-information-and-error-correction-level-from-scanned-dotcode-barcode.cs
@@ -1,58 +1,99 @@
-// Title: Retrieve DotCode version and error correction level
-// Description: Demonstrates how to scan a DotCode barcode and attempt to obtain its version and error correction level, handling cases where the API does not expose these details.
+// Title: Obtain DotCode version and error correction level from scanned barcode
+// Description: Demonstrates how to read a DotCode barcode, generate it if missing, and retrieve extended version and error‑correction information via the Aspose.BarCode API.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on extracting extended metadata from DotCode symbols. It uses BarcodeGenerator for creation, BarCodeReader for decoding, and the Extended.DotCode property to access version, error correction level and other parameters. Developers working with high‑density 2‑D barcodes often need to verify symbol version and ECC settings for quality control or compliance.
// Prompt: Obtain DotCode version information and error correction level from a scanned DotCode barcode.
-// Tags: dotcode, barcode, version, error correction, aspose.barcode, barcoderecognition
+// Tags: dotcode, barcode, recognition, version, error correction, aspnet, aspnetcore, aspose.barcode, c#
using System;
using System.IO;
+using System.Reflection;
+using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that reads a DotCode barcode from an image and tries to
-/// extract version information and error correction level using Aspose.BarCode.
+/// Example program that generates (if needed) and reads a DotCode barcode,
+/// then extracts version and error‑correction information using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application.
- /// Scans the specified image for DotCode barcodes and reports available details.
+ /// Entry point of the example. Generates a sample DotCode image if it does not exist,
+ /// reads the barcode, and prints extended DotCode metadata.
///
static void Main()
{
- // Path to the image containing a DotCode barcode.
- const string imagePath = "dotcode_sample.png";
+ // --------------------------------------------------------------------
+ // Prepare a sample DotCode image (self‑contained example)
+ // --------------------------------------------------------------------
+ const string imagePath = "dotcode.png";
+ const string codeText = "SampleDotCode";
- // Verify that the image file exists before attempting to read it.
+ // --------------------------------------------------------------------
+ // Generate DotCode barcode if it does not already exist on disk
+ // --------------------------------------------------------------------
if (!File.Exists(imagePath))
{
- Console.WriteLine($"File not found: {imagePath}");
+ using (var generator = new BarcodeGenerator(EncodeTypes.DotCode, codeText))
+ {
+ // Optional: set generation parameters (e.g., number of columns)
+ generator.Parameters.Barcode.DotCode.Columns = 20; // rows are auto‑determined
+ generator.Save(imagePath);
+ Console.WriteLine($"Generated sample barcode: {imagePath}");
+ }
+ }
+
+ // --------------------------------------------------------------------
+ // Verify the image file exists before attempting recognition
+ // --------------------------------------------------------------------
+ if (!File.Exists(imagePath))
+ {
+ Console.WriteLine($"Error: Barcode image '{imagePath}' not found.");
return;
}
- // Initialize a BarCodeReader configured for DotCode symbology.
+ // --------------------------------------------------------------------
+ // Recognize the DotCode barcode and output extended information
+ // --------------------------------------------------------------------
using (var reader = new BarCodeReader(imagePath, DecodeType.DotCode))
{
- // Iterate through all detected barcodes in the image.
- foreach (var result in reader.ReadBarCodes())
+ bool found = false;
+
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
- // Output basic barcode information.
- Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
- Console.WriteLine($"BarCode CodeText: {result.CodeText}");
-
- // Attempt to retrieve extended DotCode parameters (version, error correction level).
- // The current Aspose.BarCode API does not expose these fields.
- var dotExt = result.Extended?.DotCode;
- if (dotExt != null)
+ found = true;
+ Console.WriteLine($"CodeText: {result.CodeText}");
+
+ // Access extended DotCode information via reflection (properties may vary by version)
+ var dotCodeInfo = result.Extended?.DotCode;
+ if (dotCodeInfo != null)
{
- Console.WriteLine("DotCode version information: not available via Aspose.BarCode API.");
- Console.WriteLine("DotCode error correction level: not available via Aspose.BarCode API.");
+ Type infoType = dotCodeInfo.GetType();
+ PropertyInfo[] properties = infoType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
+ Console.WriteLine("DotCode extended information:");
+ foreach (PropertyInfo prop in properties)
+ {
+ try
+ {
+ object value = prop.GetValue(dotCodeInfo);
+ Console.WriteLine($" {prop.Name}: {value}");
+ }
+ catch
+ {
+ // Ignore any property that throws during get
+ }
+ }
}
else
{
- // No extended parameters were provided for this barcode.
- Console.WriteLine("No DotCode extended parameters were found.");
+ Console.WriteLine("No extended DotCode information available.");
}
}
+
+ if (!found)
+ {
+ Console.WriteLine("No DotCode barcode detected in the image.");
+ }
}
}
}
\ No newline at end of file
diff --git a/barcode-reading-properties/process-encrypted-pdf-files-by-providing-password-to-barcodereader-and-extracting-barcode-data.cs b/barcode-reading-properties/process-encrypted-pdf-files-by-providing-password-to-barcodereader-and-extracting-barcode-data.cs
index 8615798..84dd1ee 100644
--- a/barcode-reading-properties/process-encrypted-pdf-files-by-providing-password-to-barcodereader-and-extracting-barcode-data.cs
+++ b/barcode-reading-properties/process-encrypted-pdf-files-by-providing-password-to-barcodereader-and-extracting-barcode-data.cs
@@ -1,82 +1,75 @@
-// Title: Read Barcodes from Encrypted PDF using Aspose.BarCode
-// Description: Demonstrates how to supply a password for an encrypted PDF and extract barcode data using BarCodeReader.
+// Title: Extract barcodes from password-protected PDF using Aspose.BarCode
+// Description: Demonstrates how to open an encrypted PDF with a password, render each page to an image, and read any barcodes present.
+// Category-Description: This example belongs to the Aspose.BarCode PDF processing category, illustrating the use of Aspose.Pdf.Document, PdfConverter, and Aspose.BarCode.BarCodeRecognition.BarCodeReader to decode barcodes from secured PDF files. Typical scenarios include scanning invoices, tickets, or forms that are password-protected, where developers need to extract barcode data without manual decryption.
// Prompt: Process encrypted PDF files by providing password to BarCodeReader and extracting barcode data.
-// Tags: pdf, encryption, barcode, reading, aspose.barcode, aspose.pdf, decode
+// Tags: pdf, encryption, barcode, decoding, aspnet, aspose.barcode, aspose.pdf
using System;
using System.IO;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Pdf;
+using Aspose.Pdf.Facades;
///
-/// Example program that reads barcodes from a PDF file.
-/// It shows how to handle encrypted PDFs by providing a password (commented out)
-/// and how to extract barcode information using Aspose.BarCode.
+/// Example program that opens an encrypted PDF, renders each page to an image,
+/// and extracts any barcodes using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application. Performs file validation, demonstrates
- /// both the password‑protected PDF workflow (commented) and the simple direct
- /// reading approach, then processes any detected barcodes.
+ /// Entry point of the application.
///
- static void Main()
+ /// Command‑line arguments (not used).
+ static void Main(string[] args)
{
- // Path to the encrypted PDF file.
+ // Path to the encrypted PDF file (adjust as needed)
string pdfPath = "encrypted.pdf";
- // Verify that the file exists before attempting to read it.
+ // Password for the encrypted PDF (adjust as needed)
+ string password = "myPassword";
+
+ // Verify that the PDF file exists before attempting to open it
if (!File.Exists(pdfPath))
{
Console.WriteLine($"File not found: {pdfPath}");
return;
}
- // --------------------------------------------------------------------
- // Encrypted PDF handling (requires Aspose.Pdf). The code is provided as
- // a reference and is commented out because the Aspose.Pdf assembly may
- // not be available in the execution environment.
- // --------------------------------------------------------------------
- // string pdfPassword = "yourPassword";
- // using (var pdfDocument = new Aspose.Pdf.Document(pdfPath, new Aspose.Pdf.LoadOptions { Password = pdfPassword }))
- // {
- // // Iterate through each page, render it to an image stream, and feed it to BarCodeReader.
- // for (int pageIndex = 1; pageIndex <= pdfDocument.Pages.Count; pageIndex++)
- // {
- // using (var imageStream = new MemoryStream())
- // {
- // pdfDocument.Pages[pageIndex].ConvertToImage(imageStream, Aspose.Pdf.Devices.Resolution.Default);
- // imageStream.Position = 0;
- // using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes))
- // {
- // ProcessBarcodes(reader);
- // }
- // }
- // }
- // }
-
- // --------------------------------------------------------------------
- // Simple direct reading (suitable for unencrypted PDFs or when the
- // library can handle the password internally). This demonstrates the
- // core barcode extraction logic.
- // --------------------------------------------------------------------
- using (var reader = new BarCodeReader(pdfPath, DecodeType.AllSupportedTypes))
+ // Open the encrypted PDF document using the provided password
+ using (var pdfDocument = new Document(pdfPath, password))
{
- ProcessBarcodes(reader);
- }
- }
+ // Initialize the PDF converter which will render pages to images
+ using (var pdfConverter = new PdfConverter(pdfDocument))
+ {
+ // Enable barcode optimization to improve rendering speed for barcode detection
+ pdfConverter.RenderingOptions.BarcodeOptimization = true;
- ///
- /// Reads all barcodes from the provided instance
- /// and writes their type and decoded text to the console.
- ///
- /// Initialized BarCodeReader configured with the source document.
- private static void ProcessBarcodes(BarCodeReader reader)
- {
- // Iterate through detected barcodes and output their type and decoded text.
- foreach (var result in reader.ReadBarCodes())
- {
- Console.WriteLine($"BarCode Type: {result.CodeTypeName}");
- Console.WriteLine($"BarCode CodeText: {result.CodeText}");
+ // Process each page in the PDF sequentially
+ for (int pageNumber = 1; pageNumber <= pdfDocument.Pages.Count; pageNumber++)
+ {
+ // Configure the converter to render only the current page
+ pdfConverter.StartPage = pageNumber;
+ pdfConverter.EndPage = pageNumber;
+ pdfConverter.DoConvert();
+
+ // Capture the rendered page image into a memory stream
+ using (var imageStream = new MemoryStream())
+ {
+ pdfConverter.GetNextImage(imageStream);
+ imageStream.Position = 0; // Reset stream position for reading
+
+ // Create a barcode reader for the image stream, detecting all supported types
+ using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes))
+ {
+ // Iterate through all detected barcodes on the current page
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Page {pageNumber}: Type = {result.CodeTypeName}, Text = {result.CodeText}");
+ }
+ }
+ }
+ }
+ }
}
}
}
\ No newline at end of file
diff --git a/barcode-reading-properties/read-barcode-code-text-and-symbology-type-from-jpeg-image-using-barcodereader.cs b/barcode-reading-properties/read-barcode-code-text-and-symbology-type-from-jpeg-image-using-barcodereader.cs
index c501429..0b73e53 100644
--- a/barcode-reading-properties/read-barcode-code-text-and-symbology-type-from-jpeg-image-using-barcodereader.cs
+++ b/barcode-reading-properties/read-barcode-code-text-and-symbology-type-from-jpeg-image-using-barcodereader.cs
@@ -1,43 +1,41 @@
-// Title: Read barcode text and symbology from JPEG using BarCodeReader
-// Description: Demonstrates how to load a JPEG image, detect all supported barcodes, and output their symbology type and decoded text.
+// Title: Read barcode text and symbology from a JPEG image using BarCodeReader
+// Description: Demonstrates how to load a JPEG file, detect barcodes, and output their symbology type and decoded text.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing the BarCodeReader class for scanning images. It covers typical use cases such as extracting information from product labels, documents, or inventory images. Developers often need to read multiple symbologies from various image formats, and this snippet illustrates the straightforward approach using Aspose.BarCode APIs.
// Prompt: Read barcode code text and symbology type from a JPEG image using BarCodeReader.
-// Tags: barcode, symbology, read, jpeg, aspose, barcodereader
+// Tags: barcode, symbology, read, jpeg, aspose.barcode, barcodereader
using System;
using System.IO;
using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that reads barcode information from a JPEG image using Aspose.BarCode.
+/// Demonstrates reading barcode text and symbology type from a JPEG image using Aspose.BarCode's BarCodeReader.
///
class Program
{
///
- /// Entry point of the application. Scans the specified image (or a default one) for barcodes
- /// and prints each barcode's symbology type and decoded text to the console.
+ /// Entry point of the example. Scans the specified JPEG image for all supported barcode types and prints each result.
///
- /// Optional command‑line arguments; the first argument can specify the image path.
- static void Main(string[] args)
+ static void Main()
{
- // Determine the image file to process; allow override via first command‑line argument.
- string imagePath = args.Length > 0 ? args[0] : "barcode.jpg";
+ // Path to the JPEG image containing the barcode.
+ string imagePath = "barcode.jpg";
- // Verify that the image file exists before attempting to read it.
+ // Verify that the image file exists before attempting to read.
if (!File.Exists(imagePath))
{
- Console.WriteLine($"Image file not found: {imagePath}");
+ Console.WriteLine($"File not found: {imagePath}");
return;
}
- // Initialize a BarCodeReader that will attempt to decode all supported barcode types.
- using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
+ // Initialize BarCodeReader to scan the image for every supported symbology.
+ using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
- // Loop through each detected barcode and output its details.
+ // Iterate through all detected barcodes in the image.
foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"Symbology: {result.CodeTypeName}");
- Console.WriteLine($"Code Text : {result.CodeText}");
- Console.WriteLine();
+ // Output the detected symbology name and its decoded text.
+ Console.WriteLine($"Symbology: {result.CodeTypeName}, CodeText: {result.CodeText}");
}
}
}
diff --git a/barcode-reading-properties/read-barcode-data-from-base64-encoded-image-string-and-decode-embedded-information.cs b/barcode-reading-properties/read-barcode-data-from-base64-encoded-image-string-and-decode-embedded-information.cs
index 270d376..09a1177 100644
--- a/barcode-reading-properties/read-barcode-data-from-base64-encoded-image-string-and-decode-embedded-information.cs
+++ b/barcode-reading-properties/read-barcode-data-from-base64-encoded-image-string-and-decode-embedded-information.cs
@@ -1,7 +1,8 @@
-// Title: Base64 Barcode Generation and Decoding
-// Description: Generates a Code128 barcode, encodes it as a Base64 string, then decodes the string back to an image and reads the barcode data.
+// Title: Decode Barcode from Base64 Image
+// Description: Demonstrates generating a Code128 barcode, converting it to a Base64 string, and decoding the embedded information from the image.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator for creating barcodes, converting images to Base64, and BarCodeReader for extracting data from any supported symbology. Developers often need to exchange barcode images as text (e.g., JSON payloads) and later decode them without persisting files.
// Prompt: Read barcode data from a base64‑encoded image string and decode the embedded information.
-// Tags: code128, barcode generation, barcode decoding, base64, aspose.barcode, png
+// Tags: code128, decode, png, aspose.barcode, generation, recognition, base64, image
using System;
using System.IO;
@@ -10,47 +11,39 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates how to generate a barcode, convert it to a Base64 string,
-/// decode the string back to an image, and read the barcode information using Aspose.BarCode.
+/// Example program that generates a barcode, encodes it as Base64, and then decodes the barcode data from the image.
///
class Program
{
///
- /// Entry point of the example. Performs barcode generation, Base64 conversion, and decoding.
+ /// Entry point. Generates a Code128 barcode, converts it to a Base64 string, and reads the barcode back from the image data.
///
static void Main()
{
- // Sample barcode text to encode
- string sampleText = "1234567890";
-
- // Generate a barcode image and obtain its Base64 representation
+ // Generate a sample barcode image and obtain its Base64 representation
string base64Image;
- using (MemoryStream generationStream = new MemoryStream())
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "HelloWorld"))
{
- // Create a barcode generator for Code128 with the sample text
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, sampleText))
+ // Save the barcode to a memory stream in PNG format
+ using (var ms = new MemoryStream())
{
- // Save the barcode as PNG into the memory stream
- generator.Save(generationStream, BarCodeImageFormat.Png);
+ generator.Save(ms, BarCodeImageFormat.Png);
+ // Convert the image bytes to a Base64 string
+ base64Image = Convert.ToBase64String(ms.ToArray());
}
-
- // Convert the generated image bytes to a Base64 string
- base64Image = Convert.ToBase64String(generationStream.ToArray());
}
// Decode the Base64 string back to image bytes
byte[] imageBytes = Convert.FromBase64String(base64Image);
-
- // Read the barcode from the image bytes
- using (MemoryStream imageStream = new MemoryStream(imageBytes))
+ using (var imageStream = new MemoryStream(imageBytes))
{
- // Initialize a barcode reader that supports all barcode types
- using (BarCodeReader reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes))
+ // Create a BarCodeReader to recognize any supported barcode type
+ using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes))
{
// Iterate through all detected barcodes and output their type and decoded text
- foreach (BarCodeResult result in reader.ReadBarCodes())
+ foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}");
+ Console.WriteLine($"Detected Type: {result.CodeTypeName}");
Console.WriteLine($"Decoded Text: {result.CodeText}");
}
}
diff --git a/barcode-reading-properties/read-barcode-information-from-byte-array-representing-image-and-output-json-metadata.cs b/barcode-reading-properties/read-barcode-information-from-byte-array-representing-image-and-output-json-metadata.cs
index cc8f165..64639ce 100644
--- a/barcode-reading-properties/read-barcode-information-from-byte-array-representing-image-and-output-json-metadata.cs
+++ b/barcode-reading-properties/read-barcode-information-from-byte-array-representing-image-and-output-json-metadata.cs
@@ -1,69 +1,71 @@
-// Title: Read barcode from image byte array and output JSON
-// Description: Generates a Code128 barcode, reads it from an in‑memory byte array, and prints the decoded information as formatted JSON.
+// Title: Read barcode from byte array and output JSON metadata
+// Description: Demonstrates generating a barcode image, converting it to a byte array, reading the barcode from that array, and serializing the detection results to JSON.
+// Category-Description: This example belongs to the Aspose.BarCode reading and serialization category. It shows how to use BarcodeGenerator to create barcodes, BarCodeReader to decode them from streams, and System.Text.Json to produce structured JSON output. Developers often need to process barcode images received as byte arrays (e.g., from databases or web services) and extract metadata for logging, analytics, or further processing.
// Prompt: Read barcode information from a byte array representing an image and output JSON metadata.
-// Tags: barcode, code128, read, json, aspose.barcode, memorystream
+// Tags: code128, barcode, read, json, aspose.barcode, aspose.drawing, serialization
using System;
+using System.Collections.Generic;
using System.IO;
using System.Text.Json;
-using System.Collections.Generic;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Demonstrates how to generate a barcode, read it from a byte array, and output the decoded data as JSON.
+/// Example program that generates a barcode, reads it from a byte array,
+/// and outputs the detection metadata as formatted JSON.
///
class Program
{
///
- /// Entry point of the example. Generates a barcode image, reads it from memory, and prints JSON metadata.
+ /// Entry point of the example. Generates a sample barcode, reads it from memory,
+ /// collects detection details, and prints them as JSON.
///
- static void Main()
+ /// Command‑line arguments (not used).
+ static void Main(string[] args)
{
- // Generate a sample barcode image and store it in a byte array.
+ // Generate a sample Code128 barcode and store it in a memory stream.
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- using (var generationStream = new MemoryStream())
+ using (var memoryStream = new MemoryStream())
{
- // Save the generated barcode as PNG into the memory stream.
- generator.Save(generationStream, BarCodeImageFormat.Png);
- byte[] imageBytes = generationStream.ToArray();
+ // Save the barcode image as PNG into the memory stream.
+ generator.Save(memoryStream, BarCodeImageFormat.Png);
+ // Convert the stream contents to a byte array.
+ byte[] imageBytes = memoryStream.ToArray();
- // Read barcode information from the byte array.
- using (var readStream = new MemoryStream(imageBytes))
+ // Initialize a barcode reader to decode all supported types from the byte array.
+ using (var reader = new BarCodeReader(new MemoryStream(imageBytes), DecodeType.AllSupportedTypes))
{
- // Initialize the reader to decode all supported barcode types.
- using (var reader = new BarCodeReader(readStream, DecodeType.AllSupportedTypes))
- {
- var results = new List