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(); + var barcodeInfos = new List(); - // Iterate over each detected barcode. - foreach (var result in reader.ReadBarCodes()) + // Iterate over each detected barcode and collect its metadata. + foreach (var result in reader.ReadBarCodes()) + { + var rect = result.Region.Rectangle; + var info = new { - var rect = result.Region.Rectangle; - var info = new + CodeType = result.CodeTypeName, + CodeText = result.CodeText, + Confidence = result.Confidence, + ReadingQuality = result.ReadingQuality, + Region = new { - CodeType = result.CodeTypeName, - CodeText = result.CodeText, - Confidence = result.Confidence, - ReadingQuality = result.ReadingQuality, - Angle = result.Region.Angle, - Region = new - { - X = rect.X, - Y = rect.Y, - Width = rect.Width, - Height = rect.Height - } - }; - results.Add(info); - } - - // Serialize the collected barcode data to formatted JSON. - string json = JsonSerializer.Serialize(results, new JsonSerializerOptions { WriteIndented = true }); - Console.WriteLine(json); + X = rect.X, + Y = rect.Y, + Width = rect.Width, + Height = rect.Height + } + }; + barcodeInfos.Add(info); } + + // Serialize the collected metadata to indented JSON and output it. + string json = JsonSerializer.Serialize( + barcodeInfos, + new JsonSerializerOptions { WriteIndented = true }); + Console.WriteLine(json); } } } diff --git a/barcode-reading-properties/read-barcodes-from-multi-page-tiff-file-and-capture-orientation-for-each-page.cs b/barcode-reading-properties/read-barcodes-from-multi-page-tiff-file-and-capture-orientation-for-each-page.cs index 3b67b69..b6d9e37 100644 --- a/barcode-reading-properties/read-barcodes-from-multi-page-tiff-file-and-capture-orientation-for-each-page.cs +++ b/barcode-reading-properties/read-barcodes-from-multi-page-tiff-file-and-capture-orientation-for-each-page.cs @@ -1,7 +1,8 @@ -// Title: Read barcodes from each page of a multi‑page TIFF and report orientation -// Description: Demonstrates loading a multi‑page TIFF, iterating through its pages, reading any barcodes present, and outputting the barcode type, text, and rotation angle for each page. +// Title: Read barcodes from a multi‑page TIFF and capture orientation per page +// Description: Demonstrates how to load a multi‑page TIFF, iterate through its pages, detect barcodes, and retrieve each barcode's orientation angle. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing the use of BarCodeReader, DecodeType, and image handling classes such as Image, Bitmap, and FrameDimension. Typical use cases include processing scanned documents, invoices, or multi‑page forms where barcodes may appear on any page and orientation information is required for downstream processing. Developers often need to extract barcode data and its rotation to correctly align or validate the content. // Prompt: Read barcodes from a multi‑page TIFF file and capture orientation for each page. -// Tags: barcode, tiff, orientation, multiframe, aspose.barcode, aspose.drawing +// Tags: barcode, recognition, tiff, multiframe, orientation, aspose.barcode, decode type, image processing using System; using System.IO; @@ -10,66 +11,73 @@ using Aspose.Drawing.Imaging; /// -/// Sample console application that reads barcodes from a multi‑page TIFF file -/// and prints each barcode's type, text, and orientation (angle) per page. +/// Example program that reads barcodes from each page of a multi‑page TIFF file +/// and reports the barcode type, text, and orientation angle. /// class Program { /// /// Entry point of the application. - /// Loads the TIFF, iterates through its pages, and uses Aspose.BarCode to detect barcodes. + /// Loads the TIFF, iterates through its frames, and uses + /// to detect and report barcodes along with their orientation. /// static void Main() { - // Path to the multi‑page TIFF file (adjust as needed) - const string tiffPath = "sample.tif"; + // Path to the multi‑page TIFF file. + string tiffPath = "sample.tiff"; - // Verify that the file exists before attempting to load it + // Verify that the file exists before attempting to load it. if (!File.Exists(tiffPath)) { Console.WriteLine($"File not found: {tiffPath}"); return; } - // Load the TIFF image using Aspose.Drawing + // Load the TIFF image from disk. using (Image tiffImage = Image.FromFile(tiffPath)) { - // Determine the number of pages/frames in the TIFF + // Get the total number of pages (frames) in the TIFF. int pageCount = tiffImage.GetFrameCount(FrameDimension.Page); - // Iterate over each page in the TIFF + // Process each page sequentially. for (int pageIndex = 0; pageIndex < pageCount; pageIndex++) { - // Select the current page as the active frame + // Activate the current page so it can be read. tiffImage.SelectActiveFrame(FrameDimension.Page, pageIndex); - // Create a bitmap representation of the current page for barcode scanning + // Clone the active frame into a Bitmap, which BarCodeReader requires. using (Bitmap pageBitmap = new Bitmap(tiffImage)) { - // Initialize the barcode reader to detect all supported barcode types - using (BarCodeReader reader = new BarCodeReader(pageBitmap, DecodeType.AllSupportedTypes)) + // Initialize the barcode reader. + using (BarCodeReader reader = new BarCodeReader()) { - // Optional: set quality settings (default is NormalQuality) - // reader.QualitySettings = QualitySettings.NormalQuality; + // Configure the reader to attempt decoding all supported symbologies. + reader.BarCodeReadType = DecodeType.AllSupportedTypes; - // Perform the barcode detection - BarCodeResult[] results = reader.ReadBarCodes(); + // Provide the bitmap image to the reader. + reader.SetBarCodeImage(pageBitmap); - // Output results for the current page - if (results.Length == 0) + int barcodeCount = 0; + + // Iterate over all detected barcodes on the current page. + foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($"Page {pageIndex + 1}: No barcodes detected."); + barcodeCount++; + + // Retrieve the orientation angle (in degrees) of the barcode region. + double orientation = result.Region.Angle; + + Console.WriteLine( + $"Page {pageIndex + 1}, Barcode {barcodeCount}: " + + $"Type = {result.CodeTypeName}, " + + $"Text = {result.CodeText}, " + + $"Orientation = {orientation}°"); } - else - { - foreach (BarCodeResult result in results) - { - // Retrieve the orientation angle of the detected barcode region - double orientation = result.Region.Angle; // orientation in degrees - // Print barcode details including type, text, and orientation - Console.WriteLine($"Page {pageIndex + 1}: Type = {result.CodeTypeName}, Text = {result.CodeText}, Orientation = {orientation}°"); - } + // If no barcodes were found, inform the user. + if (barcodeCount == 0) + { + Console.WriteLine($"Page {pageIndex + 1}: No barcodes detected."); } } } diff --git a/barcode-reading-properties/read-barcodes-from-video-frame-captured-by-webcam-and-log-orientation-angles.cs b/barcode-reading-properties/read-barcodes-from-video-frame-captured-by-webcam-and-log-orientation-angles.cs index 63142e1..92b2bba 100644 --- a/barcode-reading-properties/read-barcodes-from-video-frame-captured-by-webcam-and-log-orientation-angles.cs +++ b/barcode-reading-properties/read-barcodes-from-video-frame-captured-by-webcam-and-log-orientation-angles.cs @@ -1,63 +1,60 @@ -// Title: Barcode Orientation Detection from Rotated Image -// Description: Generates a Code128 barcode, rotates it to simulate a tilted webcam capture, then reads the barcode and logs its orientation angle. +// Title: Read QR barcode from image and log orientation angle +// Description: Generates a QR code, saves it to disk, reads it back, and logs the barcode type, text, and detected orientation angle. +// Category-Description: This example demonstrates Aspose.BarCode generation and recognition APIs. It shows how to create a barcode using BarcodeGenerator, save it as an image, and then use BarCodeReader to decode the barcode and retrieve its Region.Angle property. Developers working with barcode imaging, scanning, or orientation detection can use these patterns for QR, DataMatrix, and other symbologies in desktop or server applications. // Prompt: Read barcodes from a video frame captured by a webcam and log orientation angles. -// Tags: barcode, orientation, code128, aspose.barcode, image processing +// Tags: qr, barcode, generation, recognition, orientation, console, aspose.barcode using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; -using Aspose.Drawing.Imaging; +using Aspose.BarCode; /// -/// Demonstrates how to generate a barcode, rotate it, and read its orientation angle using Aspose.BarCode. +/// Demonstrates generating a QR barcode, saving it, and reading it back to log orientation information. /// class Program { /// - /// Entry point of the example. Generates a barcode, applies a rotation, reads it back, and prints the detected angle. + /// Entry point of the example. Generates a QR code, saves it, reads it, and outputs detection details. /// static void Main() { - // Generate a simple Code128 barcode image in memory. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123")) + // Define the output directory and barcode image path + string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Output"); + string barcodePath = Path.Combine(outputDir, "sample_barcode.png"); + + // Ensure the output directory exists + if (!Directory.Exists(outputDir)) { - using (var originalBmp = generator.GenerateBarCodeImage()) - { - // Create a bitmap to hold the rotated image. - using (var rotatedBmp = new Bitmap(originalBmp.Width, originalBmp.Height)) - { - // Obtain a graphics object for drawing onto the rotated bitmap. - using (var graphics = Graphics.FromImage(rotatedBmp)) - { - // Set high‑quality rendering options. - graphics.SmoothingMode = Aspose.Drawing.Drawing2D.SmoothingMode.AntiAlias; - graphics.InterpolationMode = Aspose.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; + Directory.CreateDirectory(outputDir); + } - // Translate the origin to the center, rotate, then translate back. - graphics.TranslateTransform(originalBmp.Width / 2f, originalBmp.Height / 2f); - graphics.RotateTransform(45f); - graphics.TranslateTransform(-originalBmp.Width / 2f, -originalBmp.Height / 2f); + // Generate a simple QR barcode and save it to a PNG file + using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Aspose.BarCode Sample")) + { + // Set QR error correction level (optional visual parameter) + generator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelM; + generator.Save(barcodePath, BarCodeImageFormat.Png); + } - // Draw the original barcode onto the rotated canvas. - graphics.DrawImage(originalBmp, 0, 0, originalBmp.Width, originalBmp.Height); - } + // Verify that the barcode image was successfully created + if (!File.Exists(barcodePath)) + { + Console.WriteLine($"Failed to create barcode image at '{barcodePath}'."); + return; + } - // Initialize a barcode reader for the rotated image, supporting all barcode types. - using (var reader = new BarCodeReader(rotatedBmp, DecodeType.AllSupportedTypes)) - { - // Iterate through all detected barcodes. - foreach (var result in reader.ReadBarCodes()) - { - // Output the decoded text. - Console.WriteLine($"Detected CodeText: {result.CodeText}"); - // Output the orientation angle of the barcode region. - Console.WriteLine($"Detected Angle: {result.Region.Angle}"); - } - } - } + // Read the barcode from the saved image and log its orientation angle + using (var reader = new BarCodeReader(barcodePath, DecodeType.QR)) + { + foreach (var result in reader.ReadBarCodes()) + { + // The Region.Angle property indicates the detected orientation of the barcode + Console.WriteLine($"Detected Barcode Type : {result.CodeTypeName}"); + Console.WriteLine($"Detected Code Text : {result.CodeText}"); + Console.WriteLine($"Detected Angle (deg) : {result.Region.Angle}"); + Console.WriteLine(); } } } diff --git a/barcode-reading-properties/read-barcodes-from-zip-archive-containing-multiple-image-files-and-aggregate-metadata.cs b/barcode-reading-properties/read-barcodes-from-zip-archive-containing-multiple-image-files-and-aggregate-metadata.cs index 42fa08a..d51e0b0 100644 --- a/barcode-reading-properties/read-barcodes-from-zip-archive-containing-multiple-image-files-and-aggregate-metadata.cs +++ b/barcode-reading-properties/read-barcodes-from-zip-archive-containing-multiple-image-files-and-aggregate-metadata.cs @@ -1,109 +1,108 @@ -// Title: Read barcodes from images inside a zip archive and output aggregated metadata as JSON -// Description: Demonstrates extracting image files from a zip, decoding any barcodes they contain, and collecting detailed information for each barcode. +// Title: Read barcodes from a zip archive and aggregate metadata +// Description: Demonstrates how to extract images from a zip file, recognize barcodes using Aspose.BarCode, and collect their metadata. +// Category-Description: This example belongs to the Aspose.BarCode image processing and barcode recognition category. It showcases the use of BarCodeReader, DecodeType, and related classes to batch‑process multiple images stored in a compressed archive, a common scenario for automated inventory or document scanning systems. Developers often need to read barcodes from bulk image collections, aggregate results, and integrate them into downstream workflows. // Prompt: Read barcodes from a zip archive containing multiple image files and aggregate metadata. -// Tags: barcode, zip, json, aspose.barcode, barcoderecognition, file-io +// Tags: barcode, recognition, zip, batch processing, aspose.barcode, decode type, metadata using System; +using System.Collections.Generic; using System.IO; using System.IO.Compression; -using System.Collections.Generic; -using System.Text.Json; using Aspose.BarCode; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; /// -/// Represents detailed information about a detected barcode. +/// Demonstrates reading barcodes from images stored inside a zip archive and aggregating their metadata. /// -class BarcodeInfo -{ - public string? FileName { get; set; } - public string? CodeTypeName { get; set; } - public string? CodeText { get; set; } - public int Confidence { get; set; } - public double ReadingQuality { get; set; } - public float RegionX { get; set; } - public float RegionY { get; set; } - public float RegionWidth { get; set; } - public float RegionHeight { get; set; } - public double RegionAngle { get; set; } -} - class Program { + // Simple DTO to hold barcode metadata + class BarcodeInfo + { + public string FileName { get; set; } + public string CodeTypeName { get; set; } + public string CodeText { get; set; } + public Rectangle Region { get; set; } + } + /// - /// Entry point. Reads barcodes from image files inside a zip archive and prints aggregated metadata as JSON. + /// Entry point. Processes the specified zip file (or default) and prints detected barcode information. /// - static void Main() + /// Command‑line arguments; first argument may specify the zip file path. + static void Main(string[] args) { - // Path to the zip file containing barcode images - const string zipPath = "barcodes.zip"; + // Determine zip file path (argument or default) + string zipPath = args.Length > 0 ? args[0] : "barcodes.zip"; - // Verify that the zip file exists before proceeding + // Verify that the zip file exists if (!File.Exists(zipPath)) { Console.WriteLine($"Zip file not found: {zipPath}"); return; } - // Collection to hold barcode information from all images - var aggregatedData = new List(); + var results = new List(); // Open the zip archive for reading - using (var zip = ZipFile.OpenRead(zipPath)) + using (FileStream zipFileStream = new FileStream(zipPath, FileMode.Open, FileAccess.Read)) + using (ZipArchive archive = new ZipArchive(zipFileStream, ZipArchiveMode.Read)) { - // Iterate through each entry (file) in the archive - foreach (var entry in zip.Entries) + // Iterate through each entry in the archive + foreach (var entry in archive.Entries) { - // Determine the file extension and process only supported image types - string ext = Path.GetExtension(entry.FullName).ToLowerInvariant(); - if (ext != ".png" && ext != ".jpg" && ext != ".jpeg" && ext != ".bmp" && ext != ".gif") + // Process only image files (png, jpg, jpeg, bmp) + string ext = Path.GetExtension(entry.Name).ToLowerInvariant(); + if (ext != ".png" && ext != ".jpg" && ext != ".jpeg" && ext != ".bmp") continue; - // Open a stream to the image file inside the zip - using (var entryStream = entry.Open()) + // Load entry into a memory stream + using (Stream entryStream = entry.Open()) + using (MemoryStream ms = new MemoryStream()) { - // Initialize the barcode reader - using (var reader = new BarCodeReader()) - { - // Configure the reader to detect all supported barcode types - reader.BarCodeReadType = DecodeType.AllSupportedTypes; - // Load the image stream into the reader - reader.SetBarCodeImage(entryStream); - - // Perform barcode detection - BarCodeResult[] results = reader.ReadBarCodes(); + entryStream.CopyTo(ms); + ms.Position = 0; // reset for reading - // Process each detected barcode - foreach (var result in results) + // Create bitmap from the memory stream + using (Bitmap bitmap = new Bitmap(ms)) + { + // Initialize reader for all supported barcode types + using (BarCodeReader reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes)) { - var rect = result.Region.Rectangle; - - // Populate a BarcodeInfo instance with details from the detection result - var info = new BarcodeInfo + // Read all barcodes found in the image + foreach (BarCodeResult result in reader.ReadBarCodes()) { - FileName = entry.FullName, - CodeTypeName = result.CodeTypeName, - CodeText = result.CodeText, - Confidence = (int)result.Confidence, - ReadingQuality = result.ReadingQuality, - RegionX = rect.X, - RegionY = rect.Y, - RegionWidth = rect.Width, - RegionHeight = rect.Height, - RegionAngle = result.Region.Angle - }; - - // Add the populated info to the aggregate list - aggregatedData.Add(info); + var info = new BarcodeInfo + { + FileName = entry.Name, + CodeTypeName = result.CodeTypeName, + CodeText = result.CodeText, + Region = result.Region.Rectangle + }; + results.Add(info); + } } } } } } - // Serialize the aggregated barcode data to formatted JSON - string json = JsonSerializer.Serialize(aggregatedData, new JsonSerializerOptions { WriteIndented = true }); - // Output the JSON to the console - Console.WriteLine(json); + // Output aggregated metadata + if (results.Count == 0) + { + Console.WriteLine("No barcodes were detected in the archive."); + } + else + { + Console.WriteLine("Detected barcodes:"); + foreach (var info in results) + { + Console.WriteLine($"File: {info.FileName}"); + Console.WriteLine($" Type : {info.CodeTypeName}"); + Console.WriteLine($" Text : {info.CodeText}"); + Console.WriteLine($" Region: X={info.Region.X}, Y={info.Region.Y}, Width={info.Region.Width}, Height={info.Region.Height}"); + Console.WriteLine(); + } + } } } \ No newline at end of file diff --git a/barcode-reading-properties/read-databar-expanded-data-fields-and-numeric-values-from-jpeg-image.cs b/barcode-reading-properties/read-databar-expanded-data-fields-and-numeric-values-from-jpeg-image.cs index 6a817f7..25e32f8 100644 --- a/barcode-reading-properties/read-databar-expanded-data-fields-and-numeric-values-from-jpeg-image.cs +++ b/barcode-reading-properties/read-databar-expanded-data-fields-and-numeric-values-from-jpeg-image.cs @@ -1,75 +1,73 @@ -// Title: Read DataBar Expanded barcode fields from JPEG -// Description: Demonstrates loading a JPEG image, recognizing a GS1 DataBar Expanded barcode, and extracting its data fields and numeric values. +// Title: Read DataBar Expanded fields from a JPEG image +// Description: Demonstrates how to generate a DataBar Expanded barcode, save it as a JPEG file, and then read its AI data fields and numeric values using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of BarcodeGenerator for creating GS1 DataBar Expanded symbols and BarCodeReader for extracting encoded data. Developers working with product identification, inventory, or retail scanning often need to generate and decode DataBar Expanded barcodes, making these APIs essential for handling AI (Application Identifier) data in .NET applications. // Prompt: Read DataBar expanded data fields and numeric values from a JPEG image. -// Tags: databar expanded, barcode recognition, jpeg, numeric extraction, aspose.barcode, aspose.drawing +// Tags: databar, expanded, read, jpeg, generation, recognition, aspose.barcode using System; using System.IO; -using System.Text.RegularExpressions; +using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; /// -/// Example program that reads GS1 DataBar Expanded barcodes from a JPEG image -/// and extracts numeric values from the decoded text. +/// Example program that creates a DataBar Expanded barcode image (if missing) and reads its data fields. /// class Program { /// - /// Entry point of the application. - /// Loads the image, performs barcode recognition, and prints extracted data. + /// Entry point of the example. Generates a sample barcode image and extracts its encoded information. /// static void Main() { - // Path to the JPEG image containing a GS1 DataBar Expanded barcode. + // Path for the sample JPEG image string imagePath = "databar_expanded.jpg"; - // Verify that the image file exists before attempting to load it. + // Generate a sample DataBar Expanded barcode if the file does not exist if (!File.Exists(imagePath)) { - Console.WriteLine($"File not found: {imagePath}"); - return; + // Example GS1 DataBar Expanded code text with numeric AI values + string codeText = "(01)12345678901231(3103)001500"; + + // Create a barcode generator for DataBar Expanded symbology + using (var generator = new BarcodeGenerator(EncodeTypes.DatabarExpanded, codeText)) + { + // Save the generated barcode as a JPEG image + generator.Save(imagePath, BarCodeImageFormat.Jpeg); + Console.WriteLine($"Sample barcode image created at '{imagePath}'."); + } } - // Load the image as a bitmap using Aspose.Drawing. - using (var bitmap = new Bitmap(imagePath)) + // Verify the image exists before attempting to read + if (!File.Exists(imagePath)) { - // Initialize a BarCodeReader to detect only DataBar Expanded barcodes. - using (var reader = new BarCodeReader(bitmap, DecodeType.DatabarExpanded)) - { - // Execute the recognition process. - BarCodeResult[] results = reader.ReadBarCodes(); + Console.WriteLine($"Image file '{imagePath}' not found."); + return; + } - // If no barcodes were found, inform the user and exit. - if (results.Length == 0) - { - Console.WriteLine("No barcodes were detected."); - return; - } + // Initialize a barcode reader for DataBar Expanded type + using (var reader = new BarCodeReader(imagePath, DecodeType.DatabarExpanded)) + { + // Read all barcodes found in the image + BarCodeResult[] results = reader.ReadBarCodes(); - // Iterate through each detected barcode and display its details. - foreach (var result in results) - { - Console.WriteLine($"Barcode Type: {result.CodeTypeName}"); - Console.WriteLine($"Code Text: {result.CodeText}"); + // If no barcodes were detected, inform the user + if (results.Length == 0) + { + Console.WriteLine("No barcodes were detected in the image."); + return; + } - // Use a regular expression to extract all numeric substrings from the code text. - var matches = Regex.Matches(result.CodeText ?? string.Empty, @"\d+"); - if (matches.Count > 0) - { - Console.WriteLine("Numeric values:"); - foreach (Match match in matches) - { - Console.WriteLine($" {match.Value}"); - } - } - else - { - Console.WriteLine("No numeric values found."); - } + // Iterate through each detected barcode and display its details + foreach (var result in results) + { + Console.WriteLine($"Barcode Type: {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); - Console.WriteLine(); // Blank line between barcodes for readability. - } + // DataBar extended parameters provide additional flags (e.g., composite component) + Console.WriteLine($"Is 2D Composite Component: {result.Extended.DataBar.Is2DCompositeComponent}"); + Console.WriteLine(); } } } diff --git a/barcode-reading-properties/read-datamatrix-symbol-size-and-encoding-mode-from-tiff-image-with-datamatrix-barcodes.cs b/barcode-reading-properties/read-datamatrix-symbol-size-and-encoding-mode-from-tiff-image-with-datamatrix-barcodes.cs index 6265c7d..7e7a75d 100644 --- a/barcode-reading-properties/read-datamatrix-symbol-size-and-encoding-mode-from-tiff-image-with-datamatrix-barcodes.cs +++ b/barcode-reading-properties/read-datamatrix-symbol-size-and-encoding-mode-from-tiff-image-with-datamatrix-barcodes.cs @@ -1,58 +1,53 @@ -// Title: Read DataMatrix Symbol Size and Encoding Mode from TIFF -// Description: Demonstrates how to load a TIFF image containing DataMatrix barcodes, iterate through detected symbols, and attempt to retrieve symbol size and encoding mode (which are not exposed by the API). -// Prompt: Read DataMatrix symbol size and encoding mode from a TIFF image with DataMatrix barcodes. -// Tags: datamatrix, barcode, recognition, tiff, aspose.barcode, aspnet +// Title: Read DataMatrix Symbol Size and Encoding Mode from TIFF Image +// Description: Demonstrates how to load a TIFF file containing DataMatrix barcodes and retrieve basic barcode information using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode recognition category, illustrating the use of BarCodeReader with DecodeType.DataMatrix to extract barcode type, text, and region. Developers often need to process scanned documents, extract barcode data, and handle multi-page TIFFs. The example shows typical API usage for reading barcodes from images. +/// Prompt: Read DataMatrix symbol size and encoding mode from a TIFF image with DataMatrix barcodes. +/// Tags: datamatrix, barcode, recognition, tiff, aspose.barcode, csharp using System; using System.IO; using Aspose.BarCode.BarCodeRecognition; -using Aspose.BarCode.Generation; using Aspose.Drawing; /// -/// Example program that reads DataMatrix barcodes from a TIFF image -/// and displays available recognition information. +/// Demonstrates reading DataMatrix barcodes from a TIFF image and attempting to obtain symbol size and encoding mode. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Loads the image, validates its existence, and iterates over detected DataMatrix barcodes. /// static void Main() { - // Path to the TIFF image containing DataMatrix barcodes - string imagePath = "datamatrix.tiff"; + // Path to the TIFF image containing DataMatrix barcodes. + const string imagePath = "datamatrix.tif"; - // Verify that the file exists before attempting to read it + // Verify that the file exists before attempting to read it. if (!File.Exists(imagePath)) { Console.WriteLine($"File not found: {imagePath}"); return; } - // Create a BarCodeReader configured for DataMatrix symbology + // Create a BarCodeReader configured for DataMatrix symbology. using (var reader = new BarCodeReader(imagePath, DecodeType.DataMatrix)) { - // Iterate through all detected barcodes in the image + // Iterate through all detected barcodes in the image. foreach (var result in reader.ReadBarCodes()) { - // Output basic barcode information - Console.WriteLine($"Detected barcode type: {result.CodeTypeName}"); - Console.WriteLine($"Code text: {result.CodeText}"); + // Output basic barcode information. + Console.WriteLine($"Barcode Type: {result.CodeTypeName}"); + Console.WriteLine($"Code Text: {result.CodeText}"); - // Retrieve DataMatrix‑specific extended parameters - var dmExt = result.Extended.DataMatrix; + // Retrieve and display the bounding rectangle of the detected barcode. + var rect = result.Region.Rectangle; + Console.WriteLine($"Region - X:{rect.X}, Y:{rect.Y}, Width:{rect.Width}, Height:{rect.Height}"); - // Symbol size (version) and encoding mode are not exposed directly - // via the public recognition API. We report their unavailability. - Console.WriteLine("Symbol size (version): not available via recognition API"); - Console.WriteLine("Encoding mode: not available via recognition API"); - - // Additional DataMatrix flags that are available - Console.WriteLine($"Is Reader Programming: {dmExt.IsReaderProgramming}"); - Console.WriteLine($"Structured Append Barcode ID: {dmExt.StructuredAppendBarcodeId}"); - Console.WriteLine($"Structured Append Barcodes Count: {dmExt.StructuredAppendBarcodesCount}"); - Console.WriteLine($"Structured Append File ID: {dmExt.StructuredAppendFileId}"); + // Symbol size (DataMatrix version) and encoding mode are not directly exposed + // via the Aspose.BarCode recognition API. They would require accessing + // extended parameters that are not part of the public API. + Console.WriteLine("Symbol Size: Not directly available via API"); + Console.WriteLine("Encoding Mode: Not directly available via API"); Console.WriteLine(); } } diff --git a/barcode-reading-properties/read-qr-code-structured-append-parity-data-and-validate-against-expected-values-for-each-segment.cs b/barcode-reading-properties/read-qr-code-structured-append-parity-data-and-validate-against-expected-values-for-each-segment.cs index 9087a5d..778fc3c 100644 --- a/barcode-reading-properties/read-qr-code-structured-append-parity-data-and-validate-against-expected-values-for-each-segment.cs +++ b/barcode-reading-properties/read-qr-code-structured-append-parity-data-and-validate-against-expected-values-for-each-segment.cs @@ -1,66 +1,89 @@ -// Title: QR Code Structured‑Append Parity Validation Example -// Description: Demonstrates generating QR codes with structured‑append settings, reading them, and verifying the parity bytes for each segment. +// Title: Read QR Code Structured‑Append Parity Data and Validate Segments +// Description: Demonstrates generating multiple QR code segments with Structured Append, reading them back, and verifying parity and sequence data. +// Category-Description: This example belongs to the Aspose.BarCode QR Code generation and recognition category. It showcases the BarcodeGenerator for creating QR codes with Structured Append settings and the BarCodeReader for extracting Extended QR properties. Developers often need to split large messages across several QR symbols, ensure correct ordering, and validate parity data; this snippet provides a concise reference for those common tasks. // Prompt: Read QR Code structured‑append parity data and validate against expected values for each segment. -// Tags: qr code, structured-append, parity validation, barcode generation, barcode recognition, aspose.barcode +// Tags: qr code, structured append, validation, barcode generation, barcode recognition, aspose.barcode using System; +using System.Collections.Generic; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; /// -/// Example program that generates QR code segments with structured‑append settings, -/// reads them back, and validates the parity bytes. +/// Generates a series of QR codes using Structured Append, reads them back, +/// and validates the total count, sequence indicator, and parity byte for each segment. /// class Program { /// - /// Entry point. Generates QR code segments, reads each, and checks parity data. + /// Entry point of the example. Creates QR code segments, reads them, and prints validation results. /// static void Main() { - // Define structured‑append parameters - const int totalCount = 3; - string[] segmentTexts = { "First segment", "Second segment", "Third segment" }; - byte[] expectedParity = { 0xAA, 0xAB, 0xAC }; // sample parity bytes for each segment + const int totalSegments = 3; // Number of QR code segments to generate + const byte parityByte = 0xAB; // Parity byte shared across all segments + string baseText = "Segment "; // Base text for each QR code payload - // Loop through each segment to generate, read, and validate - for (int i = 0; i < totalCount; i++) + // Store generated QR images in memory streams for later reading + var qrStreams = new List(); + + // ------------------------------------------------------------ + // Generate QR codes with Structured Append configuration + // ------------------------------------------------------------ + for (int i = 0; i < totalSegments; i++) { - // Create QR generator with the current segment text - using (var generator = new BarcodeGenerator(EncodeTypes.QR, segmentTexts[i])) + using (var generator = new BarcodeGenerator(EncodeTypes.QR, baseText + i)) { - // Configure structured‑append settings for this segment - generator.Parameters.Barcode.QR.StructuredAppend.TotalCount = totalCount; + // Set Structured Append parameters: total count, sequence index, and parity byte + generator.Parameters.Barcode.QR.StructuredAppend.TotalCount = totalSegments; generator.Parameters.Barcode.QR.StructuredAppend.SequenceIndicator = i; - generator.Parameters.Barcode.QR.StructuredAppend.ParityByte = expectedParity[i]; + generator.Parameters.Barcode.QR.StructuredAppend.ParityByte = parityByte; - // Generate barcode image in memory - using (Bitmap bitmap = generator.GenerateBarCodeImage()) + // Save the QR code image to a memory stream (PNG format) + var ms = new MemoryStream(); + generator.Save(ms, BarCodeImageFormat.Png); + ms.Position = 0; // Reset stream position for subsequent reading + qrStreams.Add(ms); + } + } + + // ------------------------------------------------------------ + // Read each QR code and validate Structured Append metadata + // ------------------------------------------------------------ + for (int i = 0; i < qrStreams.Count; i++) + { + var stream = qrStreams[i]; + using (var reader = new BarCodeReader(stream, DecodeType.QR)) + { + foreach (var result in reader.ReadBarCodes()) { - // Initialize reader to decode the generated QR code - using (var reader = new BarCodeReader(bitmap, DecodeType.QR)) - { - // Iterate over all recognized barcodes (should be one per image) - foreach (var result in reader.ReadBarCodes()) - { - // Retrieve parity data from the recognized barcode - int parity = result.Extended.QR.StructuredAppendModeParityData; + // Extract reader‑side Structured Append properties from the result + int detectedTotal = result.Extended.QR.StructuredAppendModeBarCodesQuantity; + int detectedIndex = result.Extended.QR.StructuredAppendModeBarCodeIndex; + int detectedParity = result.Extended.QR.StructuredAppendModeParityData; - // Validate parity against the expected value - bool isValid = parity == expectedParity[i]; + // Compare detected values with the expected ones + bool totalMatch = detectedTotal == totalSegments; + bool indexMatch = detectedIndex == i; + bool parityMatch = detectedParity == parityByte; - // Output validation results - Console.WriteLine($"Segment {i + 1}:"); - Console.WriteLine($" CodeText: {result.CodeText}"); - Console.WriteLine($" Expected Parity: 0x{expectedParity[i]:X2}"); - Console.WriteLine($" Detected Parity: 0x{parity:X2}"); - Console.WriteLine($" Parity Valid: {isValid}"); - } - } + // Output validation results to the console + Console.WriteLine($"Segment {i}:"); + Console.WriteLine($" Expected TotalCount = {totalSegments}, Detected = {detectedTotal} => {(totalMatch ? "OK" : "FAIL")}"); + Console.WriteLine($" Expected SequenceIndicator = {i}, Detected = {detectedIndex} => {(indexMatch ? "OK" : "FAIL")}"); + Console.WriteLine($" Expected ParityByte = 0x{parityByte:X2}, Detected = 0x{detectedParity:X2} => {(parityMatch ? "OK" : "FAIL")}"); } } } + + // ------------------------------------------------------------ + // Cleanup: dispose all memory streams + // ------------------------------------------------------------ + foreach (var ms in qrStreams) + { + ms.Dispose(); + } } } \ No newline at end of file diff --git a/barcode-reading-properties/read-qr-code-version-and-error-correction-level-from-each-detected-qr-barcode.cs b/barcode-reading-properties/read-qr-code-version-and-error-correction-level-from-each-detected-qr-barcode.cs index b6f7014..7af3c24 100644 --- a/barcode-reading-properties/read-qr-code-version-and-error-correction-level-from-each-detected-qr-barcode.cs +++ b/barcode-reading-properties/read-qr-code-version-and-error-correction-level-from-each-detected-qr-barcode.cs @@ -1,63 +1,84 @@ -// Title: Read QR Code version and error correction level from detected QR barcodes -// Description: Demonstrates generating QR codes with specific version and error correction level, then reading them back to retrieve those properties. +// Title: Read QR Code version and error correction level from detected barcodes +// Description: Generates a QR code image, then reads the image to extract each QR code's version and error correction level. +// Category-Description: This example belongs to the Aspose.BarCode QR code recognition category, demonstrating how to use BarcodeGenerator and BarCodeReader to create QR codes and retrieve extended QR parameters such as version and error correction level. Developers working with QR code generation and decoding often need to access these properties for validation, analytics, or adaptive processing. The example showcases key classes like BarcodeGenerator, BarCodeReader, QRExtendedParameters, and QRErrorLevel. // Prompt: Read QR Code version and error correction level from each detected QR barcode. -// Tags: qr, barcode, version, error-correction, generation, recognition, aspose.barcode +// Tags: qr,barcode,recognition,generation,version,error-correction,aspose.barcode using System; using System.IO; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.BarCode; /// -/// Example program that generates QR codes with specific version and error correction level, -/// then reads them back to display the detected version and error level. +/// Demonstrates generating a QR code, saving it to a file, and then reading the QR code +/// to obtain its version and error correction level using Aspose.BarCode APIs. /// class Program { /// - /// Entry point. Generates sample QR codes, reads them, and prints version and error level. + /// Entry point of the example. Generates a QR code image, verifies its existence, + /// reads the QR code(s) from the image, and outputs version and error correction level. /// static void Main() { - // Define sample QR code configurations: version and error correction level - var samples = new (int version, QRErrorLevel level)[] + // Define the output image path for the generated QR code + string imagePath = "sample_qr.png"; + + // Generate a QR code with sample text and a high error correction level + using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Sample QR Text")) { - (5, QRErrorLevel.LevelL), - (10, QRErrorLevel.LevelM), - (15, QRErrorLevel.LevelH) - }; + // Set a specific error correction level (optional, LevelH provides the highest redundancy) + generator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelH; + + // Save the generated QR code image to the specified path + generator.Save(imagePath); + } - // Iterate over each sample configuration - foreach (var (version, level) in samples) + // Ensure the image file was created before attempting to read it + if (!File.Exists(imagePath)) { - // Create a QR code generator with the sample text - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "Sample QR")) + Console.WriteLine($"File not found: {imagePath}"); + return; + } + + // Initialize a barcode reader configured to decode QR codes from the image + using (var reader = new BarCodeReader(imagePath, DecodeType.QR)) + { + // Iterate through all detected QR barcodes in the image + foreach (var result in reader.ReadBarCodes()) { - // Set the desired QR version and error correction level - generator.Parameters.Barcode.QR.Version = (QRVersion)version; - generator.Parameters.Barcode.QR.ErrorLevel = level; + // Output the decoded text of the QR code + Console.WriteLine($"Detected QR Code Text: {result.CodeText}"); + + // Prepare default values for version and error correction level + string version = "N/A"; + string errorLevel = "N/A"; - // Save the generated QR code to a memory stream in PNG format - using (MemoryStream ms = new MemoryStream()) + // Attempt to retrieve the QR version (1‑40) from extended parameters + try { - generator.Save(ms, BarCodeImageFormat.Png); - ms.Position = 0; // Reset stream position for reading + version = result.Extended.QR.Version.ToString(); + } + catch + { + // If the property is unavailable, keep the default "N/A" + } - // Initialize a QR code reader on the memory stream - using (BarCodeReader reader = new BarCodeReader(ms, DecodeType.QR)) - { - // Read all detected barcodes - foreach (BarCodeResult result in reader.ReadBarCodes()) - { - // Ensure the detected barcode is a QR code - if (result.CodeTypeName.Equals("QR", StringComparison.OrdinalIgnoreCase)) - { - // Output the detected QR version and error correction level - Console.WriteLine($"Detected QR - Version: {result.Extended.QR.Version}, ErrorLevel: {result.Extended.QR.ErrorLevel}"); - } - } - } + // Attempt to retrieve the error correction level from extended parameters + try + { + errorLevel = result.Extended.QR.ErrorLevel.ToString(); } + catch + { + // If the property is unavailable, keep the default "N/A" + } + + // Output the extracted QR version and error correction level + Console.WriteLine($"QR Version: {version}"); + Console.WriteLine($"Error Correction Level: {errorLevel}"); + Console.WriteLine(); } } } diff --git a/barcode-reading-properties/retrieve-maxicode-mode-and-postal-code-data-from-pdf-containing-maxicode-symbols.cs b/barcode-reading-properties/retrieve-maxicode-mode-and-postal-code-data-from-pdf-containing-maxicode-symbols.cs index 8c3dfec..ab1ac61 100644 --- a/barcode-reading-properties/retrieve-maxicode-mode-and-postal-code-data-from-pdf-containing-maxicode-symbols.cs +++ b/barcode-reading-properties/retrieve-maxicode-mode-and-postal-code-data-from-pdf-containing-maxicode-symbols.cs @@ -1,95 +1,86 @@ -// Title: Retrieve MaxiCode mode and postal code from PDF -// Description: Demonstrates how to extract MaxiCode mode and postal code information from each page of a PDF containing MaxiCode symbols. +// Title: Retrieve MaxiCode mode and postal code from a PDF +// Description: Demonstrates extracting the MaxiCode mode and associated postal code data from a PDF file that contains MaxiCode symbols. +// Category-Description: This example belongs to the Aspose.BarCode PDF barcode extraction category. It uses Aspose.Pdf to render PDF pages to images and Aspose.BarCode.BarCodeRecognition to decode MaxiCode symbols. Typical use cases include processing shipping documents, invoices, or any PDF containing MaxiCode for logistics. Developers often need to read mode‑specific data such as postal codes, carrier IDs, or other structured information from MaxiCode barcodes. // Prompt: Retrieve MaxiCode mode and postal code data from a PDF containing MaxiCode symbols. -// Tags: barcode, maxicode, pdf, extraction, aspose, codetext +// Tags: maxicode, barcode, extraction, pdf, aspose.barcode, aspose.pdf, codetext, postalcode using System; using System.IO; -using Aspose.BarCode; -using Aspose.BarCode.BarCodeRecognition; -using Aspose.BarCode.ComplexBarcode; using Aspose.Pdf; using Aspose.Pdf.Facades; +using Aspose.BarCode.BarCodeRecognition; +using Aspose.BarCode.ComplexBarcode; /// -/// Example program that reads a PDF, converts each page to an image, -/// and extracts MaxiCode mode and postal code data from any detected MaxiCode symbols. +/// Program that extracts MaxiCode mode and postal code information from a PDF file. /// class Program { /// - /// Entry point of the application. + /// Entry point. Accepts an optional PDF path argument, renders each page to an image, + /// reads MaxiCode barcodes, and outputs the detected mode and postal code (if available). /// - static void Main() + /// Command‑line arguments; first argument may be the PDF file path. + static void Main(string[] args) { - // Path to the input PDF file containing MaxiCode symbols. - const string pdfPath = "input.pdf"; + // Determine the PDF file path: use the first argument if supplied, otherwise default to "sample.pdf". + string pdfPath = args.Length > 0 ? args[0] : "sample.pdf"; - // Verify that the PDF file exists before proceeding. + // Verify that the file exists before proceeding. if (!File.Exists(pdfPath)) { Console.WriteLine($"File not found: {pdfPath}"); return; } - // Load the PDF document. + // Open the PDF document using Aspose.Pdf. using (var pdfDocument = new Document(pdfPath)) { - // Initialize a PDF converter to render pages as images. - using (var pdfConverter = new PdfConverter(pdfDocument)) + // Initialize a PdfConverter to render pages as images with barcode optimization enabled. + using (var converter = new PdfConverter(pdfDocument)) { - // Enable barcode optimization for better recognition performance. - pdfConverter.RenderingOptions.BarcodeOptimization = true; + converter.RenderingOptions.BarcodeOptimization = true; // Iterate through each page in the PDF. for (int pageNumber = 1; pageNumber <= pdfDocument.Pages.Count; pageNumber++) { // Configure the converter to process a single page. - pdfConverter.StartPage = pageNumber; - pdfConverter.EndPage = pageNumber; - pdfConverter.DoConvert(); + converter.StartPage = pageNumber; + converter.EndPage = pageNumber; + converter.DoConvert(); - // Store the rendered page image in a memory stream. - using (var pageImageStream = new MemoryStream()) + // Render the current page to a memory stream (image format). + using (var imageStream = new MemoryStream()) { - pdfConverter.GetNextImage(pageImageStream); - pageImageStream.Position = 0; // Reset stream position for reading. + converter.GetNextImage(imageStream); + imageStream.Position = 0; // Reset stream position for reading. - // Create a barcode reader that attempts to decode all supported types. - using (var reader = new BarCodeReader(pageImageStream, DecodeType.AllSupportedTypes)) + // Create a BarCodeReader to decode MaxiCode symbols from the image. + using (var reader = new BarCodeReader(imageStream, DecodeType.MaxiCode)) { // Process each detected barcode on the page. foreach (BarCodeResult result in reader.ReadBarCodes()) { - // Skip results that are not MaxiCode. - if (result.Extended?.MaxiCode == null) - continue; - - // Retrieve the MaxiCode mode. + // Retrieve the MaxiCode mode from the extended result data. var mode = result.Extended.MaxiCode.Mode; - Console.WriteLine($"Page {pageNumber}: Detected MaxiCode"); - Console.WriteLine($" Mode: {mode}"); + Console.WriteLine($"Detected MaxiCode mode: {mode}"); + + // Decode the complex codetext using the identified mode. + var complexCodetext = ComplexCodetextReader.TryDecodeMaxiCode(mode, result.CodeText); - // Attempt to decode the MaxiCode codetext into a strongly‑typed object. - MaxiCodeCodetext decoded = ComplexCodetextReader.TryDecodeMaxiCode(mode, result.CodeText); - if (decoded == null) + // Output the postal code if the mode supports it. + switch (complexCodetext) { - Console.WriteLine(" Unable to decode MaxiCode codetext."); - continue; + case MaxiCodeCodetextMode2 mode2: + Console.WriteLine($"Postal Code: {mode2.PostalCode}"); + break; + case MaxiCodeCodetextMode3 mode3: + Console.WriteLine($"Postal Code: {mode3.PostalCode}"); + break; + default: + Console.WriteLine("Postal code not available for this mode."); + break; } - - // Extract postal code based on the specific MaxiCode mode. - string postalCode = null; - if (decoded is MaxiCodeCodetextMode2 mode2) - postalCode = mode2.PostalCode; - else if (decoded is MaxiCodeCodetextMode3 mode3) - postalCode = mode3.PostalCode; - - // Output the postal code if available. - if (!string.IsNullOrEmpty(postalCode)) - Console.WriteLine($" Postal Code: {postalCode}"); - else - Console.WriteLine(" Postal Code: (not available for this mode)"); } } } diff --git a/barcode-reading-properties/retrieve-pdf417-macro-fields-such-as-file-id-and-segment-id-from-scanned-document.cs b/barcode-reading-properties/retrieve-pdf417-macro-fields-such-as-file-id-and-segment-id-from-scanned-document.cs index 0e284aa..0488975 100644 --- a/barcode-reading-properties/retrieve-pdf417-macro-fields-such-as-file-id-and-segment-id-from-scanned-document.cs +++ b/barcode-reading-properties/retrieve-pdf417-macro-fields-such-as-file-id-and-segment-id-from-scanned-document.cs @@ -1,51 +1,79 @@ -// Title: Retrieve PDF417 Macro Fields from Scanned Image -// Description: Demonstrates how to read a PDF417 (or Macro PDF417) barcode from an image and extract macro fields such as file ID, segment ID, and segment count. +// Title: Retrieve Macro PDF417 fields from a barcode image +// Description: Demonstrates how to generate a Macro PDF417 barcode, save it, and then read macro fields such as file ID and segment ID from the scanned image. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on PDF417 macro symbology. It showcases the use of BarcodeGenerator for creating MacroPdf417 barcodes and BarCodeReader with DecodeType.MacroPdf417 for extracting extended macro parameters. Developers working with document scanning, batch processing, or secure data encoding often need to retrieve macro information to reconstruct multi‑part barcode data. // Prompt: Retrieve PDF417 macro fields such as file ID and segment ID from a scanned document. -// Tags: pdf417, macro, barcode, extraction, aspose, csharp +// Tags: pdf417, macro, barcode generation, barcode recognition, c#, aspose.barcode using System; using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Example program that reads a PDF417 (or Macro PDF417) barcode from an image -/// and prints its macro fields (file ID, segment ID, and segment count). +/// Example program that generates a Macro PDF417 barcode (if missing) and reads its macro fields +/// such as File ID, Segment ID, and Segments Count from the scanned image. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Handles barcode creation, file validation, and macro field extraction. /// static void Main() { - // Path to the scanned image containing a PDF417 (or Macro PDF417) barcode. - string imagePath = "sample.pdf417.png"; + // Define the path for the sample barcode image + string imagePath = "macropdf417.png"; - // Verify that the file exists before attempting to read it. + // ------------------------------------------------------------ + // Create a sample Macro PDF417 barcode if the image does not exist + // ------------------------------------------------------------ if (!File.Exists(imagePath)) { - Console.WriteLine($"Error: File not found - {imagePath}"); + using (var generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "SampleData")) + { + // Set macro-specific fields required for reconstruction + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 123; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 1; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 3; + + // Save the generated barcode image to disk + generator.Save(imagePath); + Console.WriteLine($"Generated sample barcode at '{Path.GetFullPath(imagePath)}'."); + } + } + + // ------------------------------------------------------------ + // Verify that the barcode image exists before attempting to read it + // ------------------------------------------------------------ + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Error: File '{imagePath}' not found."); return; } - // Create a BarCodeReader configured for PDF417 symbology. - using (var reader = new BarCodeReader(imagePath, DecodeType.Pdf417)) + // ------------------------------------------------------------ + // Read the barcode and extract macro information using BarCodeReader + // ------------------------------------------------------------ + using (var reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) { - // Iterate through all detected barcodes in the image. - foreach (var result in reader.ReadBarCodes()) + foreach (BarCodeResult result in reader.ReadBarCodes()) { - // Output basic barcode information. + // Basic barcode details Console.WriteLine($"BarCode Type: {result.CodeTypeName}"); Console.WriteLine($"BarCode CodeText: {result.CodeText}"); - // Access Macro PDF417 extended parameters. - var pdfExt = result.Extended.Pdf417; - - // Output macro fields. - Console.WriteLine($"Macro PDF417 File ID: {pdfExt.MacroPdf417FileID}"); - Console.WriteLine($"Macro PDF417 Segment ID: {pdfExt.MacroPdf417SegmentID}"); - Console.WriteLine($"Macro PDF417 Segments Count: {pdfExt.MacroPdf417SegmentsCount}"); - Console.WriteLine(); + // Access extended PDF417 macro parameters, if present + var pdf417Ext = result.Extended?.Pdf417; + if (pdf417Ext != null) + { + Console.WriteLine($"Macro PDF417 File ID: {pdf417Ext.MacroPdf417FileID}"); + Console.WriteLine($"Macro PDF417 Segment ID: {pdf417Ext.MacroPdf417SegmentID}"); + Console.WriteLine($"Macro PDF417 Segments Count: {pdf417Ext.MacroPdf417SegmentsCount}"); + } + else + { + Console.WriteLine("No Macro PDF417 extended parameters found."); + } } } } diff --git a/barcode-reading-properties/scale-down-high-resolution-images-before-barcode-reading-to-improve-performance-on-limited-hardware.cs b/barcode-reading-properties/scale-down-high-resolution-images-before-barcode-reading-to-improve-performance-on-limited-hardware.cs index e7f5fc7..44a3ca3 100644 --- a/barcode-reading-properties/scale-down-high-resolution-images-before-barcode-reading-to-improve-performance-on-limited-hardware.cs +++ b/barcode-reading-properties/scale-down-high-resolution-images-before-barcode-reading-to-improve-performance-on-limited-hardware.cs @@ -1,97 +1,103 @@ -// Title: Scaling High‑Resolution Images for Efficient Barcode Reading -// Description: Demonstrates how to downscale a high‑resolution image before barcode recognition to improve performance on constrained hardware. +// Title: Scale Down High‑Resolution Barcode Image for Faster Reading +// Description: Demonstrates generating a high‑resolution barcode, scaling it down, and reading the barcode to improve performance on limited hardware. +// Category-Description: This example belongs to the Aspose.BarCode image preprocessing category. It shows how to use BarcodeGenerator, Image manipulation classes from Aspose.Drawing, and BarCodeReader to downscale images before recognition. Developers often need to reduce image size to speed up barcode scanning on devices with constrained resources. // Prompt: Scale down high‑resolution images before barcode reading to improve performance on limited hardware. -// Tags: barcode, scaling, image processing, performance, aspose.barcode, aspose.drawing +// Tags: barcode, scaling, image preprocessing, code128, reading, generation, 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; +using Aspose.Drawing.Drawing2D; /// -/// Example program that scales down a high‑resolution image and reads barcodes from it. +/// Example program that creates a high‑resolution barcode, scales the image down, +/// and reads the barcode from the scaled image to demonstrate performance‑optimizing preprocessing. /// class Program { /// - /// Entry point. Loads an image, optionally scales it, and processes it for barcode detection. + /// Entry point of the example. Generates a barcode, downscales it, reads it, and cleans up temporary files. /// static void Main() { - // Path to the high‑resolution image containing barcodes - const string inputImagePath = "highres.png"; + // Paths for the generated high‑resolution and scaled images + const string highResPath = "highres.png"; + const string scaledPath = "scaled.png"; - // Verify that the image file exists before proceeding - if (!File.Exists(inputImagePath)) + // ------------------------------------------------- + // 1. Generate a high‑resolution barcode image + // ------------------------------------------------- + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - Console.WriteLine($"File not found: {inputImagePath}"); - return; + // Increase resolution to simulate a high‑resolution source (300 DPI) + generator.Parameters.Resolution = 300f; + // Save the barcode as a PNG file + generator.Save(highResPath, BarCodeImageFormat.Png); } - // Desired maximum dimension (width or height) after scaling, in pixels - const int maxDimension = 800; - - // Load the original high‑resolution image into a Bitmap object - using (var original = new Bitmap(inputImagePath)) + // Verify the high‑resolution file was created successfully + if (!File.Exists(highResPath)) { - // Determine the scaling factor while preserving the aspect ratio - float scale = 1f; - if (original.Width > original.Height) - { - // Landscape orientation: limit width - if (original.Width > maxDimension) - scale = (float)maxDimension / original.Width; - } - else - { - // Portrait orientation: limit height - if (original.Height > maxDimension) - scale = (float)maxDimension / original.Height; - } - - // If the image is already within the desired size, process it directly - if (scale >= 1f) - { - ProcessImage(original); - return; - } + Console.WriteLine($"Failed to create {highResPath}"); + return; + } - // Calculate new dimensions based on the scaling factor - int newWidth = (int)(original.Width * scale); - int newHeight = (int)(original.Height * scale); + // ------------------------------------------------- + // 2. Downscale the image to improve recognition speed + // ------------------------------------------------- + using (var originalImage = Image.FromFile(highResPath)) + { + // Calculate target dimensions (50 % of original size) + int targetWidth = originalImage.Width / 2; + int targetHeight = originalImage.Height / 2; - // Create a new bitmap with the reduced size - using (var scaled = new Bitmap(newWidth, newHeight)) + using (var scaledBitmap = new Bitmap(targetWidth, targetHeight)) { - // Render the original image onto the scaled bitmap - using (var graphics = Graphics.FromImage(scaled)) + using (var graphics = Graphics.FromImage(scaledBitmap)) { - graphics.DrawImage(original, 0, 0, newWidth, newHeight); + // Use high‑quality interpolation for better visual fidelity + graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; + // Draw the original image onto the scaled bitmap + graphics.DrawImage(originalImage, 0, 0, targetWidth, targetHeight); } - // Perform barcode recognition on the scaled image - ProcessImage(scaled); + // Save the downscaled image as PNG + scaledBitmap.Save(scaledPath, ImageFormat.Png); } } - } - // Reads barcodes from the provided bitmap and prints the detection results - private static void ProcessImage(Bitmap bitmap) - { - // Initialize the reader to detect all supported barcode types - using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes)) + // Verify the scaled file was created successfully + if (!File.Exists(scaledPath)) { - // Apply a high‑performance preset to speed up recognition - reader.QualitySettings = QualitySettings.HighPerformance; + Console.WriteLine($"Failed to create {scaledPath}"); + return; + } - // Iterate through each detected barcode and output its details + // ------------------------------------------------- + // 3. Read the barcode from the scaled image + // ------------------------------------------------- + using (var reader = new BarCodeReader(scaledPath, DecodeType.Code128)) + { foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($"BarCode Type: {result.CodeTypeName}"); - Console.WriteLine($"BarCode CodeText: {result.CodeText}"); + Console.WriteLine($"Detected barcode type: {result.CodeType}"); + Console.WriteLine($"Decoded text: {result.CodeText}"); } } + + // Cleanup: optional removal of temporary files (best‑effort) + try + { + File.Delete(highResPath); + File.Delete(scaledPath); + } + catch + { + // Ignored – cleanup failures are non‑critical + } } } \ No newline at end of file diff --git a/barcode-reading-properties/set-barcodereader-to-ignore-white-space-when-decoding-code39-barcodes-in-scanned-images.cs b/barcode-reading-properties/set-barcodereader-to-ignore-white-space-when-decoding-code39-barcodes-in-scanned-images.cs index fffdc81..fdc7988 100644 --- a/barcode-reading-properties/set-barcodereader-to-ignore-white-space-when-decoding-code39-barcodes-in-scanned-images.cs +++ b/barcode-reading-properties/set-barcodereader-to-ignore-white-space-when-decoding-code39-barcodes-in-scanned-images.cs @@ -1,46 +1,59 @@ -// Title: Code39 barcode decoding with whitespace ignored -// Description: Demonstrates generating a Code39 barcode containing spaces and configuring the reader to ignore whitespace during decoding. +// Title: Decode Code39 barcodes while ignoring whitespace +// Description: Demonstrates configuring BarCodeReader to strip spaces from decoded Code39 text, useful when scanning barcodes that contain unintended whitespace. +// Category-Description: This example belongs to the Aspose.BarCode recognition category, illustrating how to use BarCodeReader with DecodeType.Code39 and adjust QualitySettings to tolerate minor barcode imperfections. Developers often need to preprocess decoded strings, such as removing whitespace, to match expected data formats in inventory or tracking systems. // Prompt: Set BarCodeReader to ignore white space when decoding Code39 barcodes in scanned images. -// Tags: code39, barcode, whitespace, decoding, aspose.barcoderecognition, aspose.barcodegeneration +// Tags: code39, whitespace, barcode reader, decoding, aspose.barcode, recognition 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 Code39 barcode with spaces and reads it while ignoring whitespace. +/// Shows how to generate a Code39 barcode, read it, and ignore whitespace in the decoded result. /// class Program { /// - /// Entry point. Generates a barcode, reads it, and outputs original and whitespace‑removed text. + /// Entry point of the example. Generates a Code39 barcode containing spaces, + /// reads it with BarCodeReader, and outputs the original and whitespace‑removed text. /// static void Main() { - // Generate a Code39 barcode that contains white space in the codetext. - using (var generator = new BarcodeGenerator(EncodeTypes.Code39, "A B C")) + // Sample Code39 text containing spaces + const string originalCodeText = "A B C"; + + // Generate a Code39 barcode image in memory + using (var generator = new BarcodeGenerator(EncodeTypes.Code39, originalCodeText)) { - // Save the barcode image to a memory stream. + // Save barcode to a memory stream as PNG using (var ms = new MemoryStream()) { generator.Save(ms, BarCodeImageFormat.Png); - ms.Position = 0; // Reset stream position for reading. + ms.Position = 0; // Reset stream position for reading - // Load the image from the memory stream. + // Load the image from the memory stream using (var bitmap = new Bitmap(ms)) { - // Create a reader for Code39 barcodes. + // Initialize BarCodeReader for Code39 using (var reader = new BarCodeReader(bitmap, DecodeType.Code39)) { - // Read all detected barcodes. + // Allow recognition of barcodes with minor issues (e.g., unexpected spaces) + reader.QualitySettings.AllowIncorrectBarcodes = true; + + // Read all detected barcodes foreach (var result in reader.ReadBarCodes()) { - // Trim white space from the decoded text. - string trimmed = result.CodeText?.Replace(" ", string.Empty); - Console.WriteLine($"Original CodeText: '{result.CodeText}'"); - Console.WriteLine($"Trimmed CodeText: '{trimmed}'"); + // Original decoded text (may contain spaces) + string decoded = result.CodeText ?? string.Empty; + + // Ignore whitespace by removing all space characters + string cleaned = decoded.Replace(" ", string.Empty); + + Console.WriteLine($"Original decoded text: \"{decoded}\""); + Console.WriteLine($"Whitespace ignored text: \"{cleaned}\""); } } } diff --git a/barcode-reading-properties/set-maximum-number-of-barcodes-per-image-to-three-to-limit-processing-overhead.cs b/barcode-reading-properties/set-maximum-number-of-barcodes-per-image-to-three-to-limit-processing-overhead.cs index 195b675..9ba8344 100644 --- a/barcode-reading-properties/set-maximum-number-of-barcodes-per-image-to-three-to-limit-processing-overhead.cs +++ b/barcode-reading-properties/set-maximum-number-of-barcodes-per-image-to-three-to-limit-processing-overhead.cs @@ -1,92 +1,60 @@ -// Title: Barcode generation, combination, and limited decoding demonstration -// Description: This example creates three different barcodes, merges them into a single image, and then reads up to three barcodes from that image to limit processing overhead. +// Title: Limit barcode detection to three per image +// Description: Demonstrates how to generate a barcode image and read up to three barcodes from it, reducing processing overhead. +// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator to create barcodes and BarCodeReader to detect them, illustrating typical scenarios where developers need to limit the number of decoded barcodes per image for performance reasons. Common use cases include batch processing, real‑time scanning, and resource‑constrained environments. // Prompt: Set maximum number of barcodes per image to three to limit processing overhead. -// Tags: barcode generation, barcode recognition, limit processing, aspose.barcode, png +// Tags: barcode symbology, generation, recognition, png, barcodegenerator, barcodereader, limit using System; using System.IO; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.Drawing; -using Aspose.Drawing.Imaging; /// -/// Demonstrates generating multiple barcodes, combining them into one image, -/// and reading a limited number of barcodes from the combined image. +/// Example program that generates a barcode image and reads up to three barcodes from it. /// class Program { /// - /// Entry point of the program. Generates three barcodes, combines them, - /// saves the combined image, and reads up to three barcodes from it. + /// Entry point of the application. + /// Generates a sample barcode, then reads a maximum of three barcodes from the image. /// static void Main() { - // Generate three sample barcodes of different symbologies - Bitmap bmp1; - Bitmap bmp2; - Bitmap bmp3; + // Define the output path for the generated barcode image + const string imagePath = "sample.png"; - using (var gen1 = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + // Generate a Code128 barcode and save it as a PNG file + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) { - bmp1 = gen1.GenerateBarCodeImage(); + generator.Save(imagePath, BarCodeImageFormat.Png); } - using (var gen2 = new BarcodeGenerator(EncodeTypes.QR, "ABC")) - { - bmp2 = gen2.GenerateBarCodeImage(); - } - - using (var gen3 = new BarcodeGenerator(EncodeTypes.EAN13, "1234567890128")) - { - bmp3 = gen3.GenerateBarCodeImage(); - } - - // Combine the three barcode images side by side into a single bitmap - int totalWidth = bmp1.Width + bmp2.Width + bmp3.Width; - int maxHeight = Math.Max(bmp1.Height, Math.Max(bmp2.Height, bmp3.Height)); - - using (var combined = new Bitmap(totalWidth, maxHeight)) - { - using (var graphics = Graphics.FromImage(combined)) - { - // Draw each barcode at the appropriate horizontal offset - graphics.DrawImage(bmp1, 0, 0); - graphics.DrawImage(bmp2, bmp1.Width, 0); - graphics.DrawImage(bmp3, bmp1.Width + bmp2.Width, 0); - } - - // Save the combined image to disk as PNG - string combinedPath = "combined.png"; - combined.Save(combinedPath, ImageFormat.Png); - } - - // Release resources held by the individual barcode bitmaps - bmp1.Dispose(); - bmp2.Dispose(); - bmp3.Dispose(); - - // Verify that the combined image file exists before attempting to read it - string imagePath = "combined.png"; + // Verify that the image file was created successfully before attempting to read it if (!File.Exists(imagePath)) { - Console.WriteLine($"Image file not found: {imagePath}"); + Console.WriteLine("Barcode image not found."); return; } - // Read barcodes from the combined image, processing at most three to limit overhead + // Initialize a barcode reader to detect all supported barcode types in the image using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes)) { - var results = reader.ReadBarCodes(); - int processed = 0; - foreach (var result in results) + int count = 0; // Counter for the number of barcodes processed + + // Iterate through detected barcodes, stopping after three have been processed + foreach (var result in reader.ReadBarCodes()) { - if (processed >= 3) - break; + if (count >= 3) + break; // Exit loop once the maximum count is reached - Console.WriteLine($"Barcode {processed + 1}: Type = {result.CodeTypeName}, Text = {result.CodeText}"); - processed++; + Console.WriteLine($"Detected Barcode {count + 1}: Type={result.CodeTypeName}, Text={result.CodeText}"); + count++; } + + // Inform the user if no barcodes were found in the image + if (count == 0) + Console.WriteLine("No barcodes detected."); } } } \ No newline at end of file diff --git a/barcode-reading-properties/store-barcode-region-polygon-points-in-spatial-database-for-later-geometric-analysis.cs b/barcode-reading-properties/store-barcode-region-polygon-points-in-spatial-database-for-later-geometric-analysis.cs index c67421a..8d084ab 100644 --- a/barcode-reading-properties/store-barcode-region-polygon-points-in-spatial-database-for-later-geometric-analysis.cs +++ b/barcode-reading-properties/store-barcode-region-polygon-points-in-spatial-database-for-later-geometric-analysis.cs @@ -1,93 +1,90 @@ -// Title: Store barcode region polygon points as JSON (demo for spatial DB) -// Description: Generates a Code128 barcode, reads its region polygon points, and saves them as JSON for later geometric analysis. +// Title: Store barcode region polygon points in a spatial database +// Description: Demonstrates generating a barcode, reading its region polygon points, and persisting them for later geometric analysis. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, showcasing how to use BarcodeGenerator, BarCodeReader, and related region data classes. Developers often need to extract barcode location geometry for spatial indexing, GIS integration, or custom analytics. The snippet illustrates creating a barcode, retrieving its region points, and serializing them for storage, a common workflow when building spatial databases of barcode locations. // Prompt: Store barcode region polygon points in a spatial database for later geometric analysis. -// Tags: barcode, code128, region, polygon, json, spatial database, aspose.barcode +// Tags: barcode, code128, region, polygon, json, spatial database, generation, recognition, aspose.barcode using System; +using System.Collections.Generic; using System.IO; using System.Text.Json; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.Drawing; -/// -/// Demonstrates generating a barcode, extracting its region polygon points, -/// and persisting those points as JSON (as a placeholder for a spatial database). -/// -class Program +namespace BarcodeRegionStorage { - /// - /// Entry point of the example. Generates a barcode, reads its region, - /// and writes the polygon points to a JSON file. - /// - static void Main() + // Simple DTO for JSON serialization of a point + public class PointInfo { - // Define file paths for the barcode image and the JSON output. - string imagePath = "barcode.png"; - string jsonPath = "barcode_regions.json"; - - // ----------------------------------------------------------------- - // 1. Generate a simple Code128 barcode and save it as an image. - // ----------------------------------------------------------------- - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) - { - // Optional: configure image size for better visibility. - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; + public float X { get; set; } + public float Y { get; set; } + } - // Save the generated barcode image to the specified path. - generator.Save(imagePath); - } + // DTO that groups a barcode's text with its region polygon points + public class RegionInfo + { + public string CodeText { get; set; } + public List Points { get; set; } + } - // ----------------------------------------------------------------- - // 2. Read the barcode image and obtain its region polygon points. - // ----------------------------------------------------------------- - using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + /// + /// Demonstrates generating a barcode, extracting its region polygon points, and storing them for later geometric analysis. + /// + class Program + { + /// + /// Entry point that creates a barcode image, reads its region points, and writes them to a JSON file. + /// + static void Main() { - // Decode all barcodes present in the image. - var results = reader.ReadBarCodes(); - - // Prepare a list to hold region data for each detected barcode. - var barcodeRegions = new System.Collections.Generic.List(); + // Define file paths for the temporary barcode image and the output JSON file + string imagePath = "sample_barcode.png"; + string jsonPath = "barcode_regions.json"; - // Iterate over each decoded result. - foreach (var result in results) + // 1. Generate a barcode image using Code128 symbology + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) { - // result.Region.Points returns an array of PointF structures (X,Y coordinates). - var points = result.Region.Points; - var pointList = new System.Collections.Generic.List(); + // Save the generated barcode to the specified image file + generator.Save(imagePath); + } - // Convert each PointF to an anonymous object with X and Y properties. - foreach (var pt in points) + // 2. Read the barcode from the image and extract its region polygon points + var regions = new List(); + using (var reader = new BarCodeReader(imagePath, DecodeType.Code128)) + { + // Iterate over all detected barcodes (there should be only one in this example) + foreach (var result in reader.ReadBarCodes()) { - pointList.Add(new { X = pt.X, Y = pt.Y }); - } + var regionInfo = new RegionInfo + { + CodeText = result.CodeText, + Points = new List() + }; - // Add the barcode data and its polygon points to the collection. - barcodeRegions.Add(new - { - CodeText = result.CodeText, - Symbology = result.CodeTypeName, - Points = pointList - }); + // result.Region.Points provides the polygon vertices of the barcode region + foreach (var pt in result.Region.Points) + { + // Convert each Aspose.BarCode.Point to the serializable PointInfo DTO + regionInfo.Points.Add(new PointInfo + { + X = pt.X, + Y = pt.Y + }); + } + + // Add the populated region information to the collection + regions.Add(regionInfo); + } } - // ----------------------------------------------------------------- - // 3. Store the polygon points locally as JSON (stand‑in for a spatial DB). - // ----------------------------------------------------------------- + // 3. Serialize the extracted region data to JSON (acting as a stand‑in for a spatial database) var jsonOptions = new JsonSerializerOptions { WriteIndented = true }; - string json = JsonSerializer.Serialize(barcodeRegions, jsonOptions); + string json = JsonSerializer.Serialize(regions, jsonOptions); File.WriteAllText(jsonPath, json); - Console.WriteLine($"Barcode region data written to '{jsonPath}'."); + // Inform the user that the operation completed successfully + Console.WriteLine($"Barcode region data saved to '{jsonPath}'."); } - - // ----------------------------------------------------------------- - // NOTE: In a real scenario you would store the polygon points in a spatial - // database (e.g., SQLite with SpatiaLite, PostgreSQL with PostGIS, etc.). - // The code would involve creating a table with a geometry column and - // inserting the points using appropriate spatial types (e.g., POLYGON). - // ----------------------------------------------------------------- } } \ No newline at end of file diff --git a/barcode-reading-properties/use-barcodereader-on-pdf-stream-to-decode-barcodes-embedded-on-each-page.cs b/barcode-reading-properties/use-barcodereader-on-pdf-stream-to-decode-barcodes-embedded-on-each-page.cs index a62728a..d28acdb 100644 --- a/barcode-reading-properties/use-barcodereader-on-pdf-stream-to-decode-barcodes-embedded-on-each-page.cs +++ b/barcode-reading-properties/use-barcodereader-on-pdf-stream-to-decode-barcodes-embedded-on-each-page.cs @@ -1,82 +1,46 @@ -// Title: Decode Barcodes from Each Page of a PDF Using BarCodeReader -// Description: Demonstrates how to convert each PDF page to an image stream and use BarCodeReader to detect all supported barcode types. +// Title: Decode barcodes from each page of a PDF using BarCodeReader +// Description: Demonstrates how to read a PDF file as a stream and extract all barcodes on every page. +// Category-Description: This example belongs to the Aspose.BarCode PDF barcode recognition category. It shows how to use BarCodeReader with a PDF stream to detect any supported barcode symbology across multiple pages. Developers often need to batch‑process PDFs to retrieve embedded barcodes for inventory, shipping, or document automation tasks. // Prompt: Use BarCodeReader on a PDF stream to decode barcodes embedded on each page. -// Tags: barcode, pdf, decoding, aspnet, aspose, barcodereader, image +// Tags: pdf, barcode, decoding, barcodereader, aspnet, aspnetcore, csharp, aspose.barcode using System; using System.IO; using Aspose.BarCode.BarCodeRecognition; -using Aspose.Pdf; -using Aspose.Pdf.Facades; /// -/// Sample console application that reads a PDF file, renders each page to an image, -/// and decodes any barcodes found on the page using Aspose.BarCode. +/// Demonstrates barcode decoding from a PDF file using Aspose.BarCode's BarCodeReader. /// class Program { /// - /// Entry point of the application. + /// Entry point. Reads a PDF stream, scans each page for barcodes, and prints their type and text. /// static void Main() { - // Path to the PDF file containing barcodes. + // Path to the PDF file containing barcodes const string pdfPath = "sample.pdf"; - // Verify that the PDF file exists before proceeding. + // Verify that the PDF file exists before attempting to read it if (!File.Exists(pdfPath)) { Console.WriteLine($"File not found: {pdfPath}"); return; } - // Open the PDF document for processing. - using (var pdfDocument = new Document(pdfPath)) + // Open the PDF file as a read‑only stream + using (FileStream pdfStream = new FileStream(pdfPath, FileMode.Open, FileAccess.Read)) { - // Initialize a PDF converter to render pages as images. - using (var pdfConverter = new PdfConverter(pdfDocument)) + // Initialize the reader to detect all supported barcode types + using (BarCodeReader reader = new BarCodeReader(pdfStream, DecodeType.AllSupportedTypes)) { - // Enable barcode optimization to improve rendering quality of barcodes. - pdfConverter.RenderingOptions.BarcodeOptimization = true; - - // Iterate through each page in the PDF. - for (int pageNumber = 1; pageNumber <= pdfDocument.Pages.Count; pageNumber++) + // Iterate through all detected barcodes in the PDF + foreach (var result in reader.ReadBarCodes()) { - // Configure the converter to process a single page. - pdfConverter.StartPage = pageNumber; - pdfConverter.EndPage = pageNumber; - pdfConverter.DoConvert(); - - // Render the current page to an in‑memory image stream. - using (var pageImageStream = new MemoryStream()) - { - pdfConverter.GetNextImage(pageImageStream); - pageImageStream.Position = 0; // Reset stream position for reading. - - // Create a BarCodeReader to scan the image for any supported barcode types. - using (var reader = new BarCodeReader(pageImageStream, DecodeType.AllSupportedTypes)) - { - // Optional: improve detection of low‑quality barcodes. - reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast; - - bool anyFound = false; - - // Enumerate all detected barcodes on the page. - foreach (var result in reader.ReadBarCodes()) - { - anyFound = true; - Console.WriteLine($"Page {pageNumber}: Type = {result.CodeTypeName}, Text = {result.CodeText}"); - var bounds = result.Region.Rectangle; - Console.WriteLine($" Region: X={bounds.X}, Y={bounds.Y}, Width={bounds.Width}, Height={bounds.Height}"); - } - - // Inform the user if no barcodes were detected on the current page. - if (!anyFound) - { - Console.WriteLine($"Page {pageNumber}: No barcodes detected."); - } - } - } + // Output the barcode type and decoded text + Console.WriteLine($"Barcode Type: {result.CodeTypeName}"); + Console.WriteLine($"Barcode Text: {result.CodeText}"); + Console.WriteLine(); } } } diff --git a/barcode-reading-properties/use-custom-region-of-interest-to-limit-barcode-detection-to-specific-area-of-image.cs b/barcode-reading-properties/use-custom-region-of-interest-to-limit-barcode-detection-to-specific-area-of-image.cs index d3289c9..e97b12d 100644 --- a/barcode-reading-properties/use-custom-region-of-interest-to-limit-barcode-detection-to-specific-area-of-image.cs +++ b/barcode-reading-properties/use-custom-region-of-interest-to-limit-barcode-detection-to-specific-area-of-image.cs @@ -1,7 +1,8 @@ // Title: Barcode detection with custom region of interest // Description: Demonstrates limiting barcode recognition to a specific area of an image using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode image processing and barcode recognition category. It shows how to use BarCodeReader with a region of interest to improve detection performance and accuracy. Developers often need to restrict scanning to a portion of an image when multiple barcodes are present or when background noise is high. Key classes include BarCodeReader, DecodeType, and Rectangle. // Prompt: Use custom region of interest to limit barcode detection to a specific area of an image. -// Tags: barcode, region of interest, detection, aspose.barcode, csharp +// Tags: barcode, region of interest, detection, code128, aspose.barcode, image processing using System; using System.IO; @@ -12,56 +13,61 @@ using Aspose.Drawing.Imaging; /// -/// Example program that generates a barcode (if needed) and reads it using a custom region of interest. +/// Example program that generates a barcode image (if missing) and then +/// detects the barcode using a custom region of interest to limit the scanning area. /// class Program { /// - /// Entry point. Generates a sample barcode image if missing, then reads barcodes within the top‑left quarter of the image. + /// Entry point of the application. /// static void Main() { - // Path for the sample barcode image - string imagePath = "sample_barcode.png"; + // Path to the sample barcode image. + string imagePath = "barcode.png"; - // Generate a barcode image if it does not exist + // Generate a barcode image if it does not already exist. if (!File.Exists(imagePath)) { using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Set a simple black bar color + // Optional: set barcode foreground and background colors. generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; - // Save as PNG + generator.Parameters.BackColor = Aspose.Drawing.Color.White; + + // Save the generated barcode as a PNG file. generator.Save(imagePath, BarCodeImageFormat.Png); - Console.WriteLine($"Barcode image generated: {imagePath}"); + Console.WriteLine($"Generated barcode image at: {Path.GetFullPath(imagePath)}"); } } - // Verify the image file exists before attempting recognition - if (!File.Exists(imagePath)) - { - Console.WriteLine($"Error: Image file '{imagePath}' not found."); - return; - } - - // Load the image and define a custom region of interest (top‑left quarter) + // Load the image into a Bitmap object for processing. using (var bitmap = new Bitmap(imagePath)) { - // Define a rectangle covering the top‑left quarter of the image - var roi = new Rectangle(0, 0, bitmap.Width / 2, bitmap.Height / 2); + // Define a custom region of interest (top‑left quarter of the image). + int roiWidth = bitmap.Width / 2; + int roiHeight = bitmap.Height / 2; + var region = new Rectangle(0, 0, roiWidth, roiHeight); - // Create a reader and set the image with the region of interest + // Initialize the barcode reader. using (var reader = new BarCodeReader()) { - reader.SetBarCodeImage(bitmap, roi); + // Restrict decoding to the Code128 symbology. + reader.BarCodeReadType = DecodeType.Code128; + + // Assign the bitmap and the region of interest to the reader. + reader.SetBarCodeImage(bitmap, new Rectangle[] { region }); - // Read barcodes within the specified region + // Perform barcode recognition within the specified region. foreach (var result in reader.ReadBarCodes()) { Console.WriteLine($"Detected Type: {result.CodeTypeName}"); Console.WriteLine($"Detected Text: {result.CodeText}"); - var bounds = result.Region.Rectangle; - Console.WriteLine($"Region - X:{bounds.X}, Y:{bounds.Y}, Width:{bounds.Width}, Height:{bounds.Height}"); + + // Output the bounds of the region where the barcode was found. + var rect = result.Region.Rectangle; + Console.WriteLine($"Region - X:{rect.X}, Y:{rect.Y}, Width:{rect.Width}, Height:{rect.Height}"); + Console.WriteLine($"Angle: {result.Region.Angle}"); } } } diff --git a/barcode-reading-properties/use-parallel-processing-to-read-barcodes-from-multiple-images-concurrently-and-aggregate-results.cs b/barcode-reading-properties/use-parallel-processing-to-read-barcodes-from-multiple-images-concurrently-and-aggregate-results.cs index e2a2e6f..8d2fc31 100644 --- a/barcode-reading-properties/use-parallel-processing-to-read-barcodes-from-multiple-images-concurrently-and-aggregate-results.cs +++ b/barcode-reading-properties/use-parallel-processing-to-read-barcodes-from-multiple-images-concurrently-and-aggregate-results.cs @@ -1,118 +1,102 @@ -// Title: Parallel Barcode Reading and Aggregation -// Description: Demonstrates generating multiple barcode images, reading them concurrently using parallel processing, and aggregating the recognition results. +// Title: Parallel barcode reading from multiple images +// Description: Demonstrates generating several barcode images, then reading them concurrently using Aspose.BarCode's parallel processing capabilities. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing how to use BarCodeReader with ProcessorSettings for multi‑core execution. It illustrates typical use cases such as batch processing of scanned documents, inventory scans, or bulk image analysis where developers need to decode many barcodes efficiently. // Prompt: Use parallel processing to read barcodes from multiple images concurrently and aggregate results. -// Tags: barcode, parallel, aggregation, code128, aspose.barcode +// Tags: barcode symbology, parallel processing, batch recognition, aspnet, aspose.barcode, csharp using System; -using System.Collections.Concurrent; -using System.Collections.Generic; using System.IO; +using System.Collections.Concurrent; using System.Threading.Tasks; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; /// -/// Sample program that creates several Code128 barcode images, -/// reads them in parallel, and aggregates the recognition results. +/// Demonstrates generating barcode images, reading them in parallel, and aggregating the results. /// class Program { /// - /// Entry point of the application. - /// Generates barcode images, processes them concurrently, - /// and displays aggregated results. + /// Entry point of the example. Generates sample barcodes, processes them concurrently, + /// and outputs aggregated recognition results. /// static void Main() { - // -------------------------------------------------------------------- - // Prepare a temporary directory for sample barcode images. - // -------------------------------------------------------------------- - string tempDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodesSample"); - if (!Directory.Exists(tempDir)) + // Prepare a temporary folder for sample barcode images + string folderPath = Path.Combine(Path.GetTempPath(), "AsposeBarcodesSample"); + if (!Directory.Exists(folderPath)) { - Directory.CreateDirectory(tempDir); + Directory.CreateDirectory(folderPath); } - // -------------------------------------------------------------------- - // Define sample texts to encode into barcodes. - // -------------------------------------------------------------------- - string[] sampleTexts = new string[] { "ABC123", "XYZ789", "1234567890", "HELLO", "WORLD" }; - List imagePaths = new List(); + // Define sample barcodes to generate (file name, symbology, encoded text) + var samples = new (string FileName, BaseEncodeType EncodeType, string CodeText)[] + { + ("code128.png", EncodeTypes.Code128, "ABC123456"), + ("qr.png", EncodeTypes.QR, "https://example.com"), + ("ean13.png", EncodeTypes.EAN13, "5901234123457"), + ("datamatrix.png", EncodeTypes.DataMatrix, "DataMatrixSample"), + ("pdf417.png", EncodeTypes.Pdf417, "PDF417 Sample Text") + }; - // -------------------------------------------------------------------- - // Generate barcode images (Code128) and collect their file paths. - // -------------------------------------------------------------------- - for (int i = 0; i < sampleTexts.Length; i++) + // Generate barcode images and save them to the temporary folder + foreach (var sample in samples) { - string filePath = Path.Combine(tempDir, $"barcode{i}.png"); - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, sampleTexts[i])) + string filePath = Path.Combine(folderPath, sample.FileName); + using (var generator = new BarcodeGenerator(sample.EncodeType, sample.CodeText)) { + // Optional: customize image size, colors, etc., here generator.Save(filePath); } - imagePaths.Add(filePath); } - // -------------------------------------------------------------------- - // Thread‑safe collection to aggregate recognition results. - // -------------------------------------------------------------------- + // Retrieve all generated PNG files + string[] imageFiles = Directory.GetFiles(folderPath, "*.png"); + if (imageFiles.Length == 0) + { + Console.WriteLine("No barcode images found."); + return; + } + + // Configure the barcode reader to utilize all available CPU cores + BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Environment.ProcessorCount; + + // Thread‑safe collection for storing aggregated recognition results var aggregatedResults = new ConcurrentBag(); - // -------------------------------------------------------------------- - // Read barcodes from all images concurrently using Parallel.ForEach. - // -------------------------------------------------------------------- - Parallel.ForEach(imagePaths, filePath => + // Parallel processing: read barcodes from each image concurrently + Parallel.ForEach(imageFiles, file => { - if (!File.Exists(filePath)) - { - Console.WriteLine($"Warning: File not found - {filePath}"); - return; - } - - using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes)) + using (var reader = new BarCodeReader(file, DecodeType.AllSupportedTypes)) { foreach (var result in reader.ReadBarCodes()) { - string line = $"File: {Path.GetFileName(filePath)}, Type: {result.CodeTypeName}, Text: {result.CodeText}"; - aggregatedResults.Add(line); + string entry = $"{Path.GetFileName(file)} | Type: {result.CodeTypeName} | Text: {result.CodeText}"; + aggregatedResults.Add(entry); } } }); - // -------------------------------------------------------------------- - // Output aggregated results to the console. - // -------------------------------------------------------------------- - Console.WriteLine("Aggregated Barcode Recognition Results:"); + // Output the aggregated results to the console + Console.WriteLine("Aggregated barcode recognition results:"); foreach (var line in aggregatedResults) { Console.WriteLine(line); } - // -------------------------------------------------------------------- - // Clean up generated files (optional). - // -------------------------------------------------------------------- - foreach (var path in imagePaths) + // Clean up temporary files (optional) + try { - try - { - File.Delete(path); - } - catch + foreach (var file in imageFiles) { - // Ignore any deletion errors. + File.Delete(file); } - } - - // -------------------------------------------------------------------- - // Remove temporary directory if it is empty. - // -------------------------------------------------------------------- - try - { - Directory.Delete(tempDir); + Directory.Delete(folderPath); } catch { - // Ignore if directory not empty or deletion fails. + // Ignore any cleanup errors } } } \ No newline at end of file