diff --git a/mailmark-four-state-barcode/adjust-barcode-module-size-to-produce-compact-mailmark-barcode-suitable-for-small-labels.cs b/mailmark-four-state-barcode/adjust-barcode-module-size-to-produce-compact-mailmark-barcode-suitable-for-small-labels.cs index b45abf1..3896b79 100644 --- a/mailmark-four-state-barcode/adjust-barcode-module-size-to-produce-compact-mailmark-barcode-suitable-for-small-labels.cs +++ b/mailmark-four-state-barcode/adjust-barcode-module-size-to-produce-compact-mailmark-barcode-suitable-for-small-labels.cs @@ -1,68 +1,49 @@ -// Title: Generate a compact Mailmark barcode for small labels -// Description: Demonstrates how to adjust the module size and padding of a Mailmark barcode to create a compact image suitable for small label printing. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode symbologies such as Mailmark. It showcases the use of ComplexBarcodeGenerator, MailmarkCodetext, and barcode parameter settings like XDimension, AutoSizeMode, and padding. Developers often need to create high‑density barcodes for limited space applications, and this snippet provides a concise reference for those scenarios. +// Title: Generate a compact Mailmark barcode with reduced module size +// Description: Demonstrates how to create a Mailmark barcode, adjust its X‑dimension for a smaller module size, and remove padding to fit small labels. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as Mailmark. It showcases the use of ComplexBarcodeGenerator, MailmarkCodetext, and barcode parameter settings (XDimension, Padding) to customize output. Developers often need to produce compact barcodes for limited‑space applications like product labels, shipping tags, or inventory stickers. // Prompt: Adjust barcode module size to produce a compact Mailmark barcode suitable for small labels. -// Tags: mailmark, barcode, module size, compact, small labels, generation, aspose.barcode +// Tags: mailmark, barcode, generation, png, complexbarcodegenerator, mailmarkcodetext, xdimension, padding using System; -using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; -using Aspose.BarCode.BarCodeRecognition; -using Aspose.Drawing; /// -/// Program demonstrating compact Mailmark barcode generation. +/// Demonstrates generating a Mailmark barcode with a reduced module size for compact label printing. /// class Program { /// - /// Entry point. Generates a Mailmark barcode with reduced module size and padding, then saves it as PNG. + /// Entry point. Creates Mailmark codetext, configures barcode parameters, and saves the image. /// static void Main() { - // Prepare Mailmark codetext with required fields + // Initialize Mailmark codetext with required values. var mailmark = new MailmarkCodetext(); - mailmark.Format = 4; // unspecified/default format for compact barcode - mailmark.VersionID = 1; - mailmark.Class = "0"; - mailmark.SupplychainID = 384224; - mailmark.ItemID = 16563762; - mailmark.DestinationPostCodePlusDPS = "EF61AH8T "; - - // Create ComplexBarcodeGenerator for Mailmark + mailmark.Format = 4; // 4‑state Mailmark + mailmark.VersionID = 1; // version + mailmark.Class = "0"; // class as string + mailmark.SupplychainID = 384224; // supply chain identifier + mailmark.ItemID = 16563762; // item identifier + mailmark.DestinationPostCodePlusDPS = "EF61AH8T "; // trailing space required + + // Create a generator for the complex Mailmark barcode. using (var generator = new ComplexBarcodeGenerator(mailmark)) { - // Use interpolation auto-size mode so that XDimension controls overall size - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - - // Set a small module (dot) size for compactness - generator.Parameters.Barcode.XDimension.Point = 0.5f; // 0.5 point per module - - // Reduce padding to keep the barcode tight on small labels - generator.Parameters.Barcode.Padding.Left.Point = 1f; - generator.Parameters.Barcode.Padding.Top.Point = 1f; - generator.Parameters.Barcode.Padding.Right.Point = 1f; - generator.Parameters.Barcode.Padding.Bottom.Point = 1f; + // Reduce module size for a compact barcode suitable for small labels. + generator.Parameters.Barcode.XDimension.Point = 0.5f; // small module width - // Optional: set foreground and background colors - generator.Parameters.Barcode.BarColor = Color.Black; - generator.Parameters.BackColor = Color.White; + // Minimize padding to keep the barcode tight. + generator.Parameters.Barcode.Padding.Left.Point = 0f; + generator.Parameters.Barcode.Padding.Top.Point = 0f; + generator.Parameters.Barcode.Padding.Right.Point = 0f; + generator.Parameters.Barcode.Padding.Bottom.Point = 0f; - // Define output path - string outputPath = "mailmark_compact.png"; - - // Ensure the directory exists - string directory = Path.GetDirectoryName(Path.GetFullPath(outputPath)); - if (!Directory.Exists(directory)) - { - Directory.CreateDirectory(directory); - } - - // Save the barcode image - generator.Save(outputPath, BarCodeImageFormat.Png); - Console.WriteLine($"Compact Mailmark barcode saved to: {outputPath}"); + // Save the generated barcode as a PNG image. + generator.Save("mailmark.png"); } + + Console.WriteLine("Mailmark barcode generated: mailmark.png"); } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/batch-generate-mailmark-barcodes-from-customer-records-saving-each-as-separate-bmp-files.cs b/mailmark-four-state-barcode/batch-generate-mailmark-barcodes-from-customer-records-saving-each-as-separate-bmp-files.cs index 35f2630..0d56791 100644 --- a/mailmark-four-state-barcode/batch-generate-mailmark-barcodes-from-customer-records-saving-each-as-separate-bmp-files.cs +++ b/mailmark-four-state-barcode/batch-generate-mailmark-barcodes-from-customer-records-saving-each-as-separate-bmp-files.cs @@ -1,8 +1,8 @@ -// Title: Batch Mailmark Barcode Generation to BMP Files -// Description: Demonstrates generating Mailmark barcodes for a list of customer records and saving each barcode as an individual BMP image. -// Category-Description: This example belongs to the Aspose.BarCode generation category, focusing on complex barcode types such as Mailmark. It showcases the use of Aspose.BarCode.Generation.ComplexBarcodeGenerator and Aspose.BarCode.ComplexBarcode.MailmarkCodetext to create barcodes programmatically. Developers often need to batch‑process records, embed specific data fields, and export barcodes to image formats for printing or archival purposes. +// Title: Batch generation of Mailmark barcodes to BMP files +// Description: Demonstrates how to create Mailmark barcodes for multiple customer records and save each barcode as an individual BMP image. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as Mailmark. It showcases the use of ComplexBarcodeGenerator and MailmarkCodetext classes to produce high‑volume barcode images, a common requirement for logistics, mailing, and inventory systems. Developers often need to generate barcodes in bulk, customize codetext, and export them to various image formats. // Prompt: Batch generate Mailmark barcodes from customer records, saving each as separate BMP files. -// Tags: mailmark, barcode, generation, bmp, aspose.barcode, complexbarcode +// Tags: mailmark, barcode generation, bmp, batch processing, aspose.barcode, complexbarcode, codetext using System; using System.Collections.Generic; @@ -12,56 +12,70 @@ using Aspose.BarCode.ComplexBarcode; /// -/// Generates Mailmark barcodes for a collection of customer records and saves each barcode as a BMP file. +/// Example program that generates Mailmark barcodes for a list of customer records +/// and saves each barcode as a separate BMP file. /// class Program { /// - /// Entry point of the application. Creates an output folder, iterates over sample records, - /// builds Mailmark codetext, generates the barcode, and writes it to disk. + /// Entry point of the application. Iterates over sample customer data, + /// builds Mailmark codetext, generates the barcode image, and writes it to disk. /// static void Main() { - // Define the output directory and ensure it exists - string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "MailmarkBarcodes"); - if (!Directory.Exists(outputDir)) + // Sample customer records – in a real scenario these would come from a database or file. + var customers = new List { - Directory.CreateDirectory(outputDir); - } + new CustomerRecord { Class = "0", SupplychainID = 384224, ItemID = 16563762 }, + new CustomerRecord { Class = "1", SupplychainID = 384224, ItemID = 16563763 }, + new CustomerRecord { Class = "2", SupplychainID = 384224, ItemID = 16563764 }, + new CustomerRecord { Class = "3", SupplychainID = 384224, ItemID = 16563765 }, + new CustomerRecord { Class = "4", SupplychainID = 384224, ItemID = 16563766 } + }; - // Sample customer records (limited to 5 for safe execution) - var records = new List<(int ItemID, string DestinationPostCodePlusDPS)> + // Determine output folder for generated BMP files. + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "MailmarkBarcodes"); + if (!Directory.Exists(outputFolder)) { - (16563762, "EF61AH8T "), - (16563763, "EF61AH8T "), - (16563764, "EF61AH8T "), - (16563765, "EF61AH8T "), - (16563766, "EF61AH8T ") - }; + // Create the folder if it does not already exist. + Directory.CreateDirectory(outputFolder); + } int index = 1; - foreach (var record in records) + foreach (var record in customers) { - // Build the Mailmark codetext with required fields for each record + // Construct Mailmark codetext according to the specification. var mailmark = new MailmarkCodetext { - Format = 4, // 4‑state (unspecified/default) - VersionID = 1, - Class = "0", // Test/Null class - SupplychainID = 384224, + Format = 4, // 4‑state Mailmark. + VersionID = 1, // Version identifier. + Class = record.Class, // Class as string. + SupplychainID = record.SupplychainID, ItemID = record.ItemID, - DestinationPostCodePlusDPS = record.DestinationPostCodePlusDPS + DestinationPostCodePlusDPS = "EF61AH8T " // Trailing space is required. }; - // Generate the barcode and save it as a BMP image + // Generate the barcode image using ComplexBarcodeGenerator. using (var generator = new ComplexBarcodeGenerator(mailmark)) { - string filePath = Path.Combine(outputDir, $"Mailmark_{index}.bmp"); + // Build file name and path for the current barcode. + string filePath = Path.Combine(outputFolder, $"Mailmark_{index}.bmp"); + // Save the barcode as a BMP image. generator.Save(filePath, BarCodeImageFormat.Bmp); - Console.WriteLine($"Saved Mailmark barcode to: {filePath}"); + Console.WriteLine($"Saved Mailmark barcode #{index} to: {filePath}"); } index++; } + + Console.WriteLine("All Mailmark barcodes have been generated."); + } + + // Simple data holder for demonstration purposes. + private class CustomerRecord + { + public string Class { get; set; } + public int SupplychainID { get; set; } + public int ItemID { get; set; } } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/compare-performance-of-generating-mailmark-barcodes-as-png-versus-jpeg-by-measuring-file-size-and-generation-time.cs b/mailmark-four-state-barcode/compare-performance-of-generating-mailmark-barcodes-as-png-versus-jpeg-by-measuring-file-size-and-generation-time.cs index 8254efa..7524622 100644 --- a/mailmark-four-state-barcode/compare-performance-of-generating-mailmark-barcodes-as-png-versus-jpeg-by-measuring-file-size-and-generation-time.cs +++ b/mailmark-four-state-barcode/compare-performance-of-generating-mailmark-barcodes-as-png-versus-jpeg-by-measuring-file-size-and-generation-time.cs @@ -1,85 +1,105 @@ -// Title: Mailmark Barcode Generation Performance: PNG vs JPEG -// Description: Demonstrates measuring generation time and file size when creating Mailmark barcodes in PNG and JPEG formats. -// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of ComplexBarcodeGenerator to produce Mailmark symbology. It illustrates typical tasks such as configuring Mailmark codetext, rendering barcodes to different image formats, and profiling performance—common needs for developers integrating barcode creation into high‑throughput or size‑sensitive applications. The snippet highlights key API classes like MailmarkCodetext, ComplexBarcodeGenerator, and BarCodeImageFormat, serving as a reference for performance‑oriented barcode generation scenarios. -/// Prompt: Compare performance of generating Mailmark barcodes as PNG versus JPEG by measuring file size and generation time. -/// Tags: mailmark, barcode, performance, png, jpeg, generation, aspose.barcode, complexbarcodegenerator +// Title: Mailmark Barcode Generation: PNG vs JPEG Performance Comparison +// Description: Demonstrates generating Mailmark barcodes as PNG and JPEG images, measuring file size and generation time for each format. +// Category-Description: Shows how to use Aspose.BarCode's ComplexBarcodeGenerator to create Mailmark barcodes, covering image format selection, stream handling, and performance measurement. This example belongs to the barcode generation and image export category, where developers often need to compare output formats for size and speed. +// Prompt: Compare performance of generating Mailmark barcodes as PNG versus JPEG by measuring file size and generation time. +// Tags: mailmark, barcode, performance, png, jpeg, imageformat, complexbarcodegenerator, aspose.barcode using System; -using System.Diagnostics; using System.IO; -using Aspose.BarCode; -using Aspose.BarCode.Generation; +using System.Diagnostics; using Aspose.BarCode.ComplexBarcode; -using Aspose.Drawing.Imaging; +using Aspose.BarCode.Generation; /// -/// Generates Mailmark barcodes in PNG and JPEG formats and compares their generation time and file size. +/// Generates a series of Mailmark barcodes in PNG and JPEG formats, +/// then reports file size and generation time for each format. /// class Program { /// - /// Entry point of the example. Prepares Mailmark data, renders the barcode in two image formats, - /// and outputs average generation time and file size for each format. + /// Entry point of the example. Creates output directory, generates barcodes, + /// saves them as PNG and JPEG, and prints performance metrics. /// static void Main() { - // Prepare a valid Mailmark codetext with required fields. - var mailmark = new MailmarkCodetext - { - Format = 4, // 4‑state barcode - VersionID = 1, - Class = "0", - SupplychainID = 384224, - ItemID = 16563762, - DestinationPostCodePlusDPS = "EF61AH8T " - }; - - // Define the image formats to be tested: PNG and JPEG. - var formats = new[] + // Ensure the output directory exists + string outputDir = "MailmarkOutput"; + if (!Directory.Exists(outputDir)) { - BarCodeImageFormat.Png, - BarCodeImageFormat.Jpeg - }; + Directory.CreateDirectory(outputDir); + } - const int iterations = 5; // Number of repetitions for averaging results. + // Number of barcode samples to generate + int sampleCount = 5; - // Iterate over each format and measure performance. - foreach (var format in formats) + for (int i = 0; i < sampleCount; i++) { - long totalBytes = 0; // Accumulator for total file size. - long totalTicks = 0; // Accumulator for total elapsed ticks. + // Prepare Mailmark codetext with unique ItemID for each sample + var mailmark = new MailmarkCodetext + { + Format = 4, // 4‑state Mailmark + VersionID = 1, + Class = "0", + SupplychainID = 384224, + ItemID = 16563762 + i, // vary ItemID to keep records unique + DestinationPostCodePlusDPS = "EF61AH8T " // trailing space is required + }; - // Run the generation multiple times to obtain average metrics. - for (int i = 0; i < iterations; i++) + // ---------- PNG generation ---------- + string pngPath = Path.Combine(outputDir, $"mailmark_{i}_png.png"); + long pngSize; + double pngMs; + + using (var generator = new ComplexBarcodeGenerator(mailmark)) + using (var pngStream = new MemoryStream()) { - // Create a generator for the Mailmark barcode. - using (var generator = new ComplexBarcodeGenerator(mailmark)) - { - // Use a memory stream to avoid disk I/O overhead. - using (var ms = new MemoryStream()) - { - // Start timing the Save operation. - var sw = Stopwatch.StartNew(); - generator.Save(ms, format); - sw.Stop(); + // Measure time to render PNG + var sw = Stopwatch.StartNew(); + generator.Save(pngStream, BarCodeImageFormat.Png); + sw.Stop(); + pngMs = sw.Elapsed.TotalMilliseconds; - // Accumulate elapsed time and resulting byte size. - totalTicks += sw.ElapsedTicks; - totalBytes += ms.Length; - } + // Write PNG stream to file + pngStream.Position = 0; + using (var file = new FileStream(pngPath, FileMode.Create, FileAccess.Write)) + { + pngStream.CopyTo(file); } } - // Compute average generation time in milliseconds. - double avgMs = (totalTicks * 1000.0) / Stopwatch.Frequency / iterations; - // Compute average file size in kilobytes. - double avgKb = (totalBytes / 1024.0) / iterations; + // Retrieve PNG file size + pngSize = new FileInfo(pngPath).Length; + + // ---------- JPEG generation ---------- + string jpegPath = Path.Combine(outputDir, $"mailmark_{i}_jpeg.jpg"); + long jpegSize; + double jpegMs; - // Friendly format name for output. - string formatName = format == BarCodeImageFormat.Png ? "PNG" : "JPEG"; + using (var generator = new ComplexBarcodeGenerator(mailmark)) + using (var jpegStream = new MemoryStream()) + { + // Measure time to render JPEG + var sw = Stopwatch.StartNew(); + generator.Save(jpegStream, BarCodeImageFormat.Jpeg); + sw.Stop(); + jpegMs = sw.Elapsed.TotalMilliseconds; - // Display the averaged results. - Console.WriteLine($"{formatName} - Average generation time: {avgMs:F2} ms, Average file size: {avgKb:F2} KB"); + // Write JPEG stream to file + jpegStream.Position = 0; + using (var file = new FileStream(jpegPath, FileMode.Create, FileAccess.Write)) + { + jpegStream.CopyTo(file); + } + } + + // Retrieve JPEG file size + jpegSize = new FileInfo(jpegPath).Length; + + // Output comparison results for the current record + Console.WriteLine($"Record {i}: PNG - {pngSize} bytes, {pngMs:F2} ms; JPEG - {jpegSize} bytes, {jpegMs:F2} ms"); } + + // Indicate that the performance comparison has finished + Console.WriteLine("Performance comparison completed."); } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/configure-barcodereader-for-multi-threaded-processing-to-accelerate-decoding-of-large-mailmark-image-batches.cs b/mailmark-four-state-barcode/configure-barcodereader-for-multi-threaded-processing-to-accelerate-decoding-of-large-mailmark-image-batches.cs index 1b48234..35d5b98 100644 --- a/mailmark-four-state-barcode/configure-barcodereader-for-multi-threaded-processing-to-accelerate-decoding-of-large-mailmark-image-batches.cs +++ b/mailmark-four-state-barcode/configure-barcodereader-for-multi-threaded-processing-to-accelerate-decoding-of-large-mailmark-image-batches.cs @@ -1,94 +1,94 @@ -// Title: Multi‑Threaded Mailmark Barcode Decoding Example -// Description: Demonstrates how to generate a batch of Mailmark barcode images and decode them concurrently using BarCodeReader to speed up processing of large image sets. -// Category-Description: This example belongs to the Aspose.BarCode barcode decoding category, focusing on high‑performance multi‑threaded reading of complex barcodes such as Mailmark. It showcases the use of BarCodeReader, QualitySettings, and ProcessorSettings classes to leverage all CPU cores, a common requirement for developers processing bulk barcode images in mail and logistics applications. +// Title: Multi‑threaded Mailmark Barcode Decoding with BarCodeReader +// Description: Generates sample Mailmark barcodes, saves them as PNG files, and decodes them using BarCodeReader configured to utilize all CPU cores for faster batch processing. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, demonstrating how to configure BarCodeReader for parallel processing. It showcases the use of ComplexBarcodeGenerator for creating Mailmark barcodes and BarCodeReader with ProcessorSettings to leverage multi‑core CPUs. Developers often need to decode large sets of images efficiently, and this pattern provides a scalable solution. // Prompt: Configure BarCodeReader for multi‑threaded processing to accelerate decoding of large Mailmark image batches. -// Tags: mailmark, barcode, decoding, multithreading, barcodereader, complexbarcode, generation, qualitysettings, processorsettings +// Tags: mailmark, barcode, decoding, multithreading, aspose.barcode, complexbarcodegenerator, barcodereader, processorsettings using System; -using System.Collections.Generic; using System.IO; -using System.Threading.Tasks; -using Aspose.BarCode.ComplexBarcode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; -using Aspose.BarCode; +using Aspose.BarCode.ComplexBarcode; /// -/// Entry point for the multi‑threaded Mailmark barcode decoding example. +/// Demonstrates generating Mailmark barcodes and decoding them in parallel using Aspose.BarCode. /// class Program { /// - /// Generates sample Mailmark barcode images and decodes them in parallel using BarCodeReader. + /// Entry point that creates sample Mailmark images, configures the reader for multi‑core processing, + /// and outputs decoded results to the console. /// static void Main() { - // Define the output directory for generated sample images - string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "MailmarkSamples"); - if (!Directory.Exists(outputDir)) + // Define folder for sample Mailmark images + string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "MailmarkSamples"); + if (!Directory.Exists(folderPath)) { - // Create the directory if it does not exist - Directory.CreateDirectory(outputDir); + Directory.CreateDirectory(folderPath); } - // Generate a small batch of Mailmark barcode images (5 samples) - List imagePaths = new List(); - for (int i = 0; i < 5; i++) + // Generate a few sample Mailmark barcodes (self‑contained example) + const int sampleCount = 5; + for (int i = 0; i < sampleCount; i++) { - // Prepare Mailmark codetext with varying ItemID + // Create a valid MailmarkCodetext instance with unique ItemID var mailmark = new MailmarkCodetext { - Format = 4, // Premium (default) + Format = 4, // 4‑state Mailmark VersionID = 1, - Class = "0", // Null/Test + Class = "0", SupplychainID = 384224, - ItemID = 16563762 + i, // Vary ItemID for each sample - DestinationPostCodePlusDPS = "EF61AH8T " // Known valid value + ItemID = 16563762 + i, // vary ItemID to make each barcode unique + DestinationPostCodePlusDPS = "EF61AH8T " // trailing space is required }; - // Create a ComplexBarcodeGenerator using the Mailmark codetext + // Generate the barcode image and save to file + string filePath = Path.Combine(folderPath, $"Mailmark_{i + 1}.png"); using (var generator = new ComplexBarcodeGenerator(mailmark)) { - // Save the generated barcode image as PNG - string filePath = Path.Combine(outputDir, $"Mailmark_{i + 1}.png"); - generator.Save(filePath, BarCodeImageFormat.Png); - imagePaths.Add(filePath); + using (var stream = new MemoryStream()) + { + generator.Save(stream, BarCodeImageFormat.Png); + File.WriteAllBytes(filePath, stream.ToArray()); + } } } - // Configure BarCodeReader to use all available processor cores for each call + // Configure BarCodeReader to use all available processor cores BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Environment.ProcessorCount; - // Set up parallel processing options (max degree equals processor count) - var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }; - - // Process the batch of images in parallel - Parallel.ForEach(imagePaths, parallelOptions, imagePath => + // Process the generated images using multi‑threaded decoding + string[] imageFiles = Directory.GetFiles(folderPath, "*.png"); + foreach (string imagePath in imageFiles) { if (!File.Exists(imagePath)) { Console.WriteLine($"File not found: {imagePath}"); - return; + continue; } - // Initialize BarCodeReader for Mailmark decode type + // Create a reader for Mailmark symbology using (var reader = new BarCodeReader(imagePath, DecodeType.Mailmark)) { - // Apply high‑performance quality settings for faster decoding - reader.QualitySettings = QualitySettings.HighPerformance; + // Optional: allow decoding of slightly damaged barcodes + reader.QualitySettings.AllowIncorrectBarcodes = true; - // Read all barcodes found in the image - foreach (var result in reader.ReadBarCodes()) + try { - Console.WriteLine($"File: {Path.GetFileName(imagePath)}"); - Console.WriteLine($" Type: {result.CodeTypeName}"); - Console.WriteLine($" CodeText: {result.CodeText}"); - Console.WriteLine($" Confidence: {result.Confidence}"); - Console.WriteLine($" ReadingQuality: {result.ReadingQuality}"); - var bounds = result.Region.Rectangle; - Console.WriteLine($" Region: X={bounds.X}, Y={bounds.Y}, Width={bounds.Width}, Height={bounds.Height}"); + // Read and output each decoded barcode + foreach (var result in reader.ReadBarCodes()) + { + Console.WriteLine($"File: {Path.GetFileName(imagePath)} | Type: {result.CodeTypeName} | Text: {result.CodeText}"); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error reading '{imagePath}': {ex.Message}"); } } - }); + } + + Console.WriteLine("Processing completed."); } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/configure-barcodereader-to-ignore-quiet-zones-while-decoding-mailmark-barcodes-in-densely-packed-images.cs b/mailmark-four-state-barcode/configure-barcodereader-to-ignore-quiet-zones-while-decoding-mailmark-barcodes-in-densely-packed-images.cs index 223f305..d33f49f 100644 --- a/mailmark-four-state-barcode/configure-barcodereader-to-ignore-quiet-zones-while-decoding-mailmark-barcodes-in-densely-packed-images.cs +++ b/mailmark-four-state-barcode/configure-barcodereader-to-ignore-quiet-zones-while-decoding-mailmark-barcodes-in-densely-packed-images.cs @@ -1,71 +1,57 @@ -// Title: Ignore Quiet Zones When Decoding Mailmark Barcodes with BarCodeReader -// Description: Demonstrates configuring BarCodeReader to ignore quiet zones while decoding Mailmark barcodes in densely packed images. -// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on Mailmark symbology and quality settings. It showcases the use of BarCodeReader, QualitySettings, and ComplexBarcodeGenerator to generate and read Mailmark barcodes, a common requirement for postal automation and bulk mail processing. +// Title: Decode Mailmark Barcodes While Ignoring Quiet Zones in Dense Images +// Description: Demonstrates how to configure Aspose.BarCode's BarCodeReader to decode Mailmark (4‑state) barcodes in a densely packed image, using settings that improve detection when quiet zones are ignored. +// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on Mailmark symbology and quality settings. It showcases the use of BarCodeReader, DecodeType.Mailmark, and QualitySettings (DeconvolutionMode, AllowIncorrectBarcodes) to handle challenging image conditions. Developers often need to read Mailmark codes from high‑density documents where quiet zones are minimal or absent, and this snippet provides a practical pattern for such scenarios. // Prompt: Configure BarCodeReader to ignore quiet zones while decoding Mailmark barcodes in densely packed images. -// Tags: mailmark, barcode, reader, quiet zone, decode, aspose.barcode, qualitysettings, complexbarcode +// Tags: mailmark, barcode, decoding, quiet zones, deconvolution, allowincorrectbarcodes, c#, aspose.barcode using System; using System.IO; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.BarCode.ComplexBarcode; -using Aspose.Drawing.Imaging; /// -/// Example program that generates a Mailmark barcode, then reads it while configuring the reader -/// to ignore quiet zones (via quality settings) for better detection in densely packed images. +/// Provides an example of decoding Mailmark barcodes while ignoring quiet zones. /// class Program { /// - /// Entry point of the example. Generates a Mailmark barcode, configures the reader, - /// and outputs detection results to the console. + /// Entry point that generates a Mailmark barcode, then reads it using BarCodeReader + /// with quality settings to improve detection in dense images. /// static void Main() { - // ------------------------------------------------------------ - // 1. Prepare Mailmark codetext data (format 4 = unspecified/default) - // ------------------------------------------------------------ + // Create a sample Mailmark barcode (4‑state) using ComplexBarcodeGenerator var mailmark = new MailmarkCodetext { - Format = 4, + Format = 4, // 4‑state Mailmark VersionID = 1, Class = "0", SupplychainID = 384224, ItemID = 16563762, - DestinationPostCodePlusDPS = "EF61AH8T " + DestinationPostCodePlusDPS = "EF61AH8T " // trailing space is required }; - // ------------------------------------------------------------ - // 2. Generate the Mailmark barcode image into a memory stream - // ------------------------------------------------------------ + // Generate the barcode image into a memory stream using (var generator = new ComplexBarcodeGenerator(mailmark)) - using (var ms = new MemoryStream()) + using (var imageStream = new MemoryStream()) { - generator.Save(ms, BarCodeImageFormat.Png); - ms.Position = 0; // Reset stream position for subsequent reading + generator.Save(imageStream, BarCodeImageFormat.Png); + imageStream.Position = 0; // Reset stream position for reading - // ------------------------------------------------------------ - // 3. Initialize BarCodeReader for Mailmark symbology - // ------------------------------------------------------------ - using (var reader = new BarCodeReader(ms, DecodeType.Mailmark)) + // Configure BarCodeReader for Mailmark decoding + // Note: Aspose.BarCode does not expose a property to ignore quiet zones. + // We improve detection in dense images by enabling fast deconvolution + // and allowing incorrect barcodes. + using (var reader = new BarCodeReader(imageStream, DecodeType.Mailmark)) { - // Quiet zone handling is internal; there is no public API to ignore them. - // Adjust quality settings to improve detection in densely packed images. - reader.QualitySettings = QualitySettings.HighQuality; reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast; reader.QualitySettings.AllowIncorrectBarcodes = true; - // ------------------------------------------------------------ - // 4. Read all barcodes found in the image and display details - // ------------------------------------------------------------ + // Read and output all detected Mailmark codes foreach (var result in reader.ReadBarCodes()) { - Console.WriteLine($"Detected Type: {result.CodeTypeName}"); - Console.WriteLine($"Code Text: {result.CodeText}"); - Console.WriteLine($"Reading Quality: {result.ReadingQuality}"); - var bounds = result.Region.Rectangle; - Console.WriteLine($"Region: X={bounds.X}, Y={bounds.Y}, Width={bounds.Width}, Height={bounds.Height}"); + Console.WriteLine($"Detected Mailmark CodeText: {result.CodeText}"); } } } diff --git a/mailmark-four-state-barcode/configure-complexbarcodegenerator-for-high-resolution-output-at-300-dpi-with-transparent-background.cs b/mailmark-four-state-barcode/configure-complexbarcodegenerator-for-high-resolution-output-at-300-dpi-with-transparent-background.cs index e5f8a4d..51900ea 100644 --- a/mailmark-four-state-barcode/configure-complexbarcodegenerator-for-high-resolution-output-at-300-dpi-with-transparent-background.cs +++ b/mailmark-four-state-barcode/configure-complexbarcodegenerator-for-high-resolution-output-at-300-dpi-with-transparent-background.cs @@ -1,26 +1,28 @@ -// Title: Generate Swiss QR Bill barcode with high‑resolution transparent PNG -// Description: Demonstrates creating a Swiss QR Bill barcode using Aspose.BarCode, configuring 300 DPI resolution and a transparent background, then saving as PNG. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as Swiss QR Bill. It showcases the use of ComplexBarcodeGenerator, SwissQRCodetext, and generation parameters to control image resolution, colors, and output formats—common tasks for developers integrating payment QR codes into applications. +// Title: Generate High‑Resolution Swiss QR Complex Barcode with Transparent Background +// Description: Demonstrates creating a Swiss QR bill complex barcode, configuring the generator for 300 DPI resolution and a transparent background, and saving it as a PNG image. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator together with SwissQRCodetext to produce payment‑oriented QR codes. Developers often need high‑resolution, transparent images for printing invoices or embedding in UI designs, and this pattern illustrates the typical API workflow. // Prompt: Configure ComplexBarcodeGenerator for high‑resolution output at 300 DPI with transparent background. -// Tags: swissqr, barcode, high resolution, transparent background, png, aspose.barcode, complexbarcodegenerator +// Tags: swissqr, complexbarcode, generation, png, aspose.barcode.complexbarcode, aspose.barcode.generation, aspose.drawing using System; -using Aspose.BarCode; +using System.IO; using Aspose.BarCode.ComplexBarcode; using Aspose.BarCode.Generation; using Aspose.Drawing; /// -/// Demonstrates generating a Swiss QR Bill barcode with high resolution and transparent background. +/// Example program that generates a Swiss QR bill complex barcode with high resolution +/// and a transparent background, then saves it as a PNG file. /// class Program { /// - /// Entry point. Builds Swiss QR codetext, configures generator, and saves PNG image. + /// Entry point of the example. Builds the Swiss QR codetext, configures the generator, + /// and writes the resulting image to disk. /// static void Main() { - // Prepare SwissQR codetext with mandatory fields + // Prepare a Swiss QR codetext (complex barcode data) with creditor and payment details var swissQr = new SwissQRCodetext(); swissQr.Bill.Creditor.Name = "John Doe"; swissQr.Bill.Creditor.CountryCode = "CH"; @@ -28,20 +30,29 @@ static void Main() swissQr.Bill.Amount = 199.95m; swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0; - // Create ComplexBarcodeGenerator with the codetext + // Create a ComplexBarcodeGenerator using the prepared codetext using (var generator = new ComplexBarcodeGenerator(swissQr)) { - // Set high resolution (300 DPI) + // Configure the generator for high‑resolution output (300 DPI) generator.Parameters.Resolution = 300f; - // Set transparent background - generator.Parameters.BackColor = Color.Transparent; + // Set the background to be fully transparent + generator.Parameters.BackColor = Aspose.Drawing.Color.Transparent; - // Save the barcode image as PNG - generator.Save("SwissQR.png"); + // Define the output file path + string outputPath = "complex_highres.png"; + + // Ensure the target directory exists before saving + string directory = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(directory)) + { + Directory.CreateDirectory(directory); + } + + // Save the generated barcode as a PNG image + generator.Save(outputPath, BarCodeImageFormat.Png); } - // Inform the user that generation succeeded Console.WriteLine("Barcode generated successfully."); } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/create-function-accepting-raw-barcode-image-bytes-and-returning-populated-mailmarkcodetext-object.cs b/mailmark-four-state-barcode/create-function-accepting-raw-barcode-image-bytes-and-returning-populated-mailmarkcodetext-object.cs index 2df4198..341525a 100644 --- a/mailmark-four-state-barcode/create-function-accepting-raw-barcode-image-bytes-and-returning-populated-mailmarkcodetext-object.cs +++ b/mailmark-four-state-barcode/create-function-accepting-raw-barcode-image-bytes-and-returning-populated-mailmarkcodetext-object.cs @@ -1,93 +1,103 @@ -// Title: Decode Mailmark barcode from image bytes -// Description: Demonstrates how to read a Mailmark barcode from raw image bytes and extract its fields using Aspose.BarCode. -// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on complex barcode types such as Mailmark. It shows how to use BarCodeReader with DecodeType.Mailmark, MemoryStream for byte input, and ComplexCodetextReader to parse the codetext into a MailmarkCodetext object. Developers working with postal or logistics solutions often need to decode Mailmark symbols from scanned images or byte streams. +// Title: Mailmark barcode generation and decoding example +// Description: Demonstrates creating a Mailmark barcode image from a MailmarkCodetext object, then decoding it back from raw image bytes. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on complex barcode symbologies such as Mailmark. It showcases the use of ComplexBarcodeGenerator for encoding and BarCodeReader with ComplexCodetextReader for decoding. Developers working with postal or logistics solutions often need to generate and read Mailmark barcodes to embed routing and tracking information. // Prompt: Create a function accepting raw barcode image bytes and returning a populated MailmarkCodetext object. -// Tags: mailmark, barcode, decoding, image-bytes, aspnet, aspnet-barcode, complexbarcode, codetext +// Tags: mailmark, barcode, generation, recognition, complexbarcode, aspnet, csharp using System; using System.IO; -using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.BarCode.ComplexBarcode; -namespace MailmarkDecoder +/// +/// Demonstrates how to generate a Mailmark barcode, convert it to a byte array, +/// and decode it back into a object using Aspose.BarCode. +/// +class Program { /// - /// Sample console application that decodes a Mailmark barcode from an image file. + /// Entry point of the example. Generates a Mailmark barcode, decodes it, + /// and writes the decoded fields to the console. /// - class Program + static void Main() { - /// - /// Entry point of the application. Loads a sample image, decodes the Mailmark barcode, - /// and prints the extracted fields to the console. - /// - static void Main() + // -------------------------------------------------------------------- + // 1. Create a sample MailmarkCodetext instance with required fields. + // -------------------------------------------------------------------- + var mailmark = new MailmarkCodetext { - // Path to the sample image containing a Mailmark barcode. - string imagePath = "mailmark.png"; + Format = 4, // 4‑state Mailmark + VersionID = 1, + Class = "0", + SupplychainID = 384224, + ItemID = 16563762, + DestinationPostCodePlusDPS = "EF61AH8T " // trailing space required + }; - // Verify that the image file exists before attempting to read it. - if (!File.Exists(imagePath)) - { - Console.WriteLine($"Image file not found: {imagePath}"); - return; - } - - // Read the entire image file into a byte array. - byte[] imageBytes = File.ReadAllBytes(imagePath); - - // Decode the Mailmark barcode from the raw image bytes. - MailmarkCodetext mailmark = DecodeMailmarkFromBytes(imageBytes); - - // If decoding failed, inform the user and exit. - if (mailmark == null) + // --------------------------------------------------------------- + // 2. Generate a PNG image of the Mailmark barcode into a byte array. + // --------------------------------------------------------------- + byte[] imageBytes; + using (var ms = new MemoryStream()) + { + // ComplexBarcodeGenerator encodes the MailmarkCodetext into a barcode. + using (var generator = new ComplexBarcodeGenerator(mailmark)) { - Console.WriteLine("No Mailmark barcode could be decoded."); - return; + generator.Save(ms, BarCodeImageFormat.Png); + imageBytes = ms.ToArray(); // Capture the image data. } - - // Output the decoded Mailmark fields to the console. - Console.WriteLine($"Format: {mailmark.Format}"); - Console.WriteLine($"VersionID: {mailmark.VersionID}"); - Console.WriteLine($"Class: {mailmark.Class}"); - Console.WriteLine($"SupplychainID: {mailmark.SupplychainID}"); - Console.WriteLine($"ItemID: {mailmark.ItemID}"); - Console.WriteLine($"DestinationPostCodePlusDPS: {mailmark.DestinationPostCodePlusDPS}"); } - /// - /// Decodes a Mailmark barcode from raw image bytes. - /// - /// Byte array containing the barcode image. - /// Populated object, or null if decoding fails. - static MailmarkCodetext DecodeMailmarkFromBytes(byte[] imageBytes) + // --------------------------------------------------------------- + // 3. Decode the barcode image bytes back to a MailmarkCodetext object. + // --------------------------------------------------------------- + var decoded = DecodeMailmarkFromBytes(imageBytes); + if (decoded != null) + { + // Output each decoded property for verification. + Console.WriteLine($"Format: {decoded.Format}"); + Console.WriteLine($"VersionID: {decoded.VersionID}"); + Console.WriteLine($"Class: {decoded.Class}"); + Console.WriteLine($"SupplychainID: {decoded.SupplychainID}"); + Console.WriteLine($"ItemID: {decoded.ItemID}"); + Console.WriteLine($"DestinationPostCodePlusDPS: '{decoded.DestinationPostCodePlusDPS}'"); + } + else { - // Validate input. - if (imageBytes == null || imageBytes.Length == 0) - throw new ArgumentException("Image bytes cannot be null or empty.", nameof(imageBytes)); + Console.WriteLine("Mailmark barcode could not be decoded."); + } + } - // Load the image bytes into a memory stream for the reader. - using (MemoryStream ms = new MemoryStream(imageBytes)) + /// + /// Decodes a Mailmark barcode from raw image bytes. + /// + /// Raw image data containing a Mailmark barcode. + /// Populated if decoding succeeds; otherwise null. + static MailmarkCodetext DecodeMailmarkFromBytes(byte[] imageBytes) + { + // Validate input. + if (imageBytes == null || imageBytes.Length == 0) + throw new ArgumentException("Image bytes must be a non‑empty array.", nameof(imageBytes)); + + // Load the image bytes into a memory stream for the reader. + using (var ms = new MemoryStream(imageBytes)) + { + // BarCodeReader scans the stream for any supported barcode types. + using (var reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes)) { - // Initialize the barcode reader for the Mailmark symbology. - using (BarCodeReader reader = new BarCodeReader(ms, DecodeType.Mailmark)) + // Iterate through all detected barcodes. + foreach (var result in reader.ReadBarCodes()) { - // Read all detected barcodes from the stream. - BarCodeResult[] results = reader.ReadBarCodes(); - - // If no barcodes were found, return null. - if (results == null || results.Length == 0) - return null; - - // Assume the first result contains the desired Mailmark barcode. - string encodedCodetext = results[0].CodeText; - - // Convert the encoded codetext into a MailmarkCodetext object. - MailmarkCodetext mailmark = ComplexCodetextReader.TryDecodeMailmark(encodedCodetext); - - return mailmark; + // Attempt to interpret the code text as a Mailmark (4‑state) barcode. + var mailmark = ComplexCodetextReader.TryDecodeMailmark(result.CodeText); + if (mailmark != null) + return mailmark; // Successful decode. } } } + + // No Mailmark barcode was found in the provided image. + return null; } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/create-helper-class-abstracting-mailmark-barcode-generation-exposing-methods-to-set-individual-data-fields.cs b/mailmark-four-state-barcode/create-helper-class-abstracting-mailmark-barcode-generation-exposing-methods-to-set-individual-data-fields.cs index 3889346..a024455 100644 --- a/mailmark-four-state-barcode/create-helper-class-abstracting-mailmark-barcode-generation-exposing-methods-to-set-individual-data-fields.cs +++ b/mailmark-four-state-barcode/create-helper-class-abstracting-mailmark-barcode-generation-exposing-methods-to-set-individual-data-fields.cs @@ -1,21 +1,18 @@ -// Title: Mailmark 4‑state barcode generation helper example -// Description: Demonstrates how to build a Mailmark barcode by setting individual data fields and saving it as a PNG image. -// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, showcasing the MailmarkCodetext and ComplexBarcodeGenerator classes. Developers use these APIs to create UK Mailmark 4‑state barcodes for postal automation, needing to configure format, version, class, supply chain ID, item ID, and destination postcode. The snippet serves as a reference for building similar barcode helpers. +// Title: Mailmark Barcode Generation Helper Example +// Description: Demonstrates how to use Aspose.BarCode to generate a Mailmark 4‑state barcode by configuring individual data fields through a helper class. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on the Mailmark symbology. It showcases the MailmarkCodetext and ComplexBarcodeGenerator classes, typical for creating postal barcodes with custom data fields such as format, version ID, class, supply chain ID, item ID, and destination postcode plus DPS. Developers working with postal automation, logistics, or mailing solutions often need to generate Mailmark barcodes programmatically. // Prompt: Create a helper class abstracting Mailmark barcode generation, exposing methods to set individual data fields. -// Tags: mailmark, barcode, generation, png, aspnet, aspose.barcode, complexbarcode, helper +// Tags: mailmark, barcode, generation, complexbarcode, aspose.barcode, csharp using System; -using System.IO; -using Aspose.BarCode; -using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; -using Aspose.Drawing; +using Aspose.BarCode.Generation; namespace MailmarkDemo { /// - /// Helper class for building Mailmark 4‑state barcodes using Aspose.BarCode. - /// Provides methods to set each component of the Mailmark codetext and to generate the barcode image. + /// Helper class for building and generating Mailmark barcodes. + /// Provides methods to set each required data field before creating the barcode image. /// public class MailmarkHelper { @@ -30,51 +27,51 @@ public MailmarkHelper() _mailmark = new MailmarkCodetext(); } - // Set the format (1 = Letter, 2 = Large Letter, 4 = unspecified/default) + // Set the 4‑state format (must be 4 for Mailmark) public void SetFormat(int format) { - if (format != 1 && format != 2 && format != 4) - throw new ArgumentOutOfRangeException(nameof(format), "Format must be 1, 2, or 4."); + if (format != 4) + throw new ArgumentException("Mailmark format must be 4 for 4‑state barcodes."); _mailmark.Format = format; } - // Set version identifier (typically 1) + // Set version ID (typically 1) public void SetVersionID(int versionId) { - if (versionId < 0) - throw new ArgumentOutOfRangeException(nameof(versionId), "VersionID must be non‑negative."); + if (versionId <= 0) + throw new ArgumentOutOfRangeException(nameof(versionId)); _mailmark.VersionID = versionId; } - // Set the service class (string values "0"‑"9") - public void SetClass(string serviceClass) + // Set class (single‑character string, e.g., "0") + public void SetClass(string classValue) { - if (string.IsNullOrEmpty(serviceClass) || serviceClass.Length != 1) - throw new ArgumentException("Class must be a single character string.", nameof(serviceClass)); - _mailmark.Class = serviceClass; + if (string.IsNullOrEmpty(classValue) || classValue.Length != 1) + throw new ArgumentException("Class must be a single character string."); + _mailmark.Class = classValue; } - // Set the supply chain identifier (max 999999 for large letters) + // Set supply chain ID (int) public void SetSupplychainID(int supplychainId) { if (supplychainId < 0) - throw new ArgumentOutOfRangeException(nameof(supplychainId), "SupplychainID must be non‑negative."); + throw new ArgumentOutOfRangeException(nameof(supplychainId)); _mailmark.SupplychainID = supplychainId; } - // Set the unique item identifier (max 99 999 999) + // Set item ID (int) public void SetItemID(int itemId) { - if (itemId < 0 || itemId > 99999999) - throw new ArgumentOutOfRangeException(nameof(itemId), "ItemID must be between 0 and 99,999,999."); + if (itemId < 0) + throw new ArgumentOutOfRangeException(nameof(itemId)); _mailmark.ItemID = itemId; } - // Set the destination postcode plus DPS (exact 9‑character format, trailing spaces allowed) + // Set destination postcode plus DPS (must retain trailing space) public void SetDestinationPostCodePlusDPS(string postcodePlusDps) { - if (string.IsNullOrWhiteSpace(postcodePlusDps) || postcodePlusDps.Length != 9) - throw new ArgumentException("DestinationPostCodePlusDPS must be a 9‑character string.", nameof(postcodePlusDps)); + if (string.IsNullOrEmpty(postcodePlusDps) || !postcodePlusDps.EndsWith(" ")) + throw new ArgumentException("DestinationPostCodePlusDPS must end with a trailing space."); _mailmark.DestinationPostCodePlusDPS = postcodePlusDps; } @@ -82,22 +79,18 @@ public void SetDestinationPostCodePlusDPS(string postcodePlusDps) public void Generate(string outputPath) { if (string.IsNullOrWhiteSpace(outputPath)) - throw new ArgumentException("Output path cannot be null or empty.", nameof(outputPath)); + throw new ArgumentException("Output path must be a valid file name.", nameof(outputPath)); - // Ensure the output directory exists - string directory = Path.GetDirectoryName(outputPath); - if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) - Directory.CreateDirectory(directory); + // Ensure required fields are set (basic validation) + if (_mailmark.Format != 4) + throw new InvalidOperationException("Format must be set to 4 before generation."); + if (string.IsNullOrEmpty(_mailmark.DestinationPostCodePlusDPS)) + throw new InvalidOperationException("DestinationPostCodePlusDPS must be set before generation."); - // Use ComplexBarcodeGenerator to create the Mailmark barcode + // Create the generator with the configured Mailmark codetext and save the image. using (var generator = new ComplexBarcodeGenerator(_mailmark)) { - // Optional: set foreground/background colors - generator.Parameters.Barcode.BarColor = Color.Black; - generator.Parameters.BackColor = Color.White; - - // Save the barcode as a PNG file - generator.Save(outputPath, BarCodeImageFormat.Png); + generator.Save(outputPath); } } } @@ -105,26 +98,26 @@ public void Generate(string outputPath) class Program { /// - /// Entry point demonstrating the usage of to create and save a Mailmark barcode. + /// Entry point of the demo application. Configures a MailmarkHelper instance, + /// sets all required fields, generates the barcode, and writes the output path to the console. /// static void Main() { - // Sample usage of the MailmarkHelper var helper = new MailmarkHelper(); - // Populate required fields with known‑valid sample data - helper.SetFormat(4); // 4‑state barcode - helper.SetVersionID(1); - helper.SetClass("0"); // Null/Test class - helper.SetSupplychainID(384224); - helper.SetItemID(16563762); - helper.SetDestinationPostCodePlusDPS("EF61AH8T "); + // Configure Mailmark fields + helper.SetFormat(4); // 4‑state Mailmark + helper.SetVersionID(1); // version + helper.SetClass("0"); // class "0" + helper.SetSupplychainID(384224); // example supply chain ID + helper.SetItemID(16563762); // example item ID + helper.SetDestinationPostCodePlusDPS("EF61AH8T "); // trailing space required - // Generate and save the barcode image + // Generate barcode image string outputFile = "mailmark.png"; helper.Generate(outputFile); - Console.WriteLine($"Mailmark barcode saved to {Path.GetFullPath(outputFile)}"); + Console.WriteLine($"Mailmark barcode saved to {outputFile}"); } } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/create-powershell-script-invoking-net-library-to-batch-convert-csv-rows-into-individual-mailmark-barcode-images.cs b/mailmark-four-state-barcode/create-powershell-script-invoking-net-library-to-batch-convert-csv-rows-into-individual-mailmark-barcode-images.cs index f826b81..ddb69b2 100644 --- a/mailmark-four-state-barcode/create-powershell-script-invoking-net-library-to-batch-convert-csv-rows-into-individual-mailmark-barcode-images.cs +++ b/mailmark-four-state-barcode/create-powershell-script-invoking-net-library-to-batch-convert-csv-rows-into-individual-mailmark-barcode-images.cs @@ -1,121 +1,103 @@ -// Title: Batch conversion of CSV rows to Mailmark barcode images -// Description: Demonstrates reading a CSV file and generating individual Mailmark barcode PNGs using Aspose.BarCode. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as Mailmark. It showcases the use of MailmarkCodetext and ComplexBarcodeGenerator classes to create barcodes from structured data, a common requirement for logistics and mailing applications. Developers can adapt this pattern for bulk barcode creation from data sources like CSV, databases, or APIs. +// Title: Batch conversion of CSV rows to Mailmark barcode images using Aspose.BarCode +// Description: Demonstrates reading a CSV file and generating a separate Mailmark barcode image for each data row. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use ComplexBarcodeGenerator and MailmarkCodetext to create Mailmark barcodes in bulk. Typical use cases include converting data sources such as CSV files into individual barcode images for mailing, logistics, or inventory tracking. Developers often need to automate barcode creation for large datasets, and this pattern illustrates the essential API classes and workflow. // Prompt: Create a PowerShell script invoking the .NET library to batch convert CSV rows into individual Mailmark barcode images. -// Tags: mailmark, barcode generation, csv, batch processing, aspnet, aspose.barcode, png +// Tags: mailmark, barcode, generation, csv, batch, aspose.barcode, png, complexbarcodegenerator using System; using System.IO; -using System.Collections.Generic; -using Aspose.BarCode; using Aspose.BarCode.ComplexBarcode; using Aspose.BarCode.Generation; /// -/// Example program that reads a CSV file and generates Mailmark barcode images for each data row. +/// Demonstrates batch conversion of CSV data rows into individual Mailmark barcode PNG images. /// class Program { /// - /// Entry point of the application. Processes the CSV and creates PNG barcode files. + /// Entry point that reads CSV, creates output folder, and generates barcode images. /// static void Main() { - // Input CSV file path (adjust as needed) + // Define the input CSV file path; fall back to a sample file if it does not exist. string csvPath = "mailmark_data.csv"; - - // Output directory for generated barcode images - string outputDir = "Barcodes"; - - // Verify that the CSV file exists before proceeding if (!File.Exists(csvPath)) { - Console.WriteLine($"CSV file not found: {csvPath}"); - return; + // Create a small sample CSV to ensure the example runs without external data. + File.WriteAllText(csvPath, + "Class,DestinationPostCodePlusDPS,Format,VersionID,ItemID,SupplychainID\n" + + "\"0\",\"EF61AH8T \",1,1,16563762,384224\n" + + "\"1\",\"EF61AH8T \",2,1,16563763,384224"); + Console.WriteLine($"Sample CSV created at '{Path.GetFullPath(csvPath)}'."); } - // Ensure the output directory exists; create it if it does not - if (!Directory.Exists(outputDir)) + // Prepare the output folder where generated barcode images will be saved. + string outputFolder = "MailmarkBarcodes"; + if (!Directory.Exists(outputFolder)) { - Directory.CreateDirectory(outputDir); + Directory.CreateDirectory(outputFolder); } - // Read all lines from the CSV file into memory - string[] allLines = File.ReadAllLines(csvPath); - - // Check that there is at least one data row (excluding header) - if (allLines.Length <= 1) + // Read all lines from the CSV file. + string[] lines = File.ReadAllLines(csvPath); + if (lines.Length <= 1) { - Console.WriteLine("CSV file does not contain data rows."); + Console.WriteLine("CSV contains no data rows."); return; } - // Assume the first line is a header row describing column names - // Expected columns: Format,VersionID,Class,SupplychainID,ItemID,DestinationPostCodePlusDPS - // Process up to 5 rows for safety (adjust as needed) - int maxRows = Math.Min(5, allLines.Length - 1); - for (int i = 1; i <= maxRows; i++) + // Process each data row (skip header line at index 0). + for (int i = 1; i < lines.Length; i++) { - string line = allLines[i]; - - // Skip empty or whitespace-only lines + string line = lines[i]; if (string.IsNullOrWhiteSpace(line)) - continue; + continue; // Skip empty lines. - // Split the CSV line into individual fields + // Simple CSV split (does not handle escaped commas). string[] parts = line.Split(','); - // Validate that the required number of columns is present if (parts.Length < 6) { - Console.WriteLine($"Skipping line {i + 1}: insufficient columns."); + Console.WriteLine($"Skipping malformed line {i + 1}: insufficient columns."); continue; } try { - // Trim whitespace from each field to ensure clean parsing - for (int p = 0; p < parts.Length; p++) - parts[p] = parts[p].Trim(); - - // Parse fields into appropriate data types - int format = int.Parse(parts[0]); // Format as integer (1,2,4 etc.) - int versionId = int.Parse(parts[1]); // VersionID as integer - string classValue = parts[2]; // Class as string - int supplychainId = int.Parse(parts[3]); // SupplychainID as integer - int itemId = int.Parse(parts[4]); // ItemID as integer - string destinationPostCodePlusDps = parts[5]; // DestinationPostCodePlusDPS as string (keep spaces) - - // Create a MailmarkCodetext object populated with the parsed values + // Extract and clean individual column values. + string classValue = parts[0].Trim().Trim('\"'); + string destination = parts[1].Trim().Trim('\"'); // Keep trailing space as required. + int format = int.Parse(parts[2].Trim()); + int versionId = int.Parse(parts[3].Trim()); + int itemId = int.Parse(parts[4].Trim()); + int supplyChainId = int.Parse(parts[5].Trim()); + + // Build the Mailmark codetext object with the extracted values. var mailmark = new MailmarkCodetext { + Class = classValue, + DestinationPostCodePlusDPS = destination, Format = format, VersionID = versionId, - Class = classValue, - SupplychainID = supplychainId, ItemID = itemId, - DestinationPostCodePlusDPS = destinationPostCodePlusDps + SupplychainID = supplyChainId }; - // Use ComplexBarcodeGenerator to generate the barcode image + // Generate the barcode image using ComplexBarcodeGenerator. using (var generator = new ComplexBarcodeGenerator(mailmark)) { - // Construct the output file name (e.g., Mailmark_12345.png) - string outputPath = Path.Combine(outputDir, $"Mailmark_{itemId}.png"); - - // Save the generated barcode as a PNG file + string fileName = $"Mailmark_{i:D4}_{itemId}.png"; + string outputPath = Path.Combine(outputFolder, fileName); generator.Save(outputPath, BarCodeImageFormat.Png); - Console.WriteLine($"Generated barcode for ItemID {itemId} -> {outputPath}"); + Console.WriteLine($"Generated: {outputPath}"); } } catch (Exception ex) { - // Report any errors encountered while processing the current line Console.WriteLine($"Error processing line {i + 1}: {ex.Message}"); } } - // Indicate that the batch processing has finished - Console.WriteLine("Batch processing completed."); + Console.WriteLine("Batch conversion completed."); } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/develop-console-app-that-reads-multiple-tiff-files-extracts-mailmark-barcodes-and-logs-decoded-fields.cs b/mailmark-four-state-barcode/develop-console-app-that-reads-multiple-tiff-files-extracts-mailmark-barcodes-and-logs-decoded-fields.cs index 2fb7e5c..20b280d 100644 --- a/mailmark-four-state-barcode/develop-console-app-that-reads-multiple-tiff-files-extracts-mailmark-barcodes-and-logs-decoded-fields.cs +++ b/mailmark-four-state-barcode/develop-console-app-that-reads-multiple-tiff-files-extracts-mailmark-barcodes-and-logs-decoded-fields.cs @@ -1,104 +1,127 @@ -// Title: Mailmark barcode extraction from multiple TIFF images -// Description: Demonstrates reading up to five TIFF files, detecting Mailmark barcodes, and outputting decoded fields to the console. -// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on complex barcode types such as Mailmark. It showcases the BarCodeReader and ComplexCodetextReader classes for detecting and decoding Mailmark symbology, a common requirement in postal and logistics applications where developers need to extract routing and item information from scanned documents. +// Title: Mailmark Barcode Generation, Detection, and Decoding from TIFF Files +// Description: Demonstrates creating sample Mailmark barcodes, saving them as TIFF images, scanning the images, and logging decoded fields. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, showcasing the ComplexBarcodeGenerator for creating Mailmark symbols and BarCodeReader for extracting them. Typical use cases include bulk processing of mail items, automated verification of Mailmark data, and integration into logistics workflows. Developers often need to generate, read, and parse Mailmark barcodes using Aspose.BarCode's API classes such as ComplexBarcodeGenerator, BarCodeReader, and ComplexCodetextReader. // Prompt: Develop a console app that reads multiple TIFF files, extracts Mailmark barcodes, and logs decoded fields. -// Tags: mailmark, barcode, recognition, tiff, console, aspose.barcode, complexbarcode +// Tags: mailmark, barcode, generation, recognition, tiff, console, aspose.barcode, complexbarcodegenerator, barcodereader using System; using System.IO; -using Aspose.BarCode.BarCodeRecognition; +using System.Collections.Generic; +using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; +using Aspose.BarCode.BarCodeRecognition; -namespace MailmarkReaderApp +/// +/// Sample console application that generates Mailmark barcodes, saves them as TIFF files, +/// reads the files, decodes the Mailmark data, and writes the extracted fields to the console. +/// +class Program { /// - /// Entry point for the MailmarkReader console application. + /// Entry point of the application. Performs generation, scanning, and decoding of Mailmark barcodes. /// - class Program + static void Main() { - /// - /// Reads up to five TIFF files from a specified directory, detects Mailmark barcodes, - /// decodes their fields, and writes the information to the console. - /// - static void Main() + // -------------------------------------------------------------------- + // Prepare a temporary folder for sample TIFF files + // -------------------------------------------------------------------- + string sampleFolder = Path.Combine(Path.GetTempPath(), "MailmarkSamples"); + if (!Directory.Exists(sampleFolder)) { - // Directory containing TIFF files (adjust as needed) - string imagesDirectory = "SampleTiffImages"; + Directory.CreateDirectory(sampleFolder); + } - // Ensure the directory exists before proceeding - if (!Directory.Exists(imagesDirectory)) + // -------------------------------------------------------------------- + // Create a few sample Mailmark codetext objects + // -------------------------------------------------------------------- + var samples = new List + { + new MailmarkCodetext + { + Format = 4, + VersionID = 1, + Class = "0", + SupplychainID = 384224, + ItemID = 16563762, + DestinationPostCodePlusDPS = "EF61AH8T " + }, + new MailmarkCodetext { - Console.WriteLine($"Directory not found: {imagesDirectory}"); - return; + Format = 4, + VersionID = 1, + Class = "1", + SupplychainID = 384224, + ItemID = 16563763, + DestinationPostCodePlusDPS = "EF61AH8T " + }, + new MailmarkCodetext + { + Format = 4, + VersionID = 1, + Class = "2", + SupplychainID = 384224, + ItemID = 16563764, + DestinationPostCodePlusDPS = "EF61AH8T " } + }; - // Retrieve all TIFF files in the directory - string[] tiffFiles = Directory.GetFiles(imagesDirectory, "*.tif"); - // Limit processing to a maximum of five files - int maxFiles = Math.Min(tiffFiles.Length, 5); - if (maxFiles == 0) + // -------------------------------------------------------------------- + // Generate a TIFF file for each sample Mailmark barcode + // -------------------------------------------------------------------- + int index = 0; + foreach (var mailmark in samples) + { + string filePath = Path.Combine(sampleFolder, $"mailmark_{index}.tif"); + using (var generator = new ComplexBarcodeGenerator(mailmark)) { - Console.WriteLine("No TIFF files found."); - return; + generator.Save(filePath, BarCodeImageFormat.Tiff); } + index++; + } - // Process each selected TIFF file - for (int i = 0; i < maxFiles; i++) + // -------------------------------------------------------------------- + // Scan the folder for TIFF files and decode any Mailmark barcodes found + // -------------------------------------------------------------------- + string[] tiffFiles = Directory.GetFiles(sampleFolder, "*.tif"); + foreach (string tiffFile in tiffFiles) + { + if (!File.Exists(tiffFile)) { - string filePath = tiffFiles[i]; - Console.WriteLine($"Processing file: {Path.GetFileName(filePath)}"); + Console.WriteLine($"File not found: {tiffFile}"); + continue; + } - // Verify the file still exists (it may have been moved or deleted) - if (!File.Exists(filePath)) - { - Console.WriteLine("File does not exist, skipping."); - continue; - } + using (var reader = new BarCodeReader(tiffFile, DecodeType.Mailmark)) + { + // Optional: improve detection speed/quality + reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast; - // Initialize the barcode reader for Mailmark symbology - using (var reader = new BarCodeReader(filePath, DecodeType.Mailmark)) + foreach (var result in reader.ReadBarCodes()) { - // Optional: improve detection speed/quality - // reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast; - - try + // Decode the Mailmark codetext into its structured object + MailmarkCodetext decoded = ComplexCodetextReader.TryDecodeMailmark(result.CodeText); + if (decoded != null) { - // 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($" Raw CodeText: {result.CodeText}"); - - // Attempt to decode Mailmark-specific fields - MailmarkCodetext mailmark = ComplexCodetextReader.TryDecodeMailmark(result.CodeText); - if (mailmark != null) - { - Console.WriteLine(" Decoded Mailmark fields:"); - Console.WriteLine($" Format: {mailmark.Format}"); - Console.WriteLine($" VersionID: {mailmark.VersionID}"); - Console.WriteLine($" Class: {mailmark.Class}"); - Console.WriteLine($" SupplychainID: {mailmark.SupplychainID}"); - Console.WriteLine($" ItemID: {mailmark.ItemID}"); - Console.WriteLine($" DestinationPostCodePlusDPS: \"{mailmark.DestinationPostCodePlusDPS}\""); - } - else - { - Console.WriteLine(" Failed to decode Mailmark codetext."); - } - } + Console.WriteLine($"File: {Path.GetFileName(tiffFile)}"); + Console.WriteLine($" Format: {decoded.Format}"); + Console.WriteLine($" VersionID: {decoded.VersionID}"); + Console.WriteLine($" Class: {decoded.Class}"); + Console.WriteLine($" SupplychainID: {decoded.SupplychainID}"); + Console.WriteLine($" ItemID: {decoded.ItemID}"); + Console.WriteLine($" DestinationPostCodePlusDPS: \"{decoded.DestinationPostCodePlusDPS}\""); } - catch (Exception ex) + else { - // Log any errors encountered while reading barcodes - Console.WriteLine($" Error reading barcode: {ex.Message}"); + Console.WriteLine($"File: {Path.GetFileName(tiffFile)} - Unable to decode Mailmark codetext."); } } - - Console.WriteLine(); // Blank line between files for readability } - - Console.WriteLine("Processing completed."); } + + // -------------------------------------------------------------------- + // Cleanup: optionally delete the temporary files + // -------------------------------------------------------------------- + // foreach (var file in tiffFiles) { File.Delete(file); } + // Directory.Delete(sampleFolder, true); } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/develop-rest-endpoint-receiving-json-mailmark-fields-and-returning-generated-barcode-as-base64-string.cs b/mailmark-four-state-barcode/develop-rest-endpoint-receiving-json-mailmark-fields-and-returning-generated-barcode-as-base64-string.cs index c3bd006..5324a57 100644 --- a/mailmark-four-state-barcode/develop-rest-endpoint-receiving-json-mailmark-fields-and-returning-generated-barcode-as-base64-string.cs +++ b/mailmark-four-state-barcode/develop-rest-endpoint-receiving-json-mailmark-fields-and-returning-generated-barcode-as-base64-string.cs @@ -1,84 +1,98 @@ -// Title: Generate Mailmark barcode from JSON and return Base64 -// Description: Demonstrates how to deserialize Mailmark fields from JSON, create a Mailmark barcode using Aspose.BarCode, and output the image as a Base64 string. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as Mailmark. It showcases the use of ComplexBarcodeGenerator and MailmarkCodetext classes to create barcodes from structured data, a common requirement for developers building REST services that need to return barcode images in web-friendly formats. +// Title: Generate Mailmark 4‑state barcode and return Base64 string +// Description: Demonstrates creating a Mailmark 4‑state barcode from JSON input and encoding the image as a Base64 string, suitable for returning from a REST endpoint. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of Aspose.BarCode.ComplexBarcode.MailmarkCodetext and Aspose.BarCode.Generation.ComplexBarcodeGenerator to produce Mailmark barcodes, a common requirement in postal automation and logistics. Developers often need to convert barcode images to Base64 for web APIs, email attachments, or storage. // Prompt: Develop a REST endpoint receiving JSON Mailmark fields and returning the generated barcode as Base64 string. -// Tags: mailmark, barcode generation, json, base64, aspose.barcode, complexbarcode +// Tags: mailmark, barcode, generation, base64, aspnet, aspose.barcode, json, rest using System; using System.IO; using System.Text.Json; -using Aspose.BarCode; using Aspose.BarCode.ComplexBarcode; using Aspose.BarCode.Generation; -/// -/// Example program that deserializes Mailmark data from JSON, -/// generates a Mailmark barcode, and outputs the image as a Base64 string. -/// -class Program +namespace MailmarkBarcodeDemo { - // Sample JSON representing Mailmark fields. - // In a real REST service this would come from the request body. - private const string SampleJson = @" + /// + /// Model matching the expected JSON payload for Mailmark barcode generation. + /// + public class MailmarkRequest { - ""format"": 4, - ""versionId"": 1, - ""class"": ""0"", - ""supplychainId"": 384224, - ""itemId"": 16563762, - ""destinationPostCodePlusDps"": ""EF61AH8T "" - }"; + public int Format { get; set; } // Must be 4 for 4‑state Mailmark + public int VersionID { get; set; } // Typically 1 + public string Class { get; set; } // e.g. "0" + public int SupplychainID { get; set; } // e.g. 384224 + public int ItemID { get; set; } // e.g. 16563762 + public string DestinationPostCodePlusDPS { get; set; } // Must include trailing space + } /// - /// Entry point of the example. Demonstrates the core logic of - /// JSON deserialization, barcode generation, and Base64 conversion. + /// Demonstrates generating a Mailmark barcode from JSON data and outputting the image as a Base64 string. /// - static void Main() + class Program { - // NOTE: The snippet runner cannot host an HTTP server. - // The core logic is demonstrated by reading a JSON string, - // generating a Mailmark barcode, and outputting the image as Base64. + /// + /// Entry point – simulates a REST call by deserializing a JSON payload, creating a Mailmark barcode, + /// and writing the Base64‑encoded PNG image to the console (representing the HTTP response body). + /// + static void Main() + { + // Sample JSON input – in a real REST service this would come from the request body + string jsonInput = @"{ + ""Format"": 4, + ""VersionID"": 1, + ""Class"": ""0"", + ""SupplychainID"": 384224, + ""ItemID"": 16563762, + ""DestinationPostCodePlusDPS"": ""EF61AH8T "" + }"; - // Deserialize JSON to a POCO using case‑insensitive property matching. - var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; - MailmarkInput input = JsonSerializer.Deserialize(SampleJson, options); + // Deserialize JSON to a strongly‑typed request object + MailmarkRequest request = JsonSerializer.Deserialize(jsonInput); + if (request == null) + { + Console.WriteLine("Invalid input."); + return; + } - // Validate required fields. - if (input == null) - { - Console.WriteLine("Invalid input."); - return; - } + // Basic validation of required fields + if (request.Format != 4) + { + Console.WriteLine("Only Mailmark 4‑state (Format=4) is supported."); + return; + } + if (string.IsNullOrEmpty(request.Class) || + string.IsNullOrEmpty(request.DestinationPostCodePlusDPS)) + { + Console.WriteLine("Missing required Mailmark fields."); + return; + } - // Populate MailmarkCodetext with required properties. - var mailmark = new MailmarkCodetext - { - Format = input.Format, - VersionID = input.VersionId, - Class = input.Class, - SupplychainID = input.SupplychainId, - ItemID = input.ItemId, - DestinationPostCodePlusDPS = input.DestinationPostCodePlusDps - }; + // Populate the MailmarkCodetext object with request data + var mailmark = new MailmarkCodetext + { + Format = request.Format, + VersionID = request.VersionID, + Class = request.Class, + SupplychainID = request.SupplychainID, + ItemID = request.ItemID, + DestinationPostCodePlusDPS = request.DestinationPostCodePlusDPS + }; - // Generate barcode image and convert to Base64. - using (var generator = new ComplexBarcodeGenerator(mailmark)) - using (var ms = new MemoryStream()) - { - generator.Save(ms, BarCodeImageFormat.Png); - string base64 = Convert.ToBase64String(ms.ToArray()); - Console.WriteLine(base64); - } - } + // Generate the barcode image into a memory stream + using (var ms = new MemoryStream()) + { + using (var generator = new ComplexBarcodeGenerator(mailmark)) + { + // Save the barcode as PNG (BarCodeImageFormat resides in Aspose.BarCode.Generation) + generator.Save(ms, BarCodeImageFormat.Png); + } - // POCO matching the expected JSON structure. - private class MailmarkInput - { - public int Format { get; set; } - public int VersionId { get; set; } - public string Class { get; set; } - public int SupplychainId { get; set; } - public int ItemId { get; set; } - public string DestinationPostCodePlusDps { get; set; } + // Convert the PNG bytes to a Base64 string + string base64 = Convert.ToBase64String(ms.ToArray()); + + // Output the Base64 string (simulating a REST response body) + Console.WriteLine(base64); + } + } } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/enable-barcode-rotation-by-setting-complexbarcodegenerator-rotationangle-property-before-generating-image.cs b/mailmark-four-state-barcode/enable-barcode-rotation-by-setting-complexbarcodegenerator-rotationangle-property-before-generating-image.cs index f069025..4484dc7 100644 --- a/mailmark-four-state-barcode/enable-barcode-rotation-by-setting-complexbarcodegenerator-rotationangle-property-before-generating-image.cs +++ b/mailmark-four-state-barcode/enable-barcode-rotation-by-setting-complexbarcodegenerator-rotationangle-property-before-generating-image.cs @@ -1,25 +1,26 @@ -// Title: Rotate SwissQR barcode image using ComplexBarcodeGenerator -// Description: Demonstrates how to rotate a SwissQR barcode by setting the RotationAngle property before saving the image. -// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, showcasing the use of ComplexBarcodeGenerator and SwissQRCodetext classes to create and manipulate Swiss QR Bill barcodes. Typical use cases include generating payment QR codes with custom orientation for printing or display. Developers often need to adjust rotation, size, and other parameters when integrating barcodes into documents or UI layouts. -// Prompt: Enable barcode rotation by setting ComplexBarcodeGenerator RotationAngle property before generating the image. -// Tags: swissqr, rotation, complexbarcodegenerator, barcodegeneration, png, aspnet, aspnetcore, csharp +// Title: Rotate Swiss QR Code Barcode Using ComplexBarcodeGenerator +// Description: Demonstrates how to rotate a Swiss QR Code barcode image by setting the RotationAngle property before saving the image. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator and its Parameters to manipulate barcode appearance, such as rotation. Developers working with Swiss QR Codes, QR payments, or custom barcode layouts often need to adjust orientation for branding or layout requirements. The example highlights key classes like SwissQRCodetext, ComplexBarcodeGenerator, and the RotationAngle property, providing a quick reference for similar scenarios. +/// Prompt: Enable barcode rotation by setting ComplexBarcodeGenerator RotationAngle property before generating the image. +// Tags: swissqr, rotation, complexbarcodegenerator, barcode, image, csharp, aspose.barcode using System; -using Aspose.BarCode.ComplexBarcode; +using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.BarCode.ComplexBarcode; /// -/// Example program that generates a rotated SwissQR barcode image. +/// Example program that generates a rotated Swiss QR Code barcode using Aspose.BarCode. /// class Program { /// - /// Entry point of the application. Creates a SwissQR codetext, sets a rotation angle, - /// and saves the resulting barcode image to a file. + /// Entry point. Creates a Swiss QR Code, sets rotation, and saves the image. /// static void Main() { - // Create a SwissQR codetext and populate required fields for a payment bill + // Initialize Swiss QR Code data with required fields var swissQr = new SwissQRCodetext(); swissQr.Bill.Creditor.Name = "John Doe"; swissQr.Bill.Creditor.CountryCode = "CH"; @@ -27,17 +28,18 @@ static void Main() swissQr.Bill.Amount = 199.95m; swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0; - // Initialize ComplexBarcodeGenerator with the prepared codetext + // Create a ComplexBarcodeGenerator using the Swiss QR Code data using (var generator = new ComplexBarcodeGenerator(swissQr)) { - // Set rotation angle (e.g., 90 degrees) before generating the image - generator.Parameters.RotationAngle = 90f; + // Set the rotation angle (e.g., 45 degrees) before generating the image + generator.Parameters.RotationAngle = 45f; - // Save the rotated barcode image to a PNG file - generator.Save("rotated_swissqr.png"); - } + // Define output file path and save the rotated barcode image + string outputPath = "rotatedSwissQR.png"; + generator.Save(outputPath); - // Inform the user that the barcode has been generated - Console.WriteLine("Barcode generated and saved as rotated_swissqr.png"); + // Output the full path of the saved image for verification + Console.WriteLine($"Barcode saved to {Path.GetFullPath(outputPath)}"); + } } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/generate-mailmark-4-state-barcode-with-complexbarcodegenerator-and-save-as-png.cs b/mailmark-four-state-barcode/generate-mailmark-4-state-barcode-with-complexbarcodegenerator-and-save-as-png.cs index 1cd136a..7f7488e 100644 --- a/mailmark-four-state-barcode/generate-mailmark-4-state-barcode-with-complexbarcodegenerator-and-save-as-png.cs +++ b/mailmark-four-state-barcode/generate-mailmark-4-state-barcode-with-complexbarcodegenerator-and-save-as-png.cs @@ -1,36 +1,45 @@ -// Title: Generate Mailmark 4‑state barcode with ComplexBarcodeGenerator -// Description: Demonstrates creating a Mailmark 4‑state barcode using Aspose.BarCode's ComplexBarcodeGenerator and saving it as a PNG image. -// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, illustrating how to work with the MailmarkCodetext class and ComplexBarcodeGenerator to produce 4‑state barcodes. Developers often need to encode postal routing information, service class, and item identifiers for mail processing systems, and this snippet shows the typical steps for configuring the codetext and exporting the barcode image. +// Title: Generate Mailmark 4‑state barcode and save as PNG +// Description: Demonstrates how to create a Mailmark 4‑state barcode using Aspose.BarCode's ComplexBarcodeGenerator and write the image to a PNG file. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, showcasing the use of MailmarkCodetext and ComplexBarcodeGenerator classes. Developers often need to produce Mailmark 4‑state symbols for postal automation, requiring precise codetext configuration and image export. The snippet illustrates typical setup, parameter tuning, and saving the result, useful for integration into mailing systems. // Prompt: Generate a Mailmark 4‑state barcode with ComplexBarcodeGenerator and save as PNG. -// Tags: mailmark, barcode, complexbarcodegenerator, png, aspose.barcode, 4-state +// Tags: mailmark, 4-state, barcode, generation, png, complexbarcodegenerator, aspose.barcode using System; +using System.IO; using Aspose.BarCode.ComplexBarcode; using Aspose.BarCode.Generation; +using Aspose.Drawing.Imaging; /// -/// Demonstrates generating a Mailmark 4‑state barcode and saving it as a PNG file. +/// Demonstrates generation of a Mailmark 4‑state barcode and saving it as a PNG image. /// class Program { /// - /// Entry point that creates the Mailmark codetext, generates the barcode, and writes it to disk. + /// Entry point of the example. Configures Mailmark codetext, generates the barcode, and writes the image file. /// static void Main() { // Initialize Mailmark 4‑state codetext with required fields var mailmark = new MailmarkCodetext(); - mailmark.Format = 4; // 4‑state format identifier - mailmark.VersionID = 1; // Version of the Mailmark specification - mailmark.Class = "0"; // Service type / class code - mailmark.SupplychainID = 384224; // Routing code (supply chain identifier) - mailmark.ItemID = 16563762; // Customer reference (item identifier) - mailmark.DestinationPostCodePlusDPS = "EF61AH8T "; // Destination postcode plus DPS (trailing space required) + mailmark.Format = 4; // 4‑state Mailmark + mailmark.VersionID = 1; // version + mailmark.Class = "0"; // class as string + mailmark.SupplychainID = 384224; // example supply‑chain ID + mailmark.ItemID = 16563762; // example item ID + mailmark.DestinationPostCodePlusDPS = "EF61AH8T "; // trailing space required - // Generate the barcode using ComplexBarcodeGenerator and save it as a PNG file + // Create generator for the specified codetext using (var generator = new ComplexBarcodeGenerator(mailmark)) { - generator.Save("mailmark.png"); // Write the barcode image to the file system + // Adjust optional barcode parameters + generator.Parameters.Barcode.FilledBars = false; + generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false; + + // Export barcode image to PNG file + string outputPath = "Mailmark4State.png"; + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Mailmark barcode saved to: {Path.GetFullPath(outputPath)}"); } } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/generate-mailmark-barcode-into-memorystream-and-return-image-bytes-to-web-api.cs b/mailmark-four-state-barcode/generate-mailmark-barcode-into-memorystream-and-return-image-bytes-to-web-api.cs index e6db894..06c78dd 100644 --- a/mailmark-four-state-barcode/generate-mailmark-barcode-into-memorystream-and-return-image-bytes-to-web-api.cs +++ b/mailmark-four-state-barcode/generate-mailmark-barcode-into-memorystream-and-return-image-bytes-to-web-api.cs @@ -1,58 +1,53 @@ -// Title: Generate Mailmark barcode to MemoryStream -// Description: Demonstrates creating a Mailmark barcode, saving it as PNG into a MemoryStream, and returning the image bytes for use in a web API response. -// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on Mailmark symbology. It showcases the use of MailmarkCodetext to define barcode data and ComplexBarcodeGenerator to render the barcode. Developers working with logistics, mailing services, or any scenario requiring Mailmark barcodes often need to generate images in-memory for API delivery or further processing. +// Title: Generate Mailmark Barcode to MemoryStream and Return PNG Bytes +// Description: Demonstrates creating a Mailmark barcode with Aspose.BarCode, saving it as a PNG image into a MemoryStream, and retrieving the raw byte array for use in a web API. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of the ComplexBarcodeGenerator class to produce Mailmark (4‑state) barcodes, a common requirement for postal services and logistics applications. Developers often need to generate barcode images on‑the‑fly and return them as byte streams for web services, mobile apps, or document workflows. // Prompt: Generate a Mailmark barcode into a MemoryStream and return image bytes to a web API. -// Tags: barcode, mailmark, generation, memory stream, png, aspnet, aspose.barcode, complexbarcode +// Tags: mailmark, barcode generation, png, memorystream, complexbarcodegenerator, aspose.barcode, web api using System; using System.IO; -using Aspose.BarCode; -using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; +using Aspose.BarCode.Generation; -/// -/// Example program that creates a Mailmark barcode, writes it to a MemoryStream, -/// and outputs the image bytes as a Base64 string (simulating a web API response). -/// -class Program +namespace MailmarkBarcodeExample { /// - /// Entry point of the example. Builds the Mailmark codetext, generates the barcode, - /// and writes the PNG image bytes to the console as Base64. + /// Provides an entry point that creates a Mailmark barcode, saves it to a MemoryStream, + /// and outputs the resulting PNG byte array length. Intended for integration with a web API. /// - static void Main() + class Program { - // Initialize Mailmark codetext with required fields - var mailmark = new MailmarkCodetext + /// + /// Main method that builds the Mailmark codetext, generates the barcode image, + /// and extracts the PNG bytes from a MemoryStream. + /// + static void Main() { - // Set the barcode format to 4-state (standard Mailmark) - Format = 4, - // Version identifier for the barcode specification - VersionID = 1, - // Class identifier (e.g., "0" for standard class) - Class = "0", - // Supply chain identifier (numeric) - SupplychainID = 384224, - // Item identifier (numeric) - ItemID = 16563762, - // Destination postcode plus DPS (trailing space is significant) - DestinationPostCodePlusDPS = "EF61AH8T " - }; + // Initialize Mailmark codetext with required fields. + var mailmark = new MailmarkCodetext + { + Format = 4, // 4‑state Mailmark format + VersionID = 1, + Class = "0", + SupplychainID = 384224, + ItemID = 16563762, + DestinationPostCodePlusDPS = "EF61AH8T " // trailing space is required + }; - // Create a ComplexBarcodeGenerator using the Mailmark codetext - using (var generator = new ComplexBarcodeGenerator(mailmark)) - { - // Prepare an in‑memory stream to hold the generated PNG image + // Create a MemoryStream to hold the generated PNG image. using (var memoryStream = new MemoryStream()) { - // Save the barcode image to the MemoryStream in PNG format - generator.Save(memoryStream, BarCodeImageFormat.Png); + // Generate the barcode using ComplexBarcodeGenerator and save as PNG. + using (var generator = new ComplexBarcodeGenerator(mailmark)) + { + generator.Save(memoryStream, BarCodeImageFormat.Png); + } - // Retrieve the raw image bytes from the stream + // Retrieve the PNG image bytes from the MemoryStream. byte[] imageBytes = memoryStream.ToArray(); - // Output the image bytes as a Base64 string (simulating API response) - Console.WriteLine(Convert.ToBase64String(imageBytes)); + // Demonstrate that the image was generated by writing the byte array length. + Console.WriteLine($"Mailmark barcode image generated. Byte array length: {imageBytes.Length}"); } } } diff --git a/mailmark-four-state-barcode/generate-mailmark-barcode-with-custom-margins-to-ensure-sufficient-white-space-around-symbol.cs b/mailmark-four-state-barcode/generate-mailmark-barcode-with-custom-margins-to-ensure-sufficient-white-space-around-symbol.cs index 33ef401..441bd32 100644 --- a/mailmark-four-state-barcode/generate-mailmark-barcode-with-custom-margins-to-ensure-sufficient-white-space-around-symbol.cs +++ b/mailmark-four-state-barcode/generate-mailmark-barcode-with-custom-margins-to-ensure-sufficient-white-space-around-symbol.cs @@ -1,51 +1,55 @@ -// Title: Generate Mailmark barcode with custom margins -// Description: Demonstrates creating a Mailmark barcode and applying custom white‑space margins to ensure adequate surrounding space. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as Mailmark. It showcases the use of ComplexBarcodeGenerator, MailmarkCodetext, and barcode parameter settings (padding, resolution). Developers often need to customize appearance and layout of generated barcodes for printing or embedding in documents, and this snippet illustrates typical steps for configuring margins and saving the image. +// Title: Generate Mailmark Barcode with Custom Margins +// Description: Demonstrates how to create a Mailmark barcode using Aspose.BarCode, set custom padding to provide adequate white space, and save the result as a PNG image. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex symbologies such as Mailmark. It showcases the use of ComplexBarcodeGenerator and MailmarkCodetext classes to configure barcode data, visual appearance, and layout. Developers commonly need to adjust margins, colors, and output formats when integrating barcodes into documents, labels, or packaging. // Prompt: Generate a Mailmark barcode with custom margins to ensure sufficient white space around the symbol. -// Tags: mailmark, barcode, padding, margin, png, aspnet, aspose.barcode, complexbarcodegenerator +// Tags: mailmark, barcode generation, png, complexbarcodegenerator, mailmarkcodetext using System; -using Aspose.BarCode; -using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; +using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Demonstrates generating a Mailmark barcode with custom margins using Aspose.BarCode. +/// Example program that generates a Mailmark barcode with custom margins. /// class Program { /// - /// Entry point. Creates a Mailmark barcode, applies padding, sets resolution, and saves as PNG. + /// Generates the barcode and saves it to a PNG file. /// static void Main() { - // Prepare Mailmark codetext with required fields + // Prepare Mailmark codetext with valid values. var mailmark = new MailmarkCodetext { - Format = 4, // unspecified/default format + // 4-state Mailmark format. + Format = 4, VersionID = 1, Class = "0", SupplychainID = 384224, ItemID = 16563762, + // Destination post code plus DPS must retain the trailing space. DestinationPostCodePlusDPS = "EF61AH8T " }; - // Create ComplexBarcodeGenerator using the Mailmark codetext + // Generate the Mailmark barcode using ComplexBarcodeGenerator. using (var generator = new ComplexBarcodeGenerator(mailmark)) { - // Set custom white space (padding) around the barcode (10 points on each side) - generator.Parameters.Barcode.Padding.Left.Point = 10f; - generator.Parameters.Barcode.Padding.Top.Point = 10f; - generator.Parameters.Barcode.Padding.Right.Point = 10f; - generator.Parameters.Barcode.Padding.Bottom.Point = 10f; + // Optional: set foreground and background colors. + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; - // Optional: set image resolution (dots per inch) - generator.Parameters.Resolution = 300; + // Configure custom margins (padding) to ensure sufficient white space. + // Values are in points; adjust as needed. + generator.Parameters.Barcode.Padding.Left.Point = 10f; + generator.Parameters.Barcode.Padding.Top.Point = 10f; + generator.Parameters.Barcode.Padding.Right.Point = 10f; + generator.Parameters.Barcode.Padding.Bottom.Point = 10f; - // Save the generated barcode image to a PNG file - string outputPath = "mailmark.png"; - generator.Save(outputPath, BarCodeImageFormat.Png); - Console.WriteLine($"Mailmark barcode saved to {outputPath}"); + // Save the barcode image to a PNG file. + generator.Save("mailmark.png"); } + + Console.WriteLine("Mailmark barcode generated: mailmark.png"); } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/implement-asynchronous-barcode-generation-with-taskrun-to-prevent-ui-thread-blocking-during-complex-mailmark-creation.cs b/mailmark-four-state-barcode/implement-asynchronous-barcode-generation-with-taskrun-to-prevent-ui-thread-blocking-during-complex-mailmark-creation.cs index 41dd889..3de0497 100644 --- a/mailmark-four-state-barcode/implement-asynchronous-barcode-generation-with-taskrun-to-prevent-ui-thread-blocking-during-complex-mailmark-creation.cs +++ b/mailmark-four-state-barcode/implement-asynchronous-barcode-generation-with-taskrun-to-prevent-ui-thread-blocking-during-complex-mailmark-creation.cs @@ -1,124 +1,55 @@ // Title: Asynchronous Mailmark Barcode Generation Example -// Description: Demonstrates generating Mailmark barcodes asynchronously to avoid UI thread blocking, saving each as a PNG file. -// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, showcasing the use of ComplexBarcodeGenerator with MailmarkCodetext. It illustrates typical scenarios where developers need to create multiple Mailmark barcodes efficiently, leveraging asynchronous Task.Run to keep UI responsive. Key API classes include ComplexBarcodeGenerator, MailmarkCodetext, and BarCodeImageFormat, commonly used for high‑volume barcode creation in .NET applications. +// Description: Demonstrates generating a Royal Mailmark barcode asynchronously to keep the UI responsive. +// Category-Description: Shows how to use Aspose.BarCode's ComplexBarcodeGenerator for creating Mailmark barcodes. This example belongs to the barcode generation category, illustrating background processing with Task.Run, setting visual parameters, and saving the image. Developers working with complex barcode symbologies such as Mailmark often need to off‑load generation to a background thread to avoid UI thread blocking. // Prompt: Implement asynchronous barcode generation with Task.Run to prevent UI thread blocking during complex Mailmark creation. -// Tags: mailmark, barcode, asynchronous, task.run, complexbarcode, generation, png, aspnet, csharp +// Tags: mailmark, barcode, asynchronous, task.run, complexbarcode, generation, png, aspose.barcode using System; -using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Aspose.BarCode; -using Aspose.BarCode.Generation; using Aspose.BarCode.ComplexBarcode; using Aspose.Drawing; /// -/// Demonstrates asynchronous generation of Mailmark barcodes using Aspose.BarCode. +/// Demonstrates asynchronous generation of a Mailmark barcode using Aspose.BarCode. /// class Program { /// - /// Asynchronously generates a Mailmark barcode image and saves it to the specified path. + /// Entry point that creates and saves a Mailmark barcode without blocking the UI thread. /// - /// The Mailmark codetext containing barcode data. - /// Full file path where the PNG image will be saved. - /// A task that resolves to the output path once the image is saved. - private static Task GenerateMailmarkAsync(MailmarkCodetext mailmark, string outputPath) + static async Task Main() { - // Run the generation on a background thread to avoid blocking the UI. - return Task.Run(() => + // Prepare a valid Mailmark codetext (4‑state Royal Mailmark) + var mailmark = new MailmarkCodetext { - // Ensure the output directory exists. - string directory = Path.GetDirectoryName(outputPath); - if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) - { - Directory.CreateDirectory(directory); - } - - // Create the complex barcode generator with the Mailmark codetext. - using (var generator = new ComplexBarcodeGenerator(mailmark)) - { - // Optional: set barcode colors. - generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; - generator.Parameters.BackColor = Aspose.Drawing.Color.White; - - // Save the barcode image as PNG. - generator.Save(outputPath, BarCodeImageFormat.Png); - } - - // Return the path of the generated file. - return outputPath; - }); - } - - /// - /// Entry point. Prepares sample Mailmark data, generates barcodes asynchronously, and outputs file locations. - /// - /// Command‑line arguments (not used). - /// A task representing the asynchronous operation. - static async Task Main(string[] args) - { - // Prepare a list of sample Mailmark codetexts. - var mailmarks = new List(); - - // Sample 1 - var mailmark1 = new MailmarkCodetext - { - Format = 4, // Default/unspecified format + Format = 4, // 4‑state format VersionID = 1, - Class = "0", + Class = "0", // test class SupplychainID = 384224, ItemID = 16563762, - DestinationPostCodePlusDPS = "EF61AH8T " + DestinationPostCodePlusDPS = "EF61AH8T " // trailing space is required }; - mailmarks.Add(mailmark1); - // Sample 2 (different ItemID) - var mailmark2 = new MailmarkCodetext - { - Format = 4, - VersionID = 1, - Class = "0", - SupplychainID = 384224, - ItemID = 16563763, - DestinationPostCodePlusDPS = "EF61AH8T " - }; - mailmarks.Add(mailmark2); - - // Sample 3 (different ItemID) - var mailmark3 = new MailmarkCodetext - { - Format = 4, - VersionID = 1, - Class = "0", - SupplychainID = 384224, - ItemID = 16563764, - DestinationPostCodePlusDPS = "EF61AH8T " - }; - mailmarks.Add(mailmark3); + string outputPath = "mailmark.png"; - // Create tasks for asynchronous generation. - var tasks = new List>(); - int index = 1; - foreach (var mailmark in mailmarks) + // Generate the barcode on a background thread to avoid UI blocking + await Task.Run(() => { - // Build a unique file name for each barcode. - string fileName = $"mailmark_{index}.png"; - string outputPath = Path.Combine(Directory.GetCurrentDirectory(), fileName); - - // Queue the generation task. - tasks.Add(GenerateMailmarkAsync(mailmark, outputPath)); - index++; - } + // Initialize the complex barcode generator with the Mailmark data + using (var generator = new ComplexBarcodeGenerator(mailmark)) + { + // Optional visual settings + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; - // Await all generation tasks to complete. - string[] results = await Task.WhenAll(tasks); + // Save the generated image to a file + generator.Save(outputPath); + } + }); - // Output the locations of the generated barcode images. - foreach (var path in results) - { - Console.WriteLine($"Generated Mailmark barcode saved to: {path}"); - } + // Inform the user where the barcode image was saved + Console.WriteLine($"Mailmark barcode saved to {Path.GetFullPath(outputPath)}"); } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/implement-error-handling-to-catch-exceptions-when-barcode-generation-fails-due-to-invalid-codetext-characters.cs b/mailmark-four-state-barcode/implement-error-handling-to-catch-exceptions-when-barcode-generation-fails-due-to-invalid-codetext-characters.cs index d4e5d42..a29c1cf 100644 --- a/mailmark-four-state-barcode/implement-error-handling-to-catch-exceptions-when-barcode-generation-fails-due-to-invalid-codetext-characters.cs +++ b/mailmark-four-state-barcode/implement-error-handling-to-catch-exceptions-when-barcode-generation-fails-due-to-invalid-codetext-characters.cs @@ -1,53 +1,56 @@ -// Title: Barcode generation with error handling for invalid Code39 characters -// Description: Demonstrates how to generate a Code39 barcode and catch exceptions when the codetext contains characters not allowed by the symbology. -// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and exception handling for invalid codetext. Developers often need to validate input before creating barcodes; this snippet shows how to enable strict validation and handle errors gracefully, a common requirement when integrating barcode creation into applications. +// Title: Barcode Generation with Error Handling for Invalid Codetext +// Description: Demonstrates generating a Code39 barcode and handling errors when the codetext contains characters not allowed by the symbology. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator, set generation parameters, and implement robust exception handling. Developers often need to validate codetext before creating barcodes for printing, labeling, or inventory systems; this snippet illustrates typical use cases such as catching InvalidCodeException and other BarCodeException types. // Prompt: Implement error handling to catch exceptions when barcode generation fails due to invalid Codetext characters. -// Tags: code39, barcode generation, error handling, invalidcodetext, aspose.barcode, csharp +// Tags: barcode, code39, error handling, exception, generation, png, aspose.barcode using System; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates barcode generation with explicit error handling for invalid codetext characters. +/// Example program that generates a Code39 barcode and demonstrates error handling +/// for invalid codetext characters using Aspose.BarCode. /// class Program { /// - /// Entry point of the example. Generates a Code39 barcode and handles possible generation errors. + /// Entry point of the application. Generates a barcode, saves it to a PNG file, + /// and catches any exceptions related to invalid codetext or other generation errors. /// static void Main() { // Define the output file path for the generated barcode image. - string outputPath = "code39.png"; + const string outputPath = "code39.png"; - try + // Create a BarcodeGenerator for Code39 with an intentionally invalid character '@'. + using (var generator = new BarcodeGenerator(EncodeTypes.Code39, "ABC@123")) { - // Create a BarcodeGenerator with an intentionally invalid Code39 text ("@" is not allowed). - using (var generator = new BarcodeGenerator(EncodeTypes.Code39, "ABC@123")) - { - // Enable throwing an exception when the codetext does not conform to the symbology rules. - generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = true; + // Configure the generator to throw an exception when the codetext is incorrect. + generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = true; - // Attempt to save the barcode image to the specified path. - generator.Save(outputPath); - Console.WriteLine($"Barcode successfully saved to '{outputPath}'."); + try + { + // Attempt to save the barcode image to the specified path in PNG format. + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode generated successfully and saved to '{outputPath}'."); + } + catch (InvalidCodeException ex) + { + // Handles invalid characters in the codetext specific to the chosen symbology. + Console.WriteLine($"InvalidCodeException: {ex.Message}"); + } + catch (BarCodeException ex) + { + // Handles other barcode generation errors (e.g., configuration issues). + Console.WriteLine($"BarCodeException: {ex.Message}"); + } + catch (Exception ex) + { + // Handles any unexpected errors that may occur. + Console.WriteLine($"Unexpected error: {ex.Message}"); } - } - // Catch specific exception for invalid characters in the codetext. - catch (InvalidCodeException ex) - { - Console.WriteLine($"InvalidCodeException: {ex.Message}"); - } - // Catch other barcode generation related exceptions. - catch (BarCodeException ex) - { - Console.WriteLine($"BarCodeException: {ex.Message}"); - } - // Catch any unexpected exceptions. - catch (Exception ex) - { - Console.WriteLine($"Unexpected error: {ex.Message}"); } } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/implement-logging-of-decoding-failures-capturing-raw-image-path-and-exception-details-for-mailmark-troubleshooting.cs b/mailmark-four-state-barcode/implement-logging-of-decoding-failures-capturing-raw-image-path-and-exception-details-for-mailmark-troubleshooting.cs index c7cea2c..e04f9bb 100644 --- a/mailmark-four-state-barcode/implement-logging-of-decoding-failures-capturing-raw-image-path-and-exception-details-for-mailmark-troubleshooting.cs +++ b/mailmark-four-state-barcode/implement-logging-of-decoding-failures-capturing-raw-image-path-and-exception-details-for-mailmark-troubleshooting.cs @@ -1,113 +1,119 @@ -// Title: Mailmark barcode decoding with failure logging -// Description: Demonstrates how to decode Mailmark barcodes from images and log any decoding failures for troubleshooting. -// Category-Description: This example belongs to the Aspose.BarCode barcode decoding category, focusing on Mailmark symbology using BarCodeReader and ComplexCodetextReader. It shows typical use cases such as batch processing of images, handling missing files, empty results, and capturing detailed error information. Developers working with postal Mailmark codes often need robust logging to diagnose decoding issues in production environments. +// Title: Mailmark Barcode Decoding with Failure Logging +// Description: Demonstrates generating Mailmark barcodes, attempting to decode them, and logging any decoding failures including the image path and exception details. +// Category-Description: Shows how to use Aspose.BarCode's ComplexBarcodeGenerator to create Mailmark symbols and BarCodeReader to decode them. Typical use cases include batch processing of Mailmark images, error handling, and troubleshooting when decoding fails. Developers often need to capture raw image paths and exception information for diagnostics, which this example logs to a text file. // Prompt: Implement logging of decoding failures, capturing raw image path and exception details for Mailmark troubleshooting. -// Tags: mailmark, decoding, logging, console, barcodereader, complexcodetextreader, exception +// Tags: mailmark, barcode, decoding, logging, aspose.barcode, complexbarcode, barcodereader, image, exception handling using System; using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.BarCode.ComplexBarcode; +using Aspose.Drawing; +using Aspose.Drawing.Imaging; /// -/// Example program that reads Mailmark barcodes from a set of image files, -/// outputs successful decodings to the console, and logs any failures -/// (missing files, no detection, empty code text, or exceptions) for later analysis. +/// Example program that generates Mailmark barcodes, attempts to decode them, +/// and logs any decoding failures for troubleshooting purposes. /// class Program { /// - /// Entry point of the application. Iterates over predefined image paths, - /// attempts to decode Mailmark barcodes, and records any issues to a log file. + /// Entry point of the application. Generates sample barcodes, creates a non‑barcode image, + /// scans all PNG files in the working folder, and logs success or failure of each decode attempt. /// static void Main() { - // Define sample image paths (replace with actual paths as needed) - string[] imagePaths = { "mailmark1.png", "mailmark2.png" }; - string logPath = "decode_failures.log"; + // -------------------------------------------------------------------- + // Prepare working folder and log file + // -------------------------------------------------------------------- + string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(folderPath); - // Initialize the log file: create it if missing or clear existing content - using (var logWriter = new StreamWriter(logPath, false)) + string logPath = Path.Combine(folderPath, "decode_log.txt"); + if (!File.Exists(logPath)) { - logWriter.WriteLine($"Log started at {DateTime.Now}"); + File.WriteAllText(logPath, $"Decode Log - {DateTime.Now}{Environment.NewLine}"); } - // Process each image file individually - foreach (string imagePath in imagePaths) + // -------------------------------------------------------------------- + // Generate sample Mailmark barcode images (2 records) + // -------------------------------------------------------------------- + for (int i = 0; i < 2; i++) { - // Verify that the image file exists before attempting to read it - if (!File.Exists(imagePath)) + var mailmark = new MailmarkCodetext + { + Format = 4, // 4‑state Mailmark + VersionID = 1, + Class = "0", + SupplychainID = 384224, + ItemID = 16563762 + i, // vary ItemID to keep records unique + DestinationPostCodePlusDPS = "EF61AH8T " // trailing space required + }; + + using (var generator = new ComplexBarcodeGenerator(mailmark)) + { + string imagePath = Path.Combine(folderPath, $"mailmark_{i + 1}.png"); + generator.Save(imagePath, BarCodeImageFormat.Png); + } + } + + // -------------------------------------------------------------------- + // Create a non‑barcode image to force a decoding failure + // -------------------------------------------------------------------- + string nonBarcodePath = Path.Combine(folderPath, "nonbarcode.png"); + using (var bitmap = new Bitmap(200, 200)) + { + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.White); + } + bitmap.Save(nonBarcodePath, ImageFormat.Png); + } + + // -------------------------------------------------------------------- + // Scan folder for PNG images and attempt to decode each one + // -------------------------------------------------------------------- + string[] imageFiles = Directory.GetFiles(folderPath, "*.png"); + foreach (string imageFile in imageFiles) + { + // Defensive check: ensure the file still exists + if (!File.Exists(imageFile)) { - LogFailure("File not found", imagePath); continue; } try { - // Create a BarCodeReader configured for Mailmark decoding - using (var reader = new BarCodeReader(imagePath, DecodeType.Mailmark)) + using (var reader = new BarCodeReader(imageFile, DecodeType.Mailmark)) { - // Attempt to read all barcodes present in the image var results = reader.ReadBarCodes(); + bool anyFound = false; - // If no barcodes were detected, log the failure and move to the next image - if (results.Length == 0) + foreach (var result in results) { - LogFailure("No barcode detected", imagePath); - continue; + anyFound = true; + Console.WriteLine($"SUCCESS: {Path.GetFileName(imageFile)} -> {result.CodeText}"); } - // Iterate over each detected barcode result - foreach (var result in results) + if (!anyFound) { - // Ensure the detected barcode contains a non‑empty CodeText - if (string.IsNullOrEmpty(result.CodeText)) - { - LogFailure("Empty CodeText", imagePath); - continue; - } - - // Attempt to decode the Mailmark-specific codetext - var mailmark = ComplexCodetextReader.TryDecodeMailmark(result.CodeText); - if (mailmark == null) - { - // Decoding failed – log the raw CodeText for troubleshooting - LogFailure($"Failed to decode Mailmark codetext. Raw CodeText: {result.CodeText}", imagePath); - } - else - { - // Successful decode – output key fields to the console - Console.WriteLine($"Decoded Mailmark from '{imagePath}': ItemID={mailmark.ItemID}, DestinationPostCodePlusDPS='{mailmark.DestinationPostCodePlusDPS}'"); - } + string msg = $"No Mailmark barcode detected in '{imageFile}'."; + Console.WriteLine($"INFO: {msg}"); + File.AppendAllText(logPath, $"{DateTime.Now}: {msg}{Environment.NewLine}"); } } } catch (Exception ex) { - // Capture any unexpected exceptions and log detailed information - LogFailure($"Exception: {ex.GetType().Name}: {ex.Message}", imagePath, ex); + // Log decoding failure with image path and exception details + string error = $"Failed to decode '{imageFile}'. Exception: {ex.GetType().Name} - {ex.Message}"; + Console.WriteLine($"ERROR: {error}"); + File.AppendAllText(logPath, $"{DateTime.Now}: {error}{Environment.NewLine}"); } } - } - /// - /// Writes a failure message to the log file, optionally including exception details. - /// - /// Human‑readable description of the failure. - /// Path to the image that caused the failure. - /// Optional exception object providing stack trace information. - static void LogFailure(string message, string imagePath, Exception ex = null) - { - string logPath = "decode_failures.log"; - using (var logWriter = new StreamWriter(logPath, true)) - { - // Log timestamp, message, and image path - logWriter.WriteLine($"{DateTime.Now}: {message} - Image: {imagePath}"); - // If an exception is provided, log its stack trace for deeper analysis - if (ex != null) - { - logWriter.WriteLine($"StackTrace: {ex.StackTrace}"); - } - } + Console.WriteLine("Decoding process completed. See log file for details."); } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/instantiate-mailmarkcodetext-and-set-service-type-routing-code-and-customer-reference.cs b/mailmark-four-state-barcode/instantiate-mailmarkcodetext-and-set-service-type-routing-code-and-customer-reference.cs index 108375f..c9d0d7e 100644 --- a/mailmark-four-state-barcode/instantiate-mailmarkcodetext-and-set-service-type-routing-code-and-customer-reference.cs +++ b/mailmark-four-state-barcode/instantiate-mailmarkcodetext-and-set-service-type-routing-code-and-customer-reference.cs @@ -1,47 +1,45 @@ -// Title: Generate a Mailmark barcode with service type, routing code, and customer reference -// Description: Demonstrates how to create a Mailmark barcode by configuring its codetext fields and saving the result as a PNG image. -// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, illustrating the use of MailmarkCodetext with ComplexBarcodeGenerator. Developers working with postal and logistics solutions often need to encode service type, routing information, and customer references into Mailmark barcodes; this snippet shows the essential API classes and typical workflow for such scenarios. +// Title: Create Mailmark Codetext with Service Type, Routing Code, and Customer Reference +// Description: Demonstrates how to instantiate a MailmarkCodetext object, set its service type, routing code, and customer reference, and retrieve the constructed codetext string. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on Mailmark symbology. It showcases the MailmarkCodetext class, which is used to build Mailmark codetext strings required for postal services. Developers working with Mailmark often need to configure service type, routing information, and customer references before encoding the barcode. // Prompt: Instantiate a MailmarkCodetext and set service type, routing code, and customer reference. -// Tags: mailmark, barcode, complexbarcode, generation, png, aspnet, aspnetcore, csharp +// Tags: mailmark, barcode, codetext, service-type, routing-code, customer-reference, aspose.barcode, complexbarcode using System; -using System.IO; -using Aspose.BarCode; using Aspose.BarCode.ComplexBarcode; -using Aspose.BarCode.Generation; -namespace MailmarkExample +/// +/// Example program that builds a Mailmark codetext using Aspose.BarCode. +/// +class Program { /// - /// Demonstrates creating and saving a Mailmark barcode using Aspose.BarCode. + /// Entry point that creates a MailmarkCodetext, configures required fields, and prints the resulting codetext. /// - class Program + static void Main() { - /// - /// Entry point. Configures MailmarkCodetext, generates the barcode, and saves it as PNG. - /// - static void Main() - { - // Instantiate MailmarkCodetext and set required fields - var mailmark = new MailmarkCodetext(); - mailmark.Format = 4; // 4-state barcode format - mailmark.VersionID = 1; - mailmark.Class = "0"; // service type - mailmark.SupplychainID = 384224; // routing code - mailmark.ItemID = 16563762; // customer reference - mailmark.DestinationPostCodePlusDPS = "EF61AH8T "; // required postcode+DP - - // Create ComplexBarcodeGenerator with the Mailmark codetext - using (var generator = new ComplexBarcodeGenerator(mailmark)) - { - // Generate the barcode image - generator.GenerateBarCodeImage(); - - // Save the barcode to a PNG file - string outputPath = "mailmark.png"; - generator.Save(outputPath, BarCodeImageFormat.Png); - Console.WriteLine($"Mailmark barcode saved to {Path.GetFullPath(outputPath)}"); - } - } + // Instantiate a new MailmarkCodetext object. + var mailmark = new MailmarkCodetext(); + + // Set the Mailmark format (4-state format). + mailmark.Format = 4; + + // Set the version identifier. + mailmark.VersionID = 1; + + // Set the service type (Class) as a string. + mailmark.Class = "0"; + + // Set the supply chain identifier. + mailmark.SupplychainID = 384224; + + // Set the customer reference (ItemID) as an integer. + mailmark.ItemID = 16563762; + + // Set the routing code (DestinationPostCodePlusDPS) with required trailing space. + mailmark.DestinationPostCodePlusDPS = "EF61AH8T "; + + // Output the constructed Mailmark codetext to the console. + Console.WriteLine("Constructed Mailmark codetext:"); + Console.WriteLine(mailmark.GetConstructedCodetext()); } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/integrate-mailmark-barcode-generation-into-aspnet-mvc-view-rendering-image-directly-via-data-uri.cs b/mailmark-four-state-barcode/integrate-mailmark-barcode-generation-into-aspnet-mvc-view-rendering-image-directly-via-data-uri.cs index 43eb86c..bc4284d 100644 --- a/mailmark-four-state-barcode/integrate-mailmark-barcode-generation-into-aspnet-mvc-view-rendering-image-directly-via-data-uri.cs +++ b/mailmark-four-state-barcode/integrate-mailmark-barcode-generation-into-aspnet-mvc-view-rendering-image-directly-via-data-uri.cs @@ -1,54 +1,54 @@ // Title: Generate Mailmark Barcode and Output as Data URI -// Description: Demonstrates creating a Mailmark 4‑state barcode with Aspose.BarCode and converting it to a Base64 data URI for direct embedding in HTML. -// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator and MailmarkCodetext to produce Mailmark barcodes, a common requirement for postal automation. Developers often need to render such barcodes in web applications, typically embedding the image via a data URI in MVC views or other HTML contexts. +// Description: Demonstrates creating a Mailmark barcode using Aspose.BarCode, encoding the PNG image as a Base64 data URI for direct embedding in an ASP.NET MVC view. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as Mailmark. It shows how to use ComplexBarcodeGenerator and MailmarkCodetext classes to produce a barcode image, then convert it to a data URI for web rendering. Developers working with ASP.NET MVC or other web frameworks can embed the generated URI directly in HTML tags, avoiding file I/O. // Prompt: Integrate Mailmark barcode generation into an ASP.NET MVC view, rendering the image directly via data URI. -// Tags: mailmark, barcode, generation, png, data uri, aspnet mvc, aspose.barcode +// Tags: mailmark, barcode, generation, data uri, aspnet mvc, png, aspose.barcode, complexbarcode using System; using System.IO; -using Aspose.BarCode.ComplexBarcode; +using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.BarCode.ComplexBarcode; /// -/// Example program that creates a Mailmark 4‑state barcode and prints a Base64 data URI. +/// Example program that creates a Mailmark barcode and prints a Base64 data URI. /// class Program { /// - /// Entry point of the console application. Generates the barcode, encodes it as a data URI, - /// and writes the result to the console for use in an MVC view. + /// Entry point. Generates the barcode, converts it to a data URI, and writes it to the console. /// static void Main() { - // Prepare Mailmark 4‑state codetext with valid sample values. + // NOTE: In a real ASP.NET MVC application the generated data URI would be embedded in a view. + // The snippet runner is a console application, so we output the data URI to the console. + + // Create a MailmarkCodetext instance with valid sample data. var mailmark = new MailmarkCodetext { - Format = 4, // 4‑state format - VersionID = 1, // version - Class = "0", // service type / class - SupplychainID = 384224, // routing code - ItemID = 16563762, // customer reference - DestinationPostCodePlusDPS = "EF61AH8T " // postcode + DPS + Format = 4, // 4‑state Mailmark + VersionID = 1, + Class = "0", + SupplychainID = 384224, + ItemID = 16563762, + DestinationPostCodePlusDPS = "EF61AH8T " // trailing space is required }; - // Generate the barcode using ComplexBarcodeGenerator. - using (var generator = new ComplexBarcodeGenerator(mailmark)) + // Generate the barcode image into a memory stream. + using (var ms = new MemoryStream()) { - // Optional: set image resolution. - generator.Parameters.Resolution = 300; - - // Save the barcode to a memory stream in PNG format. - using (var ms = new MemoryStream()) + // Use ComplexBarcodeGenerator to render the Mailmark barcode. + using (var generator = new ComplexBarcodeGenerator(mailmark)) { generator.Save(ms, BarCodeImageFormat.Png); + } - // Convert the image bytes to a Base64 data URI. - string base64 = Convert.ToBase64String(ms.ToArray()); - string dataUri = $"data:image/png;base64,{base64}"; + // Convert the image bytes to a Base64 data URI. + string base64 = Convert.ToBase64String(ms.ToArray()); + string dataUri = "data:image/png;base64," + base64; - // Output the data URI; it can be used directly in an tag. - Console.WriteLine(dataUri); - } + // Output the data URI (can be used directly in an tag). + Console.WriteLine(dataUri); } } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/load-barcode-image-from-network-stream-decode-it-and-verify-service-type-matches-expected-value.cs b/mailmark-four-state-barcode/load-barcode-image-from-network-stream-decode-it-and-verify-service-type-matches-expected-value.cs index 8f1b12d..f3eebcf 100644 --- a/mailmark-four-state-barcode/load-barcode-image-from-network-stream-decode-it-and-verify-service-type-matches-expected-value.cs +++ b/mailmark-four-state-barcode/load-barcode-image-from-network-stream-decode-it-and-verify-service-type-matches-expected-value.cs @@ -1,81 +1,75 @@ -// Title: Decode Barcode from Network Stream and Verify Service Type -// Description: Downloads a barcode image via HTTP, decodes it using Aspose.BarCode, and checks that the decoded text matches an expected service identifier. -// Category-Description: This example belongs to the Aspose.BarCode recognition category, demonstrating how to use BarCodeReader with DecodeType.AllSupportedTypes to read barcodes from streams. Typical scenarios include processing images received over a network, validating embedded data, and integrating barcode verification into web services. Developers often need to download image data, feed it to the reader, and compare the decoded value against business rules. +// Title: Decode Barcode from Network Stream and Verify Type +// Description: Demonstrates downloading a barcode image via HTTP, decoding it with Aspose.BarCode, and checking that the detected symbology matches an expected value. +// Category-Description: This example belongs to the Aspose.BarCode decoding category, showcasing how to use BarCodeReader with DecodeType.AllSupportedTypes to read barcodes from streams. Typical scenarios include processing images received over a network, validating barcode types in automated workflows, and integrating barcode verification into web services. Developers often need to download image data, invoke the reader, and compare the resulting CodeTypeName against business rules. // Prompt: Load a barcode image from a network stream, decode it, and verify service type matches expected value. -// Tags: barcode, decoding, http, network, verification, aspose.barcode, csharp +// Tags: barcode, decode, network, http, aspose.barcode, barcodereader using System; using System.IO; using System.Net.Http; -using System.Threading.Tasks; +using Aspose.BarCode; using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates loading a barcode image from a network stream, decoding it, -/// and verifying that the decoded text matches an expected service type. +/// Example program that downloads a barcode image, decodes it, and validates the detected symbology. /// class Program { - // Expected service type that should be encoded in the barcode - private const string ExpectedServiceType = "MyService"; - /// - /// Entry point of the example. Downloads the barcode image, decodes it, - /// and validates the decoded text against . + /// Entry point of the example. /// - /// Command‑line arguments (not used). - static async Task Main(string[] args) + static void Main() { - // URL of the barcode image (replace with a real URL when testing) + // URL of the barcode image to download. const string imageUrl = "https://example.com/barcode.png"; - // Create an HttpClient to download the image + // Expected barcode type name (e.g., "Code128", "QR", etc.). + const string expectedCodeType = "Code128"; + + // Create an HttpClient to download the image via HTTP. using (var httpClient = new HttpClient()) - // Request the image data with response headers read first - using (var response = await httpClient.GetAsync(imageUrl, HttpCompletionOption.ResponseHeadersRead)) { - // Ensure the request succeeded - if (!response.IsSuccessStatusCode) + // Send a GET request and wait synchronously for the response. + using (var response = httpClient.GetAsync(imageUrl).Result) { - Console.WriteLine($"Failed to download image. Status code: {response.StatusCode}"); - return; - } - - // Obtain the network stream containing the image bytes - using (var networkStream = await response.Content.ReadAsStreamAsync()) - // Copy the network stream into a memory stream for random access - using (var memoryStream = new MemoryStream()) - { - await networkStream.CopyToAsync(memoryStream); - memoryStream.Position = 0; // Reset position to the beginning for reading - - // Initialize the barcode reader with the image stream and detect all supported types - using (var reader = new BarCodeReader(memoryStream, DecodeType.AllSupportedTypes)) + // Verify the request succeeded. + if (!response.IsSuccessStatusCode) { - // Perform recognition and retrieve all detected barcodes - BarCodeResult[] results = reader.ReadBarCodes(); - - // If no barcodes were found, inform the user and exit - if (results.Length == 0) - { - Console.WriteLine("No barcode detected in the image."); - return; - } + Console.WriteLine($"Failed to download image. HTTP status: {response.StatusCode}"); + return; + } - // Process each detected barcode (normally there will be only one) - foreach (var result in results) + // Obtain the response content as a stream. + using (var imageStream = response.Content.ReadAsStreamAsync().Result) + { + // Initialize BarCodeReader with the image stream and enable all supported barcode types. + using (var reader = new BarCodeReader(imageStream, DecodeType.AllSupportedTypes)) { - Console.WriteLine($"Detected Type: {result.CodeTypeName}"); - Console.WriteLine($"Decoded Text: {result.CodeText}"); + // Read all barcodes found in the image. + var results = reader.ReadBarCodes(); - // Verify that the decoded text matches the expected service type - if (string.Equals(result.CodeText, ExpectedServiceType, StringComparison.OrdinalIgnoreCase)) + // Check if any barcodes were detected. + if (results == null || results.Length == 0) { - Console.WriteLine("Verification succeeded: service type matches expected value."); + Console.WriteLine("No barcode detected in the image."); + return; } - else + + // Iterate through each detected barcode. + foreach (var result in results) { - Console.WriteLine($"Verification failed: expected '{ExpectedServiceType}' but got '{result.CodeText}'."); + Console.WriteLine($"Detected barcode type: {result.CodeTypeName}"); + Console.WriteLine($"Decoded text: {result.CodeText}"); + + // Compare the detected type with the expected value (case‑insensitive). + if (string.Equals(result.CodeTypeName, expectedCodeType, StringComparison.OrdinalIgnoreCase)) + { + Console.WriteLine("Service type matches the expected value."); + } + else + { + Console.WriteLine($"Service type mismatch. Expected: {expectedCodeType}"); + } } } } diff --git a/mailmark-four-state-barcode/parse-raw-codetext-from-barcodereader-using-complexcodetextreadertrydecodemailmark-to-retrieve-fields.cs b/mailmark-four-state-barcode/parse-raw-codetext-from-barcodereader-using-complexcodetextreadertrydecodemailmark-to-retrieve-fields.cs index 4dc3f29..de64464 100644 --- a/mailmark-four-state-barcode/parse-raw-codetext-from-barcodereader-using-complexcodetextreadertrydecodemailmark-to-retrieve-fields.cs +++ b/mailmark-four-state-barcode/parse-raw-codetext-from-barcodereader-using-complexcodetextreadertrydecodemailmark-to-retrieve-fields.cs @@ -1,91 +1,80 @@ // Title: Parse Mailmark CodeText with ComplexCodetextReader -// Description: Demonstrates generating a Mailmark barcode, reading its raw CodeText, and decoding it into individual fields using ComplexCodetextReader.TryDecodeMailmark. -// Category-Description: This example belongs to the Aspose.BarCode complex barcode handling category, focusing on Mailmark symbology. It shows how to use ComplexBarcodeGenerator to create a Mailmark barcode, BarCodeReader to scan it, and ComplexCodetextReader to parse the raw CodeText into structured MailmarkCodetext fields. Developers working with postal or logistics applications often need to generate and decode Mailmark barcodes to exchange supply‑chain information. +// Description: Demonstrates how to generate a Mailmark barcode, read it, and decode the raw CodeText using ComplexCodetextReader.TryDecodeMailmark to extract individual fields. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode operations collection. It showcases the use of ComplexBarcodeGenerator to create a Mailmark barcode, BarCodeReader to recognize the barcode, and ComplexCodetextReader to parse the encoded data. Typical scenarios include logistics and postal applications where Mailmark symbology is used to embed structured information. Developers often need to generate, read, and decode such barcodes to integrate with tracking systems. // Prompt: Parse raw CodeText from BarCodeReader using ComplexCodetextReader.TryDecodeMailmark to retrieve fields. -// Tags: mailmark, barcode, decoding, complexcodetextreader, aspnet, csharp, aspose.barcode +// Tags: mailmark, barcode, decoding, complexcodetext, aspose.barcode, c#, generation, recognition using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.BarCode.ComplexBarcode; -using Aspose.Drawing.Imaging; /// -/// Example program that creates a Mailmark barcode, reads it back, and decodes the raw CodeText -/// into its constituent fields using . +/// Example program that generates a Mailmark barcode, reads it, and decodes its raw CodeText +/// using to retrieve individual fields. /// class Program { /// - /// Entry point of the example. Generates a Mailmark barcode image, reads the barcode, - /// decodes the raw CodeText, and outputs the extracted fields to the console. + /// Entry point of the example. Generates a Mailmark barcode, reads it from a memory stream, + /// and outputs the decoded fields to the console. /// static void Main() { - // Define a temporary file path for the generated barcode image - string imagePath = Path.Combine(Directory.GetCurrentDirectory(), "mailmark.png"); - - // Create and populate a MailmarkCodetext instance with required fields + // Create a sample Mailmark codetext object with valid values. var mailmark = new MailmarkCodetext { - Format = 4, // unspecified/default format + Format = 4, // Mailmark 4‑state format VersionID = 1, Class = "0", SupplychainID = 384224, ItemID = 16563762, - DestinationPostCodePlusDPS = "EF61AH8T " + DestinationPostCodePlusDPS = "EF61AH8T " // trailing space is required }; - // Generate the Mailmark barcode image and save it to the temporary file - using (var generator = new ComplexBarcodeGenerator(mailmark)) - { - generator.Save(imagePath, BarCodeImageFormat.Png); - } - - // Verify that the image file was successfully created - if (!File.Exists(imagePath)) + // Generate the barcode image into a memory stream. + using (var imageStream = new MemoryStream()) { - Console.WriteLine($"Failed to create barcode image at '{imagePath}'."); - return; - } + // Use ComplexBarcodeGenerator to encode the Mailmark data. + using (var generator = new ComplexBarcodeGenerator(mailmark)) + { + generator.Save(imageStream, BarCodeImageFormat.Png); + imageStream.Position = 0; // Reset stream position for reading. + } - // Read the barcode from the saved image using the Mailmark decode type - using (var reader = new BarCodeReader(imagePath, DecodeType.Mailmark)) - { - foreach (var result in reader.ReadBarCodes()) + // Read the barcode from the generated image. + using (var reader = new BarCodeReader(imageStream, DecodeType.Mailmark)) { - // Output the raw CodeText obtained from the barcode - Console.WriteLine($"Raw CodeText: {result.CodeText}"); + var results = reader.ReadBarCodes(); - // Decode the raw CodeText into a structured MailmarkCodetext object - MailmarkCodetext decoded = ComplexCodetextReader.TryDecodeMailmark(result.CodeText); - if (decoded == null) + // Verify that at least one barcode was detected. + if (results.Length == 0) { - Console.WriteLine("Unable to decode Mailmark codetext."); - continue; + Console.WriteLine("No barcode detected."); + return; } - // Output each decoded field to the console - Console.WriteLine("Decoded Mailmark fields:"); - Console.WriteLine($" Format: {decoded.Format}"); - Console.WriteLine($" VersionID: {decoded.VersionID}"); - Console.WriteLine($" Class: {decoded.Class}"); - Console.WriteLine($" SupplychainID: {decoded.SupplychainID}"); - Console.WriteLine($" ItemID: {decoded.ItemID}"); - Console.WriteLine($" DestinationPostCodePlusDPS: {decoded.DestinationPostCodePlusDPS}"); - } - } + // Process each detected barcode. + foreach (var result in results) + { + // Decode the raw CodeText using ComplexCodetextReader. + var decoded = ComplexCodetextReader.TryDecodeMailmark(result.CodeText); + if (decoded == null) + { + Console.WriteLine("Failed to decode Mailmark codetext."); + continue; + } - // Clean up the temporary image file - try - { - File.Delete(imagePath); - } - catch - { - // Ignore any errors that occur during cleanup + // Output the extracted fields. + Console.WriteLine($"Format: {decoded.Format}"); + Console.WriteLine($"VersionID: {decoded.VersionID}"); + Console.WriteLine($"Class: {decoded.Class}"); + Console.WriteLine($"SupplychainID: {decoded.SupplychainID}"); + Console.WriteLine($"ItemID: {decoded.ItemID}"); + Console.WriteLine($"DestinationPostCodePlusDPS: \"{decoded.DestinationPostCodePlusDPS}\""); + } + } } } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/read-mailmark-barcode-from-jpeg-stream-using-barcodereader-with-decodetypemailmark.cs b/mailmark-four-state-barcode/read-mailmark-barcode-from-jpeg-stream-using-barcodereader-with-decodetypemailmark.cs index e78df8c..97c95eb 100644 --- a/mailmark-four-state-barcode/read-mailmark-barcode-from-jpeg-stream-using-barcodereader-with-decodetypemailmark.cs +++ b/mailmark-four-state-barcode/read-mailmark-barcode-from-jpeg-stream-using-barcodereader-with-decodetypemailmark.cs @@ -1,53 +1,63 @@ -// Title: Read Mailmark Barcode from JPEG Stream -// Description: Demonstrates how to read a Mailmark barcode from a JPEG image using Aspose.BarCode's BarCodeReader with DecodeType.Mailmark. -// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing the use of BarCodeReader and DecodeType to detect and decode specific symbologies. Typical use cases include processing scanned documents, images, or streams to extract Mailmark data for postal automation or tracking. Developers often need to read barcodes from various image formats, handle missing files, and retrieve detailed decoding information such as confidence and region. +// Title: Read Mailmark barcode from an image stream using BarCodeReader +// Description: Demonstrates generating a Mailmark barcode, saving it to a memory stream, and decoding it with BarCodeReader using DecodeType.Mailmark. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It showcases the use of ComplexBarcodeGenerator for creating Mailmark barcodes and BarCodeReader for decoding them. Developers working with postal services, logistics, or any application that requires Mailmark symbology can refer to this pattern for generating and reading Mailmark codes in .NET. // Prompt: Read a Mailmark barcode from a JPEG stream using BarCodeReader with DecodeType.Mailmark. -// Tags: mailmark, barcode, read, jpeg, stream, aspose.barcode, barcodereader +// Tags: mailmark, barcode, generation, recognition, decode, c#, aspose.barcode using System; using System.IO; -using Aspose.BarCode; +using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; +using Aspose.BarCode.ComplexBarcode; /// -/// Example program that reads a Mailmark barcode from a JPEG image stream using Aspose.BarCode. +/// Example program that creates a Mailmark barcode, stores it in a memory stream, +/// and reads it back using with . /// class Program { /// - /// Entry point of the application. Opens a JPEG file, decodes any Mailmark barcodes, and prints their details. + /// Entry point of the example. Generates a Mailmark barcode, writes it to a stream, + /// then decodes the barcode from the same stream and prints the result. /// static void Main() { - // Path to the JPEG image containing the Mailmark barcode - const string imagePath = "mailmark.jpg"; - - // Verify that the image file exists before attempting to read it - if (!File.Exists(imagePath)) + // Create a valid Mailmark codetext object with required fields. + var mailmark = new MailmarkCodetext { - Console.WriteLine($"File not found: {imagePath}"); - return; - } + Format = 4, // 4‑state Mailmark + VersionID = 1, + Class = "0", + SupplychainID = 384224, + ItemID = 16563762, + DestinationPostCodePlusDPS = "EF61AH8T " // trailing space is required + }; - // Open the image file as a read‑only stream and create a BarCodeReader configured for Mailmark decoding - using (FileStream imageStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read)) - using (BarCodeReader reader = new BarCodeReader(imageStream, DecodeType.Mailmark)) + // Generate the Mailmark barcode image into a memory stream. + using (var barcodeStream = new MemoryStream()) { - // Iterate through all detected barcodes in the image - foreach (var result in reader.ReadBarCodes()) + // Use ComplexBarcodeGenerator to create the barcode image. + using (var generator = new ComplexBarcodeGenerator(mailmark)) { - // Output basic information about each detected Mailmark barcode - Console.WriteLine($"Barcode Type: {result.CodeTypeName}"); - Console.WriteLine($"Code Text: {result.CodeText}"); - Console.WriteLine($"Confidence: {result.Confidence}"); - Console.WriteLine($"Reading Quality: {result.ReadingQuality}"); - Console.WriteLine($"Region: {result.Region.Rectangle}"); + // Save the generated barcode as PNG into the stream. + generator.Save(barcodeStream, BarCodeImageFormat.Png); } - // If no barcodes were found, inform the user - if (reader.FoundCount == 0) + // Reset the stream position to the beginning before reading. + barcodeStream.Position = 0; + + // Set the decode type to Mailmark for the reader. + BaseDecodeType decodeType = DecodeType.Mailmark; + + // Initialize BarCodeReader with the stream and specified decode type. + using (var reader = new BarCodeReader(barcodeStream, decodeType)) { - Console.WriteLine("No Mailmark barcode detected in the image."); + // Iterate through all detected barcodes (should be one in this case). + foreach (var result in reader.ReadBarCodes()) + { + // Output the decoded Mailmark CodeText to the console. + Console.WriteLine($"Detected Mailmark CodeText: {result.CodeText}"); + } } } } diff --git a/mailmark-four-state-barcode/set-barcode-foreground-to-blue-and-background-to-white-before-generating-image.cs b/mailmark-four-state-barcode/set-barcode-foreground-to-blue-and-background-to-white-before-generating-image.cs index 904b049..bc188db 100644 --- a/mailmark-four-state-barcode/set-barcode-foreground-to-blue-and-background-to-white-before-generating-image.cs +++ b/mailmark-four-state-barcode/set-barcode-foreground-to-blue-and-background-to-white-before-generating-image.cs @@ -1,38 +1,54 @@ // Title: Generate Code128 barcode with custom colors -// Description: Demonstrates setting the barcode foreground to blue and background to white before saving as an image. -// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to customize visual appearance using BarcodeGenerator, EncodeTypes, and color properties. Developers often need to adjust bar and background colors for branding or readability when creating PNG, JPEG, or PDF barcode outputs. +// Description: Demonstrates how to create a Code128 barcode image with a blue foreground and white background using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure visual properties such as bar color and background color before rendering. It showcases the BarcodeGenerator class, its Parameters property, and common use cases like customizing barcode appearance for branding or readability. Developers often need to adjust colors, sizes, and formats when integrating barcodes into documents, labels, or web pages. // Prompt: Set barcode foreground to blue and background to white before generating the image. -// Tags: code128, color, foreground, background, png, aspose.barcode, generation +// Tags: code128, color, png, generation, barcodegenerator, parameters using System; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; -/// -/// Example program that creates a Code128 barcode with custom foreground and background colors. -/// -class Program +namespace BarcodeSample { /// - /// Entry point. Generates the barcode image and saves it to disk. + /// Provides an entry point that generates a Code128 barcode image with custom colors. /// - static void Main() + class Program { - // Initialize a BarcodeGenerator for Code128 symbology with the desired text. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + /// + /// Generates a barcode, applies blue foreground and white background, and saves it as a PNG file. + /// + static void Main() { - // Set the barcode bars (foreground) to blue. - generator.Parameters.Barcode.BarColor = Color.Blue; + // Define the output file path for the generated barcode image. + string outputPath = "barcode.png"; - // Set the image background to white. - generator.Parameters.BackColor = Color.White; + // Ensure a clean start by deleting any existing file with the same name. + if (File.Exists(outputPath)) + { + File.Delete(outputPath); + } - // Save the generated barcode as a PNG file. - generator.Save("barcode.png"); - } + // Initialize the barcode generator for the Code128 symbology. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) + { + // Specify the text that the barcode will encode. + generator.CodeText = "123456"; + + // Set the barcode's foreground (bars) color to blue. + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Blue; + + // Set the image background color to white. + generator.Parameters.BackColor = Aspose.Drawing.Color.White; - // Inform the user that the image has been saved. - Console.WriteLine("Barcode image saved as barcode.png"); + // Render and save the barcode image in PNG format. + generator.Save(outputPath, BarCodeImageFormat.Png); + } + + // Output the full path of the saved barcode image for verification. + Console.WriteLine($"Barcode image saved to {Path.GetFullPath(outputPath)}"); + } } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/set-complexbarcodegenerator-errorcorrectionlevel-to-maximum-to-boost-reed-solomon-redundancy-for-low-quality-prints.cs b/mailmark-four-state-barcode/set-complexbarcodegenerator-errorcorrectionlevel-to-maximum-to-boost-reed-solomon-redundancy-for-low-quality-prints.cs index 3d78d5d..e5fabcc 100644 --- a/mailmark-four-state-barcode/set-complexbarcodegenerator-errorcorrectionlevel-to-maximum-to-boost-reed-solomon-redundancy-for-low-quality-prints.cs +++ b/mailmark-four-state-barcode/set-complexbarcodegenerator-errorcorrectionlevel-to-maximum-to-boost-reed-solomon-redundancy-for-low-quality-prints.cs @@ -1,50 +1,50 @@ -// Title: Generate Swiss QR Bill barcode with maximum Reed‑Solomon error correction -// Description: Demonstrates how to create a Swiss QR Bill barcode and set the QR error correction level to the highest (Level H) to improve readability on low‑quality prints. -// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on QR code creation for financial documents. It showcases the use of ComplexBarcodeGenerator, SwissQRCodetext, and QR error‑correction settings, which are common tasks for developers implementing payment QR codes, invoices, or other high‑density data barcodes. +// Title: Generate Swiss QR Code with Maximum Reed‑Solomon Error Correction +// Description: Demonstrates how to create a Swiss QR bill barcode and set the QR error correction level to the highest (Level H) to improve readability on low‑quality prints. +// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It shows usage of ComplexBarcodeGenerator, SwissQRCodetext, and QR parameters to produce a Swiss QR bill image. Developers working with payment QR codes often need to adjust error correction levels, colors, and output formats, making this a common pattern in financial and invoicing applications. // Prompt: Set ComplexBarcodeGenerator ErrorCorrectionLevel to maximum to boost Reed‑Solomon redundancy for low‑quality prints. -// Tags: swiss qr, barcode generation, error correction, qr, complexbarcode, aspnet, aspnetcore, aspnet5, aspose.barcode +// Tags: swiss qr, error correction, png, complexbarcodegenerator, swissqrcodetext, barcode generation using System; -using Aspose.BarCode.ComplexBarcode; +using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.BarCode.ComplexBarcode; +using Aspose.Drawing; /// -/// Entry point for the Swiss QR Bill barcode generation example. +/// Example program that creates a Swiss QR bill barcode with maximum error correction. /// class Program { /// - /// Generates a Swiss QR Bill barcode with maximum QR error correction (Level H) and saves it as an image. + /// Entry point. Builds the Swiss QR codetext, configures the generator, and saves the image. /// static void Main() { - // Prepare Swiss QR codetext with mandatory fields + // Prepare Swiss QR codetext with required fields var swissQr = new SwissQRCodetext(); - - // Set creditor details swissQr.Bill.Creditor.Name = "John Doe"; swissQr.Bill.Creditor.CountryCode = "CH"; - - // Set account number (IBAN) swissQr.Bill.Account = "CH9300762011623852957"; - - // Set payment amount swissQr.Bill.Amount = 199.95m; - - // Use QR Bill standard version 2.0 swissQr.Bill.Version = SwissQRBill.QrBillStandardVersion.V2_0; - // Create ComplexBarcodeGenerator and configure maximum QR error correction (Level H) + // Create ComplexBarcodeGenerator for the Swiss QR codetext using (var generator = new ComplexBarcodeGenerator(swissQr)) { - // Set Reed‑Solomon error correction to the highest level + // Set maximum Reed‑Solomon error correction (Level H) for QR part generator.Parameters.Barcode.QR.ErrorLevel = QRErrorLevel.LevelH; - // Save the generated barcode image to a PNG file - generator.Save("SwissQR.png"); - } + // Optional: set colors for better visibility + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; - // Inform the user that the barcode has been generated - Console.WriteLine("Swiss QR barcode generated with maximum error correction."); + // Save the generated barcode image as PNG + string outputPath = "SwissQR_MaxError.png"; + generator.Save(outputPath, BarCodeImageFormat.Png); + + // Inform the user where the file was saved + Console.WriteLine($"Barcode saved to {Path.GetFullPath(outputPath)}"); + } } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/test-barcode-readability-after-applying-gaussian-blur-to-generated-image-to-simulate-printing-defects.cs b/mailmark-four-state-barcode/test-barcode-readability-after-applying-gaussian-blur-to-generated-image-to-simulate-printing-defects.cs index 0be4311..b508863 100644 --- a/mailmark-four-state-barcode/test-barcode-readability-after-applying-gaussian-blur-to-generated-image-to-simulate-printing-defects.cs +++ b/mailmark-four-state-barcode/test-barcode-readability-after-applying-gaussian-blur-to-generated-image-to-simulate-printing-defects.cs @@ -1,57 +1,110 @@ -// Title: Test barcode readability after Gaussian blur -// Description: Generates a Code128 barcode, applies a 3x3 Gaussian blur to simulate printing defects, and attempts to read the blurred image. -// Category-Description: Demonstrates Aspose.BarCode generation, image manipulation with Aspose.Drawing, and barcode recognition using BarCodeReader. This example shows how to create a barcode, modify its image to mimic real‑world damage, and use high‑quality decoding settings—common tasks for developers testing robustness of barcode scanning solutions. +// Title: Gaussian Blur Effect on Barcode Readability +// Description: Generates a Code128 barcode, applies a Gaussian blur to simulate printing defects, and attempts to read the blurred barcode. +// Category-Description: This example demonstrates Aspose.BarCode generation and recognition workflows. It uses BarcodeGenerator to create a barcode image, Aspose.Drawing for image manipulation, and BarCodeReader to decode the result. Typical scenarios include testing barcode robustness against printing imperfections, image processing pipelines, and quality assurance of barcode scanning systems. // Prompt: Test barcode readability after applying Gaussian blur to the generated image to simulate printing defects. -// Tags: code128, barcode generation, gaussian blur, image processing, barcode recognition, highquality, aspose.barcode, aspose.drawing +// Tags: code128, barcode generation, barcode recognition, gaussian blur, image processing, 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; /// -/// Demonstrates generating a barcode, applying Gaussian blur, and reading the blurred barcode. +/// Demonstrates generating a barcode, applying a Gaussian blur, and reading the blurred image. /// class Program { /// - /// Applies a simple 3x3 Gaussian blur to the source bitmap. + /// Entry point of the example. Generates a Code128 barcode, blurs it, and attempts to decode it. /// - /// The original bitmap to blur. - /// A new bitmap containing the blurred image. - static Bitmap ApplyGaussianBlur(Bitmap source) + static void Main() + { + // Create a Code128 barcode with the value "123456" + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + { + // Save the barcode image to a memory stream in PNG format + using (var originalStream = new MemoryStream()) + { + generator.Save(originalStream, BarCodeImageFormat.Png); + originalStream.Position = 0; // Reset stream position for reading + + // Load the PNG image into a Bitmap for processing + using (var originalBitmap = (Bitmap)Image.FromStream(originalStream)) + { + // Apply a simple 3x3 Gaussian blur to simulate printing defects + using (var blurredBitmap = ApplyGaussianBlur(originalBitmap)) + { + // Store the blurred image in another memory stream + using (var blurredStream = new MemoryStream()) + { + blurredBitmap.Save(blurredStream, ImageFormat.Png); + blurredStream.Position = 0; // Reset for barcode reading + + // Initialize a barcode reader that supports all barcode types + using (var reader = new BarCodeReader(blurredStream, DecodeType.AllSupportedTypes)) + { + // Allow detection of slightly damaged or imperfect barcodes + reader.QualitySettings.AllowIncorrectBarcodes = true; + + bool found = false; + // Iterate through all detected barcodes in the blurred image + foreach (var result in reader.ReadBarCodes()) + { + Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}"); + Console.WriteLine($"Detected Code Text: {result.CodeText}"); + found = true; + } + + if (!found) + { + Console.WriteLine("No barcode could be detected in the blurred image."); + } + } + } + } + } + } + } + } + + // Simple 3x3 Gaussian blur implementation (kernel 1 2 1 / 2 4 2 / 1 2 1) + private static Bitmap ApplyGaussianBlur(Bitmap source) { int width = source.Width; int height = source.Height; - Bitmap blurred = new Bitmap(width, height); + var blurred = new Bitmap(width, height); - // Gaussian kernel 3x3 + // Kernel weights for Gaussian blur int[,] kernel = new int[,] { { 1, 2, 1 }, { 2, 4, 2 }, { 1, 2, 1 } }; - int kernelSum = 16; + int divisor = 16; - // Convolve kernel over interior pixels + // Process interior pixels (exclude edges) for (int y = 1; y < height - 1; y++) { for (int x = 1; x < width - 1; x++) { - int r = 0, g = 0, b = 0; + int sumR = 0, sumG = 0, sumB = 0; + + // Apply kernel to surrounding pixels for (int ky = -1; ky <= 1; ky++) { for (int kx = -1; kx <= 1; kx++) { Color pixel = source.GetPixel(x + kx, y + ky); int weight = kernel[ky + 1, kx + 1]; - r += pixel.R * weight; - g += pixel.G * weight; - b += pixel.B * weight; + sumR += pixel.R * weight; + sumG += pixel.G * weight; + sumB += pixel.B * weight; } } + // Normalize and clamp color values - r = Math.Clamp(r / kernelSum, 0, 255); - g = Math.Clamp(g / kernelSum, 0, 255); - b = Math.Clamp(b / kernelSum, 0, 255); + int r = Math.Clamp(sumR / divisor, 0, 255); + int g = Math.Clamp(sumG / divisor, 0, 255); + int b = Math.Clamp(sumB / divisor, 0, 255); blurred.SetPixel(x, y, Color.FromArgb(r, g, b)); } } @@ -70,61 +123,4 @@ static Bitmap ApplyGaussianBlur(Bitmap source) return blurred; } - - /// - /// Entry point: creates a barcode image, blurs it, and attempts to decode the blurred image. - /// - static void Main() - { - const string originalPath = "barcode.png"; - const string blurredPath = "barcode_blurred.png"; - const string barcodeText = "123456789012"; - - // Generate a Code128 barcode and save it to disk. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, barcodeText)) - { - // Optional: set image dimensions for better visibility. - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; - generator.Save(originalPath, BarCodeImageFormat.Png); - } - - // Ensure the barcode image was created successfully. - if (!File.Exists(originalPath)) - { - Console.WriteLine($"Failed to create barcode image at '{originalPath}'."); - return; - } - - // Load the original image, apply Gaussian blur, and save the blurred version. - using (var originalBitmap = new Bitmap(originalPath)) - using (var blurredBitmap = ApplyGaussianBlur(originalBitmap)) - { - blurredBitmap.Save(blurredPath, ImageFormat.Png); - } - - // Verify the blurred image was saved. - if (!File.Exists(blurredPath)) - { - Console.WriteLine($"Failed to create blurred image at '{blurredPath}'."); - return; - } - - // Read the blurred barcode using high‑quality settings to improve detection. - using (var reader = new BarCodeReader(blurredPath, DecodeType.Code128)) - { - // Apply the HighQuality preset for better handling of damaged barcodes. - reader.QualitySettings = QualitySettings.HighQuality; - - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine($"Detected Type: {result.CodeTypeName}"); - Console.WriteLine($"Code Text : {result.CodeText}"); - Console.WriteLine($"Confidence : {result.Confidence}"); - Console.WriteLine($"ReadingQuality: {result.ReadingQuality}"); - var bounds = result.Region.Rectangle; - Console.WriteLine($"Region : X={bounds.X}, Y={bounds.Y}, Width={bounds.Width}, Height={bounds.Height}"); - } - } - } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/use-complexbarcodegenerator-to-embed-mailmark-barcode-onto-existing-pdf-page-as-image-overlay.cs b/mailmark-four-state-barcode/use-complexbarcodegenerator-to-embed-mailmark-barcode-onto-existing-pdf-page-as-image-overlay.cs index 43df7dd..ededbc4 100644 --- a/mailmark-four-state-barcode/use-complexbarcodegenerator-to-embed-mailmark-barcode-onto-existing-pdf-page-as-image-overlay.cs +++ b/mailmark-four-state-barcode/use-complexbarcodegenerator-to-embed-mailmark-barcode-onto-existing-pdf-page-as-image-overlay.cs @@ -1,8 +1,8 @@ -// Title: Embed Mailmark Barcode onto PDF using ComplexBarcodeGenerator -// Description: Demonstrates generating a Mailmark barcode with Aspose.BarCode and overlaying it onto an existing PDF page as an image. -// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation and PDF manipulation category. It showcases the use of ComplexBarcodeGenerator, MailmarkCodetext, and Aspose.Pdf Document classes to create a Mailmark barcode image and embed it into a PDF. Developers working with postal barcodes, document automation, or custom PDF overlays commonly need such patterns to integrate barcode data into existing documents. +// Title: Overlay Mailmark barcode on a PDF page using ComplexBarcodeGenerator +// Description: Demonstrates how to generate a Mailmark barcode image with Aspose.BarCode and overlay it onto an existing PDF document as an image. +// Category-Description: This example belongs to the Aspose.BarCode PDF integration category, showcasing the use of ComplexBarcodeGenerator to create complex symbologies (Mailmark) and Aspose.Pdf to embed the generated image into a PDF. Developers often need to add tracking or postal barcodes to documents; the key API classes involved are ComplexBarcodeGenerator, MailmarkCodetext, BarCodeImageFormat, and Aspose.Pdf.Document/Image. // Prompt: Use ComplexBarcodeGenerator to embed a Mailmark barcode onto an existing PDF page as an image overlay. -// Tags: mailmark, barcode, complexbarcode, pdf, overlay, image, generation, aspose.barcode, aspose.pdf +// Tags: mailmark, barcode, pdf, overlay, complexbarcodegenerator, aspose.barcode, aspose.pdf using System; using System.IO; @@ -11,69 +11,81 @@ using Aspose.Pdf; /// -/// Example program that generates a Mailmark barcode and embeds it as an image overlay -/// onto the first page of an existing PDF document. +/// Generates a Mailmark barcode and overlays it onto a PDF page as an image. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Creates a Mailmark barcode, embeds it into a PDF, and saves the result. /// - /// Command‑line arguments (not used). - static void Main(string[] args) + static void Main() { - // Paths for input and output PDF files + // Define file paths for the source and resulting PDF documents. string inputPdfPath = "input.pdf"; string outputPdfPath = "output.pdf"; - // Verify that the input PDF exists before proceeding + // Ensure the input PDF exists; if not, create a simple one‑page PDF. if (!File.Exists(inputPdfPath)) { - Console.WriteLine($"Input PDF file not found: {inputPdfPath}"); - return; + using (var doc = new Document()) + { + doc.Pages.Add(); + doc.Save(inputPdfPath); + } } - // Prepare Mailmark codetext with required values + // Prepare Mailmark codetext with valid values. var mailmark = new MailmarkCodetext { - Format = 4, // 4‑state Mailmark format + Format = 4, // 4‑state Mailmark VersionID = 1, Class = "0", SupplychainID = 384224, ItemID = 16563762, - DestinationPostCodePlusDPS = "EF61AH8T " // trailing space is mandatory + DestinationPostCodePlusDPS = "EF61AH8T " // trailing space is required }; - // Generate the Mailmark barcode image into a memory stream + // Generate the Mailmark barcode image into a memory stream. using (var barcodeStream = new MemoryStream()) { - // Create a ComplexBarcodeGenerator for the Mailmark codetext using (var generator = new ComplexBarcodeGenerator(mailmark)) { - // Save the barcode as PNG; BarCodeImageFormat is from Aspose.BarCode.Generation + // Optional: customize barcode and background colors. + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; + + // Save the barcode as PNG into the stream. generator.Save(barcodeStream, BarCodeImageFormat.Png); } - // Reset stream position before using it in PDF + // Reset the stream position before reading it for PDF insertion. barcodeStream.Position = 0; - // Load the existing PDF document - using (var pdfDocument = new Document(inputPdfPath)) + // Load the existing PDF and overlay the barcode image. + using (var pdfDoc = new Document(inputPdfPath)) { - // Get the first page (pages are 1‑based) - var page = pdfDocument.Pages[1]; + // Use the first page of the PDF (adjust index as needed). + var page = pdfDoc.Pages[1]; - // Define the rectangle where the barcode will be placed (coordinates in points) - var rect = new Aspose.Pdf.Rectangle(100, 500, 300, 700); // llx, lly, urx, ury + // Create an Aspose.Pdf.Image element backed by the barcode stream. + var pdfImage = new Aspose.Pdf.Image + { + ImageStream = barcodeStream, + FixWidth = 200.0, // Width in points. + FixHeight = 200.0, // Height in points. + HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center, + VerticalAlignment = Aspose.Pdf.VerticalAlignment.Center, + Margin = new Aspose.Pdf.MarginInfo { Top = 10 } + }; - // Add the barcode image as an overlay on the page - page.AddImage(barcodeStream, rect); + // Add the image to the page's paragraph collection. + page.Paragraphs.Add(pdfImage); - // Save the modified PDF to the output path - pdfDocument.Save(outputPdfPath); + // Save the modified PDF to the output path. + pdfDoc.Save(outputPdfPath); } } - Console.WriteLine($"Mailmark barcode embedded successfully into '{outputPdfPath}'."); + Console.WriteLine($"Barcode overlay completed. Output saved to '{outputPdfPath}'."); } } \ No newline at end of file diff --git a/mailmark-four-state-barcode/validate-generated-mailmark-barcode-includes-automatically-calculated-checksum-by-inspecting-codetext-property.cs b/mailmark-four-state-barcode/validate-generated-mailmark-barcode-includes-automatically-calculated-checksum-by-inspecting-codetext-property.cs index ac66249..6077e5f 100644 --- a/mailmark-four-state-barcode/validate-generated-mailmark-barcode-includes-automatically-calculated-checksum-by-inspecting-codetext-property.cs +++ b/mailmark-four-state-barcode/validate-generated-mailmark-barcode-includes-automatically-calculated-checksum-by-inspecting-codetext-property.cs @@ -1,76 +1,74 @@ -// Title: Validate Mailmark barcode checksum via Codetext inspection -// Description: Demonstrates generating a Mailmark barcode, automatically calculating its checksum, and verifying it by comparing the decoded Codetext with the expected value. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on complex barcode types such as Mailmark. It showcases the use of ComplexBarcodeGenerator for creating barcodes, BarCodeReader for decoding, and checksum validation settings. Developers often need to ensure data integrity for Mailmark barcodes in postal and logistics applications, making checksum verification a common requirement. +// Title: Validate Mailmark barcode checksum via Codetext property +// Description: Demonstrates generating a Mailmark barcode, automatically calculating its checksum, and verifying the checksum by comparing the decoded codetext with the expected constructed codetext. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on complex barcode symbologies such as Mailmark. It showcases the use of ComplexBarcodeGenerator to create a Mailmark barcode, BarCodeReader for decoding, and the MailmarkCodetext class for constructing codetext with an automatically computed checksum. Developers working with postal and logistics applications often need to generate and validate Mailmark barcodes to ensure data integrity and compliance with postal standards. // Prompt: Validate generated Mailmark barcode includes automatically calculated checksum by inspecting Codetext property. -// Tags: mailmark, checksum, barcode generation, barcode recognition, csharp, aspose.barcode +// Tags: mailmark, barcode, checksum, generation, recognition, complexbarcode, aspnet, csharp using System; using System.IO; -using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.BarCode.ComplexBarcode; /// -/// Example program that generates a Mailmark barcode, automatically calculates its checksum, -/// and validates the checksum by decoding the barcode and comparing the Codetext. +/// Example program that generates a Mailmark barcode, decodes it, and validates the automatically calculated checksum. /// class Program { /// - /// Entry point of the example. Generates a Mailmark barcode, reads it back, and verifies the checksum. + /// Entry point. Generates a Mailmark barcode, reads it back, and checks that the decoded CodeText matches the expected value including checksum. /// static void Main() { - // Prepare Mailmark codetext with required fields - var mailmark = new MailmarkCodetext(); - mailmark.Format = 4; // 4‑state barcode - mailmark.VersionID = 1; - mailmark.Class = "0"; - mailmark.SupplychainID = 384224; - mailmark.ItemID = 16563762; - mailmark.DestinationPostCodePlusDPS = "EF61AH8T "; - - // Construct the full codetext (includes automatically calculated checksum) - string expectedCodetext = mailmark.GetConstructedCodetext(); + // Prepare Mailmark codetext with known valid data. + var mailmark = new MailmarkCodetext + { + Format = 4, // 4‑state Mailmark + VersionID = 1, + Class = "0", + SupplychainID = 384224, + ItemID = 16563762, + DestinationPostCodePlusDPS = "EF61AH8T " // trailing space required + }; - // Generate the Mailmark barcode image into a memory stream - using (var generator = new ComplexBarcodeGenerator(mailmark)) + // Generate the barcode image into a memory stream. + using (var imageStream = new MemoryStream()) { - using (var ms = new MemoryStream()) + // Create a ComplexBarcodeGenerator for the Mailmark codetext. + using (var generator = new ComplexBarcodeGenerator(mailmark)) { - // Save barcode as PNG into the memory stream - generator.Save(ms, BarCodeImageFormat.Png); - ms.Position = 0; // Reset stream position for reading + // Save the generated barcode as PNG into the stream. + generator.Save(imageStream, BarCodeImageFormat.Png); + } - // Recognize the barcode and enable checksum validation - using (var reader = new BarCodeReader(ms, DecodeType.Mailmark)) - { - // Force checksum validation during decoding - reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On; + // Reset stream position for reading. + imageStream.Position = 0; - bool found = false; - // Iterate through all detected barcodes (should be only one) - foreach (var result in reader.ReadBarCodes()) - { - Console.WriteLine("Decoded CodeText: " + result.CodeText); - if (result.CodeText == expectedCodetext) - { - Console.WriteLine("Checksum validation succeeded: decoded codetext matches expected."); - } - else - { - Console.WriteLine("Checksum validation failed: decoded codetext does not match expected."); - } - found = true; - } + // Decode the barcode and obtain the codetext. + using (var reader = new BarCodeReader(imageStream, DecodeType.Mailmark)) + { + var results = reader.ReadBarCodes(); - // Inform the user if no barcode was detected - if (!found) - { - Console.WriteLine("No Mailmark barcode detected in the generated image."); - } + // Ensure at least one barcode was detected. + if (results.Length == 0) + { + Console.WriteLine("No Mailmark barcode detected."); + return; } + + // Extract the decoded CodeText. + var decoded = results[0].CodeText; + + // Get the expected codetext (includes automatically calculated checksum). + var expected = mailmark.GetConstructedCodetext(); + + // Validate that the decoded codetext matches the expected codetext. + bool checksumValid = string.Equals(decoded, expected, StringComparison.Ordinal); + + // Output the results. + Console.WriteLine($"Decoded CodeText : {decoded}"); + Console.WriteLine($"Expected CodeText: {expected}"); + Console.WriteLine($"Checksum validated: {checksumValid}"); } } } diff --git a/mailmark-four-state-barcode/write-unit-tests-verifying-successful-decoding-of-mailmark-barcodes-with-intentional-reed-solomon-error-patterns.cs b/mailmark-four-state-barcode/write-unit-tests-verifying-successful-decoding-of-mailmark-barcodes-with-intentional-reed-solomon-error-patterns.cs index c7d538d..5373afc 100644 --- a/mailmark-four-state-barcode/write-unit-tests-verifying-successful-decoding-of-mailmark-barcodes-with-intentional-reed-solomon-error-patterns.cs +++ b/mailmark-four-state-barcode/write-unit-tests-verifying-successful-decoding-of-mailmark-barcodes-with-intentional-reed-solomon-error-patterns.cs @@ -1,11 +1,13 @@ -// Title: Mailmark barcode decoding with Reed‑Solomon error simulation -// Description: Demonstrates generating a Mailmark barcode, corrupting it with simulated Reed‑Solomon errors, and verifying successful decoding. -// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on complex barcode types such as Mailmark. It showcases the use of ComplexBarcodeGenerator, BarCodeReader, and related quality settings to handle damaged barcodes, a common requirement for developers implementing robust mail processing systems. The snippet illustrates typical workflows for creating, corrupting, and validating Mailmark barcodes using Aspose.BarCode APIs. +// Title: Mailmark barcode decoding with simulated Reed‑Solomon errors +// Description: Demonstrates generating Mailmark barcodes, corrupting the image to simulate Reed‑Solomon errors, and successfully decoding them using Aspose.BarCode. +// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on complex barcode symbologies such as Mailmark. It showcases the use of ComplexBarcodeGenerator, BarCodeReader, and related classes to create, corrupt, and decode barcodes, a common task for developers testing error‑correction capabilities and robustness of barcode scanning solutions. // Prompt: Write unit tests verifying successful decoding of Mailmark barcodes with intentional Reed‑Solomon error patterns. -// Tags: mailmark, barcode, decoding, reed-solomon, error-correction, generation, recognition, aspnet, csharp +// Tags: mailmark, barcode, decoding, error-correction, reed-solomon, aspose.barcode, complexbarcode, unit-test using System; +using System.Collections.Generic; using System.IO; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeRecognition; using Aspose.BarCode.ComplexBarcode; @@ -13,109 +15,146 @@ using Aspose.Drawing.Imaging; /// -/// Demonstrates generating a Mailmark barcode, corrupting it, and verifying decoding using Aspose.BarCode. +/// Demonstrates generating, corrupting, and decoding Mailmark barcodes using Aspose.BarCode. /// class Program { /// - /// Entry point for the Mailmark decoding demonstration. + /// Entry point that runs a series of Mailmark decoding tests and reports results. /// static void Main() { - // Run the Mailmark decoding test - RunMailmarkDecodingTest(); + // Prepare test cases with different ItemID values + var testCases = new List + { + CreateMailmark(16563762), + CreateMailmark(16563763), + CreateMailmark(16563764) + }; + + int passed = 0; + int failed = 0; + + // Execute each test case + for (int i = 0; i < testCases.Count; i++) + { + bool result = RunTest(testCases[i], i + 1); + if (result) + passed++; + else + failed++; + } + + // Output summary of test results + Console.WriteLine($"TOTAL: {testCases.Count}, PASSED: {passed}, FAILED: {failed}"); } - /// - /// Generates a Mailmark barcode, introduces simulated Reed‑Solomon errors, and validates successful decoding. - /// - static void RunMailmarkDecodingTest() + // Creates a MailmarkCodetext with known valid values + static MailmarkCodetext CreateMailmark(int itemId) { - // Prepare a valid Mailmark codetext var mailmark = new MailmarkCodetext(); - mailmark.Format = 4; // Default/unspecified format + mailmark.Format = 4; // 4‑state Mailmark mailmark.VersionID = 1; mailmark.Class = "0"; mailmark.SupplychainID = 384224; - mailmark.ItemID = 16563762; - mailmark.DestinationPostCodePlusDPS = "EF61AH8T "; + mailmark.ItemID = itemId; + mailmark.DestinationPostCodePlusDPS = "EF61AH8T "; // trailing space is required + return mailmark; + } - // Generate the Mailmark barcode image using ComplexBarcodeGenerator - using (var complexGenerator = new ComplexBarcodeGenerator(mailmark)) + // Generates a barcode image, corrupts it, decodes it and verifies the result + static bool RunTest(MailmarkCodetext original, int testNumber) + { + // Step 1: generate barcode image into a memory stream + using (var barcodeStream = new MemoryStream()) { - using (Bitmap bitmap = complexGenerator.GenerateBarCodeImage()) + using (var generator = new ComplexBarcodeGenerator(original)) + { + generator.Save(barcodeStream, BarCodeImageFormat.Png); + } + + // Step 2: corrupt the image to simulate Reed‑Solomon errors + using (var corruptedStream = CorruptImage(barcodeStream)) { - // Save the image to a memory stream (PNG format) - using (var originalStream = new MemoryStream()) + // Step 3: decode the corrupted image + using (var reader = new BarCodeReader(corruptedStream, DecodeType.Mailmark)) { - bitmap.Save(originalStream, ImageFormat.Png); - byte[] originalBytes = originalStream.ToArray(); - - // Introduce intentional Reed‑Solomon error patterns by corrupting a few bytes - // (simple pixel corruption for demonstration purposes) - byte[] corruptedBytes = (byte[])originalBytes.Clone(); - int errorsToIntroduce = 5; - Random rnd = new Random(0); - for (int i = 0; i < errorsToIntroduce; i++) - { - int index = rnd.Next(corruptedBytes.Length); - corruptedBytes[index] ^= 0xFF; // Invert bits at the selected position - } + // Allow engine to try to read even if some data is damaged + reader.QualitySettings.AllowIncorrectBarcodes = true; - // Decode the corrupted image - using (var corruptedStream = new MemoryStream(corruptedBytes)) + foreach (var result in reader.ReadBarCodes()) { - using (var reader = new BarCodeReader(corruptedStream, DecodeType.Mailmark)) + // Verify that a code text was obtained + if (string.IsNullOrEmpty(result.CodeText)) + { + Console.WriteLine($"Test {testNumber}: FAILED – empty CodeText."); + return false; + } + + // Decode the complex codetext back to a MailmarkCodetext object + var decoded = ComplexCodetextReader.TryDecodeMailmark(result.CodeText); + if (decoded == null) + { + Console.WriteLine($"Test {testNumber}: FAILED – ComplexCodetextReader returned null."); + return false; + } + + // Compare all fields + bool match = + decoded.Format == original.Format && + decoded.VersionID == original.VersionID && + decoded.Class == original.Class && + decoded.SupplychainID == original.SupplychainID && + decoded.ItemID == original.ItemID && + decoded.DestinationPostCodePlusDPS == original.DestinationPostCodePlusDPS; + + if (match) { - // Allow the engine to attempt recovery from damaged barcodes - reader.QualitySettings.AllowIncorrectBarcodes = true; - reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast; - - var results = reader.ReadBarCodes(); - - if (results.Length == 0) - { - Console.WriteLine("Test FAILED: No barcode detected."); - return; - } - - // Expect only one Mailmark barcode - var result = results[0]; - if (string.IsNullOrEmpty(result.CodeText)) - { - Console.WriteLine("Test FAILED: Decoded CodeText is empty."); - return; - } - - // Verify that the decoded codetext can be parsed back to a MailmarkCodetext object - MailmarkCodetext decodedMailmark = ComplexCodetextReader.TryDecodeMailmark(result.CodeText); - if (decodedMailmark == null) - { - Console.WriteLine("Test FAILED: ComplexCodetextReader could not parse the codetext."); - return; - } - - // Simple field comparisons to ensure integrity - bool fieldsMatch = - decodedMailmark.Format == mailmark.Format && - decodedMailmark.VersionID == mailmark.VersionID && - decodedMailmark.Class == mailmark.Class && - decodedMailmark.SupplychainID == mailmark.SupplychainID && - decodedMailmark.ItemID == mailmark.ItemID && - decodedMailmark.DestinationPostCodePlusDPS == mailmark.DestinationPostCodePlusDPS; - - if (fieldsMatch) - { - Console.WriteLine("Test PASSED: Mailmark barcode decoded successfully despite errors."); - } - else - { - Console.WriteLine("Test FAILED: Decoded fields do not match original values."); - } + Console.WriteLine($"Test {testNumber}: PASS"); + return true; + } + else + { + Console.WriteLine($"Test {testNumber}: FAILED – decoded values do not match original."); + return false; } } + + Console.WriteLine($"Test {testNumber}: FAILED – no barcode detected."); + return false; } } } } + + // Introduces random pixel errors into the PNG image to mimic Reed‑Solomon corruption + static MemoryStream CorruptImage(MemoryStream originalStream) + { + // Load the original image + originalStream.Position = 0; + using (var bitmap = new Bitmap(originalStream)) + { + // Simple deterministic "random" corruption + var rand = new Random(12345); + int errorCount = Math.Max(1, bitmap.Width * bitmap.Height / 2000); // ~0.05% of pixels + + for (int i = 0; i < errorCount; i++) + { + int x = rand.Next(bitmap.Width); + int y = rand.Next(bitmap.Height); + // Flip the pixel color (black <-> white) + var current = bitmap.GetPixel(x, y); + var newColor = (current.ToArgb() == Aspose.Drawing.Color.Black.ToArgb()) + ? Aspose.Drawing.Color.White + : Aspose.Drawing.Color.Black; + bitmap.SetPixel(x, y, newColor); + } + + // Save the corrupted image to a new memory stream + var corruptedStream = new MemoryStream(); + bitmap.Save(corruptedStream, ImageFormat.Png); + corruptedStream.Position = 0; + return corruptedStream; + } + } } \ No newline at end of file