diff --git a/maxicode-barcode/apply-custom-background-color-to-maxicode-barcode-and-verify-that-decoding-remains-successful.cs b/maxicode-barcode/apply-custom-background-color-to-maxicode-barcode-and-verify-that-decoding-remains-successful.cs
index 4b97679..aab328e 100644
--- a/maxicode-barcode/apply-custom-background-color-to-maxicode-barcode-and-verify-that-decoding-remains-successful.cs
+++ b/maxicode-barcode/apply-custom-background-color-to-maxicode-barcode-and-verify-that-decoding-remains-successful.cs
@@ -1,96 +1,69 @@
-// Title: Custom Background Color for MaxiCode Barcode
-// Description: Demonstrates applying a custom background color to a MaxiCode barcode and confirming that it can still be decoded correctly.
-// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, focusing on MaxiCode symbology. It showcases the use of ComplexBarcodeGenerator to create a MaxiCode with custom visual settings, and BarCodeReader with ComplexCodetextReader to decode the generated image. Developers working with shipping, logistics, or inventory systems often need to customize barcode appearance while ensuring reliable scanning.
+// Title: Apply custom background color to a MaxiCode barcode and verify decoding
+// Description: Demonstrates setting a custom background color for a MaxiCode barcode using Aspose.BarCode, saving it as an image, and confirming that the barcode can still be decoded correctly.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator to customize visual appearance (background and bar colors) and BarCodeReader to decode the generated image. Typical use cases include branding barcodes with corporate colors while ensuring they remain machine‑readable. Developers often need to adjust visual parameters without breaking decoding, and this snippet illustrates that workflow.
// Prompt: Apply a custom background color to a MaxiCode barcode and verify that decoding remains successful.
// Tags: maxicode, background color, barcode generation, barcode recognition, aspose.barcode, c#
using System;
-using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.BarCode.ComplexBarcode;
using Aspose.Drawing;
///
/// Generates a MaxiCode barcode with a custom background color,
-/// saves it as an image, and verifies that the barcode can be decoded successfully.
+/// saves it to a PNG file, and then verifies that the barcode can be decoded successfully.
///
class Program
{
///
- /// Entry point of the example. Creates a MaxiCode with a light‑yellow background,
- /// writes it to a PNG file, and then reads the file back to confirm decoding.
+ /// Entry point of the example. Creates the barcode, applies visual customizations,
+ /// saves the image, and validates decoding.
///
static void Main()
{
- // Define the output file name.
- string outputPath = "maxicode.png";
+ // Define the output file path for the generated barcode image.
+ string imagePath = "maxicode.png";
- // Prepare MaxiCode codetext (Mode 2 example) with postal code, country code, and service category.
- var maxiCode = new MaxiCodeCodetextMode2
+ // --------------------------------------------------------------------
+ // Generate a MaxiCode barcode with custom colors.
+ // --------------------------------------------------------------------
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MaxiCode, "Sample MaxiCode"))
{
- PostalCode = "524032140", // 9‑digit US postal code
- CountryCode = 56, // USA
- ServiceCategory = 999 // Example service category
- };
+ // Set a custom background color (light orange‑yellow).
+ generator.Parameters.BackColor = Color.FromArgb(255, 255, 224, 128);
- // Add a second message to the MaxiCode.
- var secondMessage = new MaxiCodeStandardSecondMessage
- {
- Message = "Sample MaxiCode"
- };
- maxiCode.SecondMessage = secondMessage;
-
- // Generate the MaxiCode barcode with a custom background color.
- using (var complexGenerator = new ComplexBarcodeGenerator(maxiCode))
- {
- // Set background to light yellow (RGB 255,255,224).
- complexGenerator.Parameters.BackColor = Aspose.Drawing.Color.FromArgb(255, 255, 224);
+ // Optionally set the foreground (bar) color for better contrast.
+ generator.Parameters.Barcode.BarColor = Color.Black;
- // Create the barcode image.
- using (var bitmap = complexGenerator.GenerateBarCodeImage())
- {
- // Save the image as PNG.
- bitmap.Save(outputPath, Aspose.Drawing.Imaging.ImageFormat.Png);
- }
+ // Save the customized barcode image to the specified file.
+ generator.Save(imagePath);
}
- // Verify that the image file was created.
- if (!File.Exists(outputPath))
+ // --------------------------------------------------------------------
+ // Decode the saved barcode image to ensure the custom background does not affect readability.
+ // --------------------------------------------------------------------
+ BaseDecodeType decodeType = DecodeType.MaxiCode;
+ using (BarCodeReader reader = new BarCodeReader(imagePath, decodeType))
{
- Console.WriteLine("Failed to create barcode image.");
- return;
- }
+ // Use the highest quality preset to improve detection reliability.
+ reader.QualitySettings = QualitySettings.MaxQuality;
- // Read and decode the generated MaxiCode barcode.
- using (var reader = new BarCodeReader(outputPath, DecodeType.MaxiCode))
- {
- foreach (var result in reader.ReadBarCodes())
- {
- // Decode the raw codetext using the appropriate MaxiCode mode.
- var decoded = ComplexCodetextReader.TryDecodeMaxiCode(
- result.Extended.MaxiCode.MaxiCodeMode,
- result.CodeText);
-
- // Check if decoding produced the expected Mode 2 codetext.
- if (decoded is MaxiCodeCodetextMode2 decodedMode2)
- {
- Console.WriteLine("Decoding successful:");
- Console.WriteLine($"Postal Code: {decodedMode2.PostalCode}");
- Console.WriteLine($"Country Code: {decodedMode2.CountryCode}");
- Console.WriteLine($"Service Category: {decodedMode2.ServiceCategory}");
+ // Read all barcodes present in the image.
+ BarCodeResult[] results = reader.ReadBarCodes();
- // Output the second message if present.
- if (decodedMode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
- {
- Console.WriteLine($"Message: {stdMsg.Message}");
- }
- }
- else
+ // Evaluate decoding results.
+ bool success = false;
+ foreach (BarCodeResult result in results)
+ {
+ if (!string.IsNullOrEmpty(result.CodeText))
{
- Console.WriteLine("Decoding failed or unexpected codetext type.");
+ Console.WriteLine($"Decoded CodeText: {result.CodeText}");
+ success = true;
}
}
+
+ Console.WriteLine(success ? "Decoding succeeded." : "Decoding failed.");
}
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/apply-custom-foreground-color-to-maxicode-mode-2-barcode-using-generator-s-forecolor-property.cs b/maxicode-barcode/apply-custom-foreground-color-to-maxicode-mode-2-barcode-using-generator-s-forecolor-property.cs
index dd9ba8b..a0e142c 100644
--- a/maxicode-barcode/apply-custom-foreground-color-to-maxicode-mode-2-barcode-using-generator-s-forecolor-property.cs
+++ b/maxicode-barcode/apply-custom-foreground-color-to-maxicode-mode-2-barcode-using-generator-s-forecolor-property.cs
@@ -1,57 +1,45 @@
-// Title: Apply custom foreground color to a MaxiCode Mode 2 barcode
-// Description: This example creates a MaxiCode Mode 2 barcode, sets a custom bar (foreground) color, and saves it as a PNG image. It demonstrates how to customize the visual appearance of complex barcodes using Aspose.BarCode.
-// Category-Description: The sample belongs to the Aspose.BarCode complex barcode generation category, where developers work with multi‑message symbologies such as MaxiCode. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and related parameter classes to configure barcode data and appearance. Typical scenarios include shipping labels, parcel tracking, and logistics applications that require colored MaxiCode symbols.
+// Title: Custom foreground color for MaxiCode Mode 2 barcode
+// Description: Demonstrates generating a MaxiCode Mode 2 barcode and applying a custom foreground (bar) color using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator with MaxiCodeCodetextMode2, configuring barcode appearance via the Parameters.Barcode.BarColor property, and saving the result as an image. Developers working with high‑density 2‑D barcodes such as MaxiCode often need to customize visual attributes for branding or readability, making this pattern a common starting point.
// Prompt: Apply a custom foreground color to a MaxiCode Mode 2 barcode using the generator's ForeColor property.
-// Tags: maxicode, color, generation, png, aspose.barcode, complexbarcodegenerator, barcode
+// Tags: maxicode, barcode, color, foreground, generation, aspose.barcode, complexbarcode, png
-using System;
-using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates applying a custom foreground color to a MaxiCode Mode 2 barcode and saving it as PNG.
+/// Generates a MaxiCode Mode 2 barcode with a custom foreground color and saves it as a PNG file.
///
class Program
{
///
- /// Entry point that builds the MaxiCode data, configures the barcode color, generates the image, and writes it to disk.
+ /// Entry point of the example. Creates the barcode data, configures the generator, and writes the image to disk.
///
static void Main()
{
- // Prepare MaxiCode Mode 2 codetext with required fields
- var maxiCodeCodetext = new MaxiCodeCodetextMode2
+ // Prepare MaxiCode Mode 2 codetext with sample values.
+ var maxiCodeData = new MaxiCodeCodetextMode2
{
- PostalCode = "524032140", // 9‑digit US postal code
- CountryCode = 56, // USA numeric country code
- ServiceCategory = 999 // Example service category
+ PostalCode = "524032140",
+ CountryCode = 56,
+ ServiceCategory = 999,
+ SecondMessage = new MaxiCodeStandardSecondMessage { Message = "Sample message" }
};
- // Create and assign the standard second message
- var secondMessage = new MaxiCodeStandardSecondMessage
+ // Initialize the complex barcode generator using the prepared codetext.
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
{
- Message = "Sample MaxiCode"
- };
- maxiCodeCodetext.SecondMessage = secondMessage;
-
- // Initialize the generator with the prepared codetext
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
- {
- // Set a custom foreground (bar) color for the barcode
- generator.Parameters.Barcode.BarColor = Color.Blue;
-
- // Generate the barcode image in memory
- generator.GenerateBarCodeImage();
-
- // Define output file path and save the image as PNG
- const string outputPath = "maxicode_mode2.png";
- generator.Save(outputPath, BarCodeImageFormat.Png);
+ // Set a custom foreground (bar) color for the barcode.
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Red;
- // Inform the user where the file was saved
- Console.WriteLine($"Barcode saved to {Path.GetFullPath(outputPath)}");
+ // Generate the barcode image.
+ using (Aspose.Drawing.Bitmap image = generator.GenerateBarCodeImage())
+ {
+ // Save the generated image to a PNG file.
+ image.Save("MaxiCodeMode2_Red.png");
+ }
}
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/batch-decode-all-maxicode-png-files-in-directory-and-export-results-to-csv-report.cs b/maxicode-barcode/batch-decode-all-maxicode-png-files-in-directory-and-export-results-to-csv-report.cs
index c68e339..0e9bb15 100644
--- a/maxicode-barcode/batch-decode-all-maxicode-png-files-in-directory-and-export-results-to-csv-report.cs
+++ b/maxicode-barcode/batch-decode-all-maxicode-png-files-in-directory-and-export-results-to-csv-report.cs
@@ -1,151 +1,122 @@
-// Title: Batch decode MaxiCode PNG files to CSV
-// Description: Demonstrates how to read multiple MaxiCode barcodes from PNG images in a folder and export the decoded information to a CSV report.
-// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on batch processing of MaxiCode symbology. It showcases the use of BarCodeReader, DecodeType.MaxiCode, QualitySettings, and ComplexCodetextReader to extract structured data such as postal code, country code, and service category, then writes results to a CSV file. Developers working with bulk barcode decoding, logistics, or shipping label processing can use this pattern for automated data extraction.
+// Title: Batch decode MaxiCode PNG images and generate CSV report
+// Description: Demonstrates how to read multiple MaxiCode barcodes from PNG files in a folder and export the decoded text and type to a CSV file.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category. It showcases the BarCodeReader with DecodeType.MaxiCode, CSV report generation, and optional sample image creation using ComplexBarcodeGenerator. Developers working with bulk barcode processing, reporting, or logistics applications can use this pattern to automate data extraction from MaxiCode symbols.
// Prompt: Batch decode all MaxiCode PNG files in a directory and export the results to a CSV report.
-// Tags: maxicode, barcode, batch processing, csv, aspose.barcode, decoding, recognition, complexcodetext
+// Tags: maxicode, barcode, decoding, csv, aspose.barcode, csharp
using System;
using System.IO;
using System.Collections.Generic;
+using Aspose.BarCode;
+using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.BarCode.ComplexBarcode;
-using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Provides a console application that batch decodes MaxiCode barcodes from PNG files
-/// and writes the extracted information to a CSV report.
+/// Provides a console application that decodes all MaxiCode PNG images in a specified directory
+/// and writes the results to a CSV report.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point. Scans the input folder, generates sample images if needed, decodes each MaxiCode,
+ /// and writes a CSV file containing file name, decoded text, and barcode type.
///
- ///
- /// Optional command‑line arguments:
- /// args[0] – input folder path (default: "Input"),
- /// args[1] – output CSV file path (default: "MaxiCodeReport.csv").
- ///
- static void Main(string[] args)
+ static void Main()
{
- // Resolve input folder and output CSV path from arguments or use defaults.
- string inputFolder = args.Length > 0 ? args[0] : "Input";
- string outputCsv = args.Length > 1 ? args[1] : "MaxiCodeReport.csv";
+ // Define input and output paths
+ string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "MaxiCodeImages");
+ string reportPath = Path.Combine(Directory.GetCurrentDirectory(), "MaxiCodeReport.csv");
- // Ensure the input folder exists; create it if missing.
+ // Ensure the input folder exists
if (!Directory.Exists(inputFolder))
{
Directory.CreateDirectory(inputFolder);
}
- // Retrieve all PNG files from the input directory.
- string[] pngFiles = Directory.GetFiles(inputFolder, "*.png");
+ // Generate a few sample MaxiCode PNG files if the folder is empty
+ string[] sampleFiles = Directory.GetFiles(inputFolder, "*.png");
+ if (sampleFiles.Length == 0)
+ {
+ GenerateSampleMaxiCodeImages(inputFolder);
+ }
- // Limit processing to a maximum of 10 files as a safety guideline.
- int maxFiles = Math.Min(pngFiles.Length, 10);
+ // Prepare CSV header
+ var csvLines = new List { "FileName,CodeText,CodeType" };
- // Open a StreamWriter for the CSV report.
- using (var writer = new StreamWriter(outputCsv, false))
+ // Process each PNG file in the folder
+ foreach (string filePath in Directory.GetFiles(inputFolder, "*.png"))
{
- // Write the CSV header line.
- writer.WriteLine("FileName,CodeText,PostalCode,CountryCode,ServiceCategory,Message");
-
- // Process each PNG file up to the defined limit.
- for (int i = 0; i < maxFiles; i++)
+ if (!File.Exists(filePath))
{
- string filePath = pngFiles[i];
- string fileName = Path.GetFileName(filePath);
+ // Skip missing files gracefully
+ continue;
+ }
- // Guard against missing files (should not happen after GetFiles).
- if (!File.Exists(filePath))
+ // Decode using MaxiCode decode type
+ using (var reader = new BarCodeReader(filePath, DecodeType.MaxiCode))
+ {
+ foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"File not found: {filePath}");
- continue;
+ // Build CSV line with proper escaping
+ string line = $"{Path.GetFileName(filePath)},{EscapeCsv(result.CodeText)},{EscapeCsv(result.CodeTypeName)}";
+ csvLines.Add(line);
}
+ }
+ }
- // Initialize a BarCodeReader for MaxiCode decoding.
- using (var reader = new BarCodeReader(filePath, DecodeType.MaxiCode))
- {
- // Apply the highest quality settings to improve detection accuracy.
- reader.QualitySettings = QualitySettings.MaxQuality;
-
- // Read all barcodes present in the image.
- BarCodeResult[] results = reader.ReadBarCodes();
-
- // If no barcodes were found, write an empty record and continue.
- if (results.Length == 0)
- {
- writer.WriteLine($"{Escape(fileName)},,,,,");
-
- continue;
- }
-
- // Process each detected barcode.
- foreach (var result in results)
- {
- // Retrieve raw codetext; ensure it's not null.
- string rawCodeText = result.CodeText ?? string.Empty;
-
- // Decode the structured MaxiCode codetext.
- MaxiCodeCodetext decoded = ComplexCodetextReader.TryDecodeMaxiCode(
- result.Extended.MaxiCode.MaxiCodeMode,
- rawCodeText);
+ // Write all lines to the CSV report
+ File.WriteAllLines(reportPath, csvLines);
+ }
- // Initialize fields with default empty values.
- string postal = string.Empty;
- string country = string.Empty;
- string service = string.Empty;
- string message = string.Empty;
+ // Generates a few sample MaxiCode images (Mode2) for demonstration
+ private static void GenerateSampleMaxiCodeImages(string folder)
+ {
+ // Sample data for three images
+ var samples = new[]
+ {
+ new { FileName = "sample1.png", PostalCode = "524032140", CountryCode = 56, ServiceCategory = 999, Message = "Hello World" },
+ new { FileName = "sample2.png", PostalCode = "524032141", CountryCode = 56, ServiceCategory = 100, Message = "Aspose.BarCode" },
+ new { FileName = "sample3.png", PostalCode = "524032142", CountryCode = 56, ServiceCategory = 200, Message = "MaxiCode Test" }
+ };
- // Extract details for Mode 2 MaxiCode.
- if (decoded is MaxiCodeCodetextMode2 mode2)
- {
- postal = mode2.PostalCode ?? string.Empty;
- country = mode2.CountryCode.ToString();
- service = mode2.ServiceCategory.ToString();
+ foreach (var s in samples)
+ {
+ // Create MaxiCode codetext (Mode2)
+ var maxiCode = new MaxiCodeCodetextMode2
+ {
+ PostalCode = s.PostalCode,
+ CountryCode = s.CountryCode,
+ ServiceCategory = s.ServiceCategory
+ };
- if (mode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
- {
- message = stdMsg.Message ?? string.Empty;
- }
- else if (mode2.SecondMessage is MaxiCodeStructuredSecondMessage structMsg)
- {
- // Concatenate identifiers from the structured message.
- message = string.Join(" | ", structMsg.Identifiers);
- }
- }
- // Extract details for Mode 3 MaxiCode.
- else if (decoded is MaxiCodeCodetextMode3 mode3)
- {
- postal = mode3.PostalCode ?? string.Empty;
- country = mode3.CountryCode.ToString();
- service = mode3.ServiceCategory.ToString();
+ var secondMessage = new MaxiCodeStandardSecondMessage
+ {
+ Message = s.Message
+ };
+ maxiCode.SecondMessage = secondMessage;
- if (mode3.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
- {
- message = stdMsg.Message ?? string.Empty;
- }
- else if (mode3.SecondMessage is MaxiCodeStructuredSecondMessage structMsg)
- {
- message = string.Join(" | ", structMsg.Identifiers);
- }
- }
- // For other MaxiCode modes, fields remain empty.
+ string imagePath = Path.Combine(folder, s.FileName);
- // Write the CSV line, escaping commas where necessary.
- writer.WriteLine($"{Escape(fileName)},{Escape(rawCodeText)},{Escape(postal)},{Escape(country)},{Escape(service)},{Escape(message)}");
- }
- }
+ // Generate and save the barcode image
+ using (var generator = new ComplexBarcodeGenerator(maxiCode))
+ {
+ generator.Save(imagePath, BarCodeImageFormat.Png);
}
}
-
- Console.WriteLine($"Decoding completed. Report saved to '{outputCsv}'.");
}
- ///
- /// Escapes a CSV field by surrounding it with double quotes if it contains a comma,
- /// and doubles any existing double quotes.
- ///
- /// The field value to escape.
- /// The escaped field value.
- private static string Escape(string s) => s.Contains(",") ? $"\"{s.Replace("\"", "\"\"")}\"" : s;
+ // Escapes CSV fields containing commas or quotes
+ private static string EscapeCsv(string field)
+ {
+ if (field == null)
+ return "";
+ if (field.Contains(",") || field.Contains("\"") || field.Contains("\n"))
+ {
+ string escaped = field.Replace("\"", "\"\"");
+ return $"\"{escaped}\"";
+ }
+ return field;
+ }
}
\ No newline at end of file
diff --git a/maxicode-barcode/configure-barcodereader-to-decode-maxicode-images-from-byte-array-and-retrieve-both-primary-and-secondary-messages.cs b/maxicode-barcode/configure-barcodereader-to-decode-maxicode-images-from-byte-array-and-retrieve-both-primary-and-secondary-messages.cs
index 5162218..39b29ee 100644
--- a/maxicode-barcode/configure-barcodereader-to-decode-maxicode-images-from-byte-array-and-retrieve-both-primary-and-secondary-messages.cs
+++ b/maxicode-barcode/configure-barcodereader-to-decode-maxicode-images-from-byte-array-and-retrieve-both-primary-and-secondary-messages.cs
@@ -1,8 +1,8 @@
-// Title: Decode MaxiCode from Byte Array and Retrieve Primary & Secondary Messages
-// Description: Demonstrates how to generate a MaxiCode (Mode 2), save it to a memory stream, and use BarCodeReader to decode the image from a byte array, extracting both primary and secondary message data.
-// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation and recognition category. It showcases the use of ComplexBarcodeGenerator for creating MaxiCode symbols and BarCodeReader for decoding them. Developers working with logistics, shipping, or retail often need to encode and decode MaxiCode data, including structured primary and secondary messages, using the MaxiCodeCodetextMode2, MaxiCodeStandardSecondMessage, and related API classes.
+// Title: Decode MaxiCode from byte array and extract primary & secondary messages
+// Description: Demonstrates generating a MaxiCode (Mode 2) image, converting it to a byte array, and using BarCodeReader to decode both the primary postal information and the secondary message.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on complex barcode types such as MaxiCode. It showcases the use of ComplexBarcodeGenerator, BarCodeReader, and ComplexCodetextReader to handle encoding and decoding of structured MaxiCode data, a common requirement for shipping and logistics applications where both address and custom messages are embedded.
// Prompt: Configure BarcodeReader to decode MaxiCode images from a byte array and retrieve both primary and secondary messages.
-// Tags: maxicode, barcode decoding, byte array, complex barcode, aspose.barcode, c#
+// Tags: maxicode, barcode, decoding, byte array, primary message, secondary message, aspnet.barcode, complexbarcode, codetext
using System;
using System.IO;
@@ -12,102 +12,78 @@
using Aspose.Drawing.Imaging;
///
-/// Example program that generates a MaxiCode (Mode 2), stores it in a memory stream,
-/// and decodes it using to retrieve both primary and secondary messages.
+/// Demonstrates generating a MaxiCode barcode, converting it to a byte array,
+/// and decoding it to retrieve both primary (postal) and secondary (custom) messages.
///
class Program
{
///
- /// Entry point of the example. Generates a MaxiCode, writes it to a PNG stream,
- /// and reads the barcode back, printing decoded information to the console.
+ /// Entry point of the example.
///
static void Main()
{
- // ------------------------------------------------------------
- // 1. Create a MaxiCode codetext (Mode 2) with a standard secondary message.
- // ------------------------------------------------------------
- var maxiCodeCodetext = new MaxiCodeCodetextMode2
+ // Create a MaxiCode codetext (Mode 2) with a standard second message
+ var maxiCodeData = new MaxiCodeCodetextMode2
{
PostalCode = "524032140", // 9‑digit US postal code
- CountryCode = 56, // Country code
- ServiceCategory = 999 // Service category
+ CountryCode = 56, // Example country code
+ ServiceCategory = 999 // Example service category
};
-
var secondMessage = new MaxiCodeStandardSecondMessage
{
- Message = "Sample secondary message"
+ Message = "Test message"
};
- maxiCodeCodetext.SecondMessage = secondMessage;
+ maxiCodeData.SecondMessage = secondMessage;
- // ------------------------------------------------------------
- // 2. Generate the barcode image using ComplexBarcodeGenerator.
- // ------------------------------------------------------------
- using (var complexGenerator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ // Generate the MaxiCode image into a memory stream
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
{
- // Generate the barcode as a bitmap.
- using (var bitmap = complexGenerator.GenerateBarCodeImage())
+ using (var imageStream = new MemoryStream())
{
- // Save the bitmap to a memory stream in PNG format.
- using (var imageStream = new MemoryStream())
- {
- bitmap.Save(imageStream, ImageFormat.Png);
- imageStream.Position = 0; // Reset stream position for reading.
+ // Save the generated barcode as PNG into the stream
+ generator.Save(imageStream, BarCodeImageFormat.Png);
+ byte[] imageBytes = imageStream.ToArray();
- // ------------------------------------------------------------
- // 3. Decode the MaxiCode from the byte array (memory stream).
- // ------------------------------------------------------------
- using (var reader = new BarCodeReader())
+ // Decode the image from the byte array
+ using (var inputStream = new MemoryStream(imageBytes))
+ {
+ using (var reader = new BarCodeReader(inputStream, DecodeType.MaxiCode))
{
- // Set the image source for the reader.
- reader.SetBarCodeImage(imageStream);
-
- // Restrict decoding to MaxiCode symbols only.
- reader.BarCodeReadType = DecodeType.MaxiCode;
-
- // Iterate through all detected barcodes.
+ // Iterate through all detected barcodes (should be one)
foreach (var result in reader.ReadBarCodes())
{
- Console.WriteLine($"Detected barcode type: {result.CodeTypeName}");
- Console.WriteLine($"Raw CodeText: {result.CodeText}");
+ // Retrieve the MaxiCode mode from the extended parameters
+ var mode = result.Extended.MaxiCode.Mode;
- // Decode the complex codetext to obtain structured data.
- var decoded = ComplexCodetextReader.TryDecodeMaxiCode(
- result.Extended.MaxiCode.MaxiCodeMode,
- result.CodeText);
+ // Decode the raw codetext into a structured object
+ var decoded = ComplexCodetextReader.TryDecodeMaxiCode(mode, result.CodeText);
- // --------------------------------------------------------
- // 4. Process decoded data for Mode 2 (primary & secondary messages).
- // --------------------------------------------------------
- if (decoded is MaxiCodeCodetextMode2 mode2)
+ // Output primary (postal) and secondary (message) information
+ if (decoded is MaxiCodeCodetextMode2 m2)
{
- Console.WriteLine("=== Primary Message ===");
- Console.WriteLine($"Postal Code: {mode2.PostalCode}");
- Console.WriteLine($"Country Code: {mode2.CountryCode}");
- Console.WriteLine($"Service Category: {mode2.ServiceCategory}");
+ Console.WriteLine($"Postal Code: {m2.PostalCode}");
+ Console.WriteLine($"Country Code: {m2.CountryCode}");
+ Console.WriteLine($"Service Category: {m2.ServiceCategory}");
- Console.WriteLine("=== Secondary Message ===");
- if (mode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
+ if (m2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
{
- Console.WriteLine($"Message: {stdMsg.Message}");
- }
- else if (mode2.SecondMessage is MaxiCodeStructuredSecondMessage structMsg)
- {
- Console.WriteLine("Identifiers:");
- foreach (var id in structMsg.Identifiers)
- {
- Console.WriteLine($" {id}");
- }
- Console.WriteLine($"Year: {structMsg.Year}");
+ Console.WriteLine($"Second Message: {stdMsg.Message}");
}
}
- else if (decoded is MaxiCodeCodetextMode3 mode3)
+ else if (decoded is MaxiCodeCodetextMode3 m3)
{
- // Handling for Mode 3 can be added here if required.
- Console.WriteLine("Decoded as MaxiCode Mode 3 (not shown in this sample).");
+ Console.WriteLine($"Postal Code: {m3.PostalCode}");
+ Console.WriteLine($"Country Code: {m3.CountryCode}");
+ Console.WriteLine($"Service Category: {m3.ServiceCategory}");
+
+ if (m3.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
+ {
+ Console.WriteLine($"Second Message: {stdMsg.Message}");
+ }
}
else
{
- Console.WriteLine("Unable to decode MaxiCode complex codetext.");
+ Console.WriteLine("Decoded MaxiCode type is not recognized.");
}
}
}
diff --git a/maxicode-barcode/configure-barcodereader-to-ignore-checksum-errors-while-decoding-maxicode-barcodes-in-high-noise-environment.cs b/maxicode-barcode/configure-barcodereader-to-ignore-checksum-errors-while-decoding-maxicode-barcodes-in-high-noise-environment.cs
index 9d8ccb6..61bd6f2 100644
--- a/maxicode-barcode/configure-barcodereader-to-ignore-checksum-errors-while-decoding-maxicode-barcodes-in-high-noise-environment.cs
+++ b/maxicode-barcode/configure-barcodereader-to-ignore-checksum-errors-while-decoding-maxicode-barcodes-in-high-noise-environment.cs
@@ -1,75 +1,56 @@
-// Title: Decode MaxiCode with checksum errors ignored
-// Description: Demonstrates configuring BarCodeReader to ignore checksum validation while decoding MaxiCode barcodes in noisy images.
-// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on error‑tolerant decoding. It shows how to use BarCodeReader, QualitySettings, and BarcodeSettings to handle damaged or high‑noise MaxiCode symbols, a common requirement for logistics and shipping applications where barcode integrity may be compromised.
+// Title: Decode MaxiCode with checksum validation disabled
+// Description: Demonstrates configuring BarcodeReader to ignore checksum errors when decoding MaxiCode barcodes, useful in noisy environments.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, focusing on reading complex symbologies such as MaxiCode. It showcases key API classes like BarCodeReader, BarcodeSettings, and QualitySettings, illustrating how to adjust checksum validation and quality parameters for high‑noise scenarios. Developers working with barcode scanning in challenging conditions can use this pattern to improve detection reliability.
// Prompt: Configure BarcodeReader to ignore checksum errors while decoding MaxiCode barcodes in a high‑noise environment.
-// Tags: maxicode, checksum, ignore, barcodereader, qualitysettings, barcodesettings, decoding, aspose.barcode
+// Tags: maxicode, checksum, barcodereader, decoding, qualitysettings, aspnet, csharp
using System;
using System.IO;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.BarCode.ComplexBarcode;
-using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates configuring the BarCodeReader to ignore checksum errors when decoding MaxiCode barcodes,
-/// useful in high‑noise environments.
+/// Example program that generates a MaxiCode barcode and reads it while ignoring checksum errors.
///
class Program
{
///
- /// Entry point of the example. Generates a MaxiCode image, then reads it while allowing incorrect checksums.
+ /// Entry point. Generates a MaxiCode (Mode 2) barcode, then reads it with checksum validation turned off.
///
static void Main()
{
- // Create a simple MaxiCode codetext (Mode4 with a short message)
- var maxiCodeCodetext = new MaxiCodeStandardCodetext
+ // Create a sample MaxiCode (Mode 2) codetext with postal, country, and service information.
+ var maxiCodeData = new MaxiCodeCodetextMode2
{
- Mode = MaxiCodeMode.Mode4,
- Message = "Test"
+ PostalCode = "524032140",
+ CountryCode = 56,
+ ServiceCategory = 999,
+ SecondMessage = new MaxiCodeStandardSecondMessage { Message = "Test" }
};
- // Generate the MaxiCode image using ComplexBarcodeGenerator
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ // Generate the barcode image into a memory stream (PNG format).
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
+ using (var ms = new MemoryStream())
{
- // Generate bitmap representation of the barcode
- using (Bitmap bitmap = generator.GenerateBarCodeImage())
- {
- // Save bitmap to a memory stream in PNG format
- using (var imageStream = new MemoryStream())
- {
- bitmap.Save(imageStream, ImageFormat.Png);
- imageStream.Position = 0; // Reset stream position for reading
-
- // Initialize BarCodeReader for MaxiCode with high-quality settings
- using (var reader = new BarCodeReader(imageStream, DecodeType.MaxiCode))
- {
- // Allow recognition of barcodes with incorrect checksum or damaged data
- reader.QualitySettings.AllowIncorrectBarcodes = true;
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0; // Reset stream position for reading.
- // Disable checksum validation (reinforces ignoring checksum errors)
- reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.Off;
+ // Initialize the reader for MaxiCode symbology.
+ using (var reader = new BarCodeReader(ms, DecodeType.MaxiCode))
+ {
+ // Disable checksum validation to tolerate errors in noisy captures.
+ reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.Off;
- // Read barcodes from the image
- BarCodeResult[] results = reader.ReadBarCodes();
+ // Adjust quality settings to allow incorrect barcodes and speed up processing.
+ reader.QualitySettings.AllowIncorrectBarcodes = true;
+ reader.QualitySettings.Deconvolution = DeconvolutionMode.Fast;
- if (results.Length == 0)
- {
- Console.WriteLine("No MaxiCode barcode detected.");
- }
- else
- {
- // Output details of each detected barcode
- foreach (var result in results)
- {
- Console.WriteLine($"Detected Type: {result.CodeTypeName}");
- Console.WriteLine($"Code Text: {result.CodeText}");
- Console.WriteLine($"Confidence: {result.Confidence}");
- Console.WriteLine($"Reading Quality: {result.ReadingQuality}");
- }
- }
- }
+ // Perform recognition and output results.
+ foreach (var result in reader.ReadBarCodes())
+ {
+ Console.WriteLine($"Detected type: {result.CodeTypeName}");
+ Console.WriteLine($"Code text: {result.CodeText}");
}
}
}
diff --git a/maxicode-barcode/create-aspnet-mvc-action-that-returns-generated-maxicode-barcode-image-based-on-query-string-parameters.cs b/maxicode-barcode/create-aspnet-mvc-action-that-returns-generated-maxicode-barcode-image-based-on-query-string-parameters.cs
index 73d8ef8..6e774dc 100644
--- a/maxicode-barcode/create-aspnet-mvc-action-that-returns-generated-maxicode-barcode-image-based-on-query-string-parameters.cs
+++ b/maxicode-barcode/create-aspnet-mvc-action-that-returns-generated-maxicode-barcode-image-based-on-query-string-parameters.cs
@@ -1,68 +1,51 @@
-// Title: Generate MaxiCode Barcode in ASP.NET MVC Action
-// Description: Demonstrates creating a MaxiCode barcode image using Aspose.BarCode based on query string parameters.
-// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator together with MaxiCode codetext classes (MaxiCodeCodetextMode2, MaxiCodeCodetextMode3, MaxiCodeStandardCodetext) to produce PNG images. Typical scenarios include shipping labels, parcel tracking, and logistics applications where MaxiCode is required. Developers often need to build MVC actions that return barcode images directly to the client, and this snippet illustrates the core API calls and parameter handling.
+// Title: Generate MaxiCode barcode image and output as Base64 PNG
+// Description: This console example demonstrates how to create a MaxiCode barcode (mode 2 or 3) using Aspose.BarCode and output the PNG image as a Base64 string. It shows how to set postal code, country code, service category, and a secondary message.
+// Category-Description: Aspose.BarCode examples for complex barcode generation illustrate the use of ComplexBarcodeGenerator and specific codetext classes (e.g., MaxiCodeCodetextMode2, MaxiCodeCodetextMode3). Developers commonly need to generate MaxiCode symbols for shipping and logistics, customize fields such as postal code and service category, and return the image in web scenarios (e.g., ASP.NET MVC actions). This snippet provides a reusable pattern for creating and encoding the barcode image.
// Prompt: Create an ASP.NET MVC action that returns a generated MaxiCode barcode image based on query string parameters.
-// Tags: maxicode, barcode, generation, aspnet mvc, image, png, aspose.barcode, complexbarcode
+// Tags: maxicode, barcode, generation, png, base64, aspnet-mvc, aspnet, aspnet-mvc-action, aspose.barcode, complexbarcode
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.Drawing.Imaging;
///
-/// Console program that mimics an ASP.NET MVC action for generating a MaxiCode barcode image.
-/// In a real MVC controller the logic would be placed inside an action method returning a FileResult.
+/// Demonstrates generation of a MaxiCode barcode (mode 2 or 3) and outputs the PNG image as a Base64 string.
///
class Program
{
///
- /// Entry point that parses parameters, builds the appropriate MaxiCode codetext,
- /// generates the barcode image, and saves it as a PNG file.
+ /// Entry point that parses command‑line arguments, creates the appropriate MaxiCode codetext,
+ /// generates the barcode image, and writes the Base64‑encoded PNG to the console.
///
- /// Command‑line arguments used as stand‑in for query string values.
+ ///
+ /// Expected arguments:
+ /// 0 – mode (2 or 3)
+ /// 1 – postalCode
+ /// 2 – countryCode (int)
+ /// 3 – serviceCategory (int)
+ /// 4 – message (standard second message)
+ ///
static void Main(string[] args)
{
- // --------------------------------------------------------------------
- // Default parameters (used when not enough command‑line arguments are supplied)
- // --------------------------------------------------------------------
- int mode = 2; // MaxiCode mode (2,3,4,5,6)
- string postalCode = "524032140"; // 9‑digit for mode 2, 6‑char for mode 3
- int countryCode = 56; // 3‑digit numeric country code
- int serviceCategory = 999; // 3‑digit service category
- string message = "Sample message"; // Standard second message
-
- // --------------------------------------------------------------------
- // Parse command‑line arguments if provided (simulating query string)
- // Expected order: mode postalCode countryCode serviceCategory message
- // --------------------------------------------------------------------
- try
- {
- if (args.Length > 0) mode = int.Parse(args[0]);
- if (args.Length > 1) postalCode = args[1];
- if (args.Length > 2) countryCode = int.Parse(args[2]);
- if (args.Length > 3) serviceCategory = int.Parse(args[3]);
- if (args.Length > 4) message = args[4];
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Argument parsing error: {ex.Message}");
- Console.WriteLine("Using default values.");
- }
-
- // --------------------------------------------------------------------
- // Validate the requested MaxiCode mode
- // --------------------------------------------------------------------
- if (mode < 2 || mode > 6)
+ // Validate that all required arguments are supplied.
+ if (args.Length < 5)
{
- Console.WriteLine("Invalid MaxiCode mode. Supported values are 2,3,4,5,6.");
+ Console.WriteLine("Usage: ");
return;
}
- // --------------------------------------------------------------------
- // Build the appropriate codetext object based on the selected mode
- // --------------------------------------------------------------------
- IComplexCodetext codetext;
+ // Parse input parameters.
+ int mode = int.Parse(args[0]);
+ string postalCode = args[1];
+ int countryCode = int.Parse(args[2]);
+ int serviceCategory = int.Parse(args[3]);
+ string message = args[4];
+
+ // Create the appropriate MaxiCode codetext object based on the selected mode.
+ MaxiCodeCodetext maxiCodeCodetext;
if (mode == 2)
{
var ct = new MaxiCodeCodetextMode2
@@ -72,7 +55,7 @@ static void Main(string[] args)
ServiceCategory = serviceCategory,
SecondMessage = new MaxiCodeStandardSecondMessage { Message = message }
};
- codetext = ct;
+ maxiCodeCodetext = ct;
}
else if (mode == 3)
{
@@ -83,41 +66,30 @@ static void Main(string[] args)
ServiceCategory = serviceCategory,
SecondMessage = new MaxiCodeStandardSecondMessage { Message = message }
};
- codetext = ct;
+ maxiCodeCodetext = ct;
}
- else // modes 4,5,6 use standard codetext
+ else
{
- var ct = new MaxiCodeStandardCodetext
- {
- Mode = mode switch
- {
- 4 => MaxiCodeMode.Mode4,
- 5 => MaxiCodeMode.Mode5,
- 6 => MaxiCodeMode.Mode6,
- _ => throw new ArgumentOutOfRangeException()
- },
- Message = message
- };
- codetext = ct;
+ Console.WriteLine("Supported modes are 2 and 3.");
+ return;
}
- // --------------------------------------------------------------------
- // Define the output file path (in a real MVC action this would be streamed)
- // --------------------------------------------------------------------
- string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "maxicode.png");
-
- // --------------------------------------------------------------------
- // Generate the barcode image and save it as PNG
- // --------------------------------------------------------------------
- using (var generator = new ComplexBarcodeGenerator(codetext))
+ // Generate the barcode using ComplexBarcodeGenerator.
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
{
- // Generate the bitmap (optional, GenerateBarCodeImage returns the bitmap)
- generator.GenerateBarCodeImage();
+ using (var memory = new MemoryStream())
+ {
+ // Save the barcode as PNG into the memory stream.
+ generator.Save(memory, BarCodeImageFormat.Png);
+ byte[] pngBytes = memory.ToArray();
- // Save the image to the specified path
- generator.Save(outputPath, BarCodeImageFormat.Png);
+ // Convert the PNG bytes to a Base64 string and write to console.
+ string base64 = Convert.ToBase64String(pngBytes);
+ Console.WriteLine(base64);
+ }
}
- Console.WriteLine($"MaxiCode barcode generated (mode {mode}) and saved to: {outputPath}");
+ // Exit with success code.
+ Environment.Exit(0);
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/create-console-utility-that-reads-list-of-codetext-strings-and-outputs-corresponding-maxicode-png-files.cs b/maxicode-barcode/create-console-utility-that-reads-list-of-codetext-strings-and-outputs-corresponding-maxicode-png-files.cs
index 36dc8b2..e296f16 100644
--- a/maxicode-barcode/create-console-utility-that-reads-list-of-codetext-strings-and-outputs-corresponding-maxicode-png-files.cs
+++ b/maxicode-barcode/create-console-utility-that-reads-list-of-codetext-strings-and-outputs-corresponding-maxicode-png-files.cs
@@ -1,54 +1,69 @@
-// Title: Generate MaxiCode PNG files from a list of codetext strings
-// Description: Demonstrates how to create MaxiCode barcodes and save them as PNG images using Aspose.BarCode.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of EncodeTypes.MaxiCode with the BarcodeGenerator class. Developers often need to produce MaxiCode symbols for shipping, logistics, and tracking applications; this snippet illustrates typical setup, resolution configuration, and image export to PNG format, serving as a reference for similar console utilities.
+// Title: Generate MaxiCode PNG files from codetext list
+// Description: Reads a text file where each line contains a codetext string and creates a MaxiCode barcode image (PNG) for each entry.
+// Category-Description: Demonstrates Aspose.BarCode generation of MaxiCode symbology using the BarcodeGenerator class. This example belongs to the barcode creation category, showing how to configure encoding, handle invalid codetext, and save images in PNG format. Developers working with shipping, logistics, or inventory systems often need to produce MaxiCode barcodes programmatically.
// Prompt: Create a console utility that reads a list of codetext strings and outputs corresponding MaxiCode PNG files.
-// Tags: maxicode, barcode generation, png output, aspose.barcode, console utility, encode types
+// Tags: barcode, maxicode, generation, png, console, aspose.barcode, aspnet
using System;
-using Aspose.BarCode.Generation;
+using System.IO;
using Aspose.BarCode;
+using Aspose.BarCode.Generation;
+using Aspose.Drawing.Imaging;
///
-/// Console application that generates MaxiCode barcodes from predefined codetext strings
-/// and saves each barcode as a PNG image file.
+/// Console utility that reads codetext strings from a file and generates MaxiCode PNG images.
///
class Program
{
///
- /// Entry point of the application. Iterates over a collection of codetext strings,
- /// creates a MaxiCode barcode for each, and writes the resulting PNG file to disk.
+ /// Entry point. Processes each codetext line, generates a MaxiCode barcode, and saves it as a PNG file.
///
static void Main()
{
- // Define a sample list of MaxiCode codetext strings.
- // In a real scenario these could be read from a file, database, or user input.
- string[] codetexts = new[]
+ // Path to the text file containing codetext strings (one per line)
+ const string inputFile = "codetexts.txt";
+
+ // Verify that the input file exists before proceeding
+ if (!File.Exists(inputFile))
{
- "524032140056999Test message", // Mode 2 example
- "B1050 056999Another message", // Mode 3 example (space separates postal code)
- "Sample MaxiCode Text 1",
- "Sample MaxiCode Text 2",
- "Sample MaxiCode Text 3"
- };
-
- // Iterate through each codetext, generate a barcode, and save it as a PNG file.
- for (int i = 0; i < codetexts.Length; i++)
+ Console.WriteLine($"Input file '{inputFile}' not found.");
+ return;
+ }
+
+ // Read all lines from the file; each line represents a separate codetext
+ string[] lines = File.ReadAllLines(inputFile);
+
+ // Iterate through each line, generating a barcode for non‑empty entries
+ for (int i = 0; i < lines.Length; i++)
{
- string text = codetexts[i];
- string fileName = $"maxicode_{i + 1}.png";
+ string codeText = lines[i].Trim();
+
+ // Skip empty lines to avoid generating empty barcodes
+ if (string.IsNullOrEmpty(codeText))
+ continue;
- // Create a BarcodeGenerator for MaxiCode using the current codetext.
- using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, text))
+ // Create a MaxiCode generator with the current codetext
+ using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, codeText))
{
- // Optional: set the image resolution (dots per inch) if higher quality is required.
- generator.Parameters.Resolution = 300;
+ // Throw an exception if the codetext is not valid for MaxiCode
+ generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = true;
- // Save the generated barcode image in PNG format.
- generator.Save(fileName, BarCodeImageFormat.Png);
- }
+ // Optional: customize colors (commented out by default)
+ // generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ // generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- // Output a confirmation message to the console.
- Console.WriteLine($"Generated {fileName} for codetext: {text}");
+ // Save the generated image to a memory stream in PNG format
+ using (var memoryStream = new MemoryStream())
+ {
+ generator.Save(memoryStream, BarCodeImageFormat.Png);
+ memoryStream.Position = 0;
+
+ // Write the PNG file to disk with a sequential name
+ string outputPath = $"maxicode_{i + 1}.png";
+ File.WriteAllBytes(outputPath, memoryStream.ToArray());
+ Console.WriteLine($"Generated '{outputPath}' for codetext: {codeText}");
+ }
+ }
}
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/create-helper-method-that-builds-maxicode-structured-secondary-messages-from-address-components.cs b/maxicode-barcode/create-helper-method-that-builds-maxicode-structured-secondary-messages-from-address-components.cs
index fe61662..276937d 100644
--- a/maxicode-barcode/create-helper-method-that-builds-maxicode-structured-secondary-messages-from-address-components.cs
+++ b/maxicode-barcode/create-helper-method-that-builds-maxicode-structured-secondary-messages-from-address-components.cs
@@ -1,71 +1,88 @@
-// Title: Build MaxiCode Structured Secondary Message Helper
-// Description: Demonstrates creating a MaxiCode barcode with a structured secondary message built from address components.
-// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on MaxiCode symbology. It showcases the use of MaxiCodeCodetextMode2, MaxiCodeStructuredSecondMessage, and ComplexBarcodeGenerator classes to encode postal information and a custom secondary message. Developers often need to generate MaxiCode barcodes for shipping and logistics, requiring precise formatting of address data and service categories.
+// Title: Generate MaxiCode barcode with structured secondary message
+// Description: Demonstrates building a MaxiCode structured secondary message from address components and generating a Mode 2 MaxiCode barcode image.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of MaxiCodeCodetextMode2, MaxiCodeStructuredSecondMessage, and ComplexBarcodeGenerator to create postal‑oriented MaxiCode symbols. Developers working with shipping, logistics, or postal automation frequently need to encode address data and secondary messages in MaxiCode barcodes; this snippet illustrates the typical workflow and key API classes for that scenario.
// Prompt: Create a helper method that builds MaxiCode structured secondary messages from address components.
-// Tags: maxicode, structured secondary message, barcode generation, aspnet, aspose.barcode, complexbarcode, helper method
+// Tags: maxicode, structured secondary message, barcode generation, aspose.barcode, complexbarcode, c#
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates building a MaxiCode barcode with a structured secondary message.
+/// Example program that builds a MaxiCode structured secondary message and generates a Mode 2 MaxiCode barcode.
///
class Program
{
///
- /// Builds a structured secondary message for MaxiCode from address components.
+ /// Builds a structured second message for MaxiCode from address components.
///
- /// First address line (e.g., street).
- /// Second address line (e.g., city).
+ /// Array of address lines (at least one required).
+ /// City name.
/// State abbreviation.
- /// Two‑digit year value.
+ /// Two‑digit year (0‑99).
/// A populated instance.
- static MaxiCodeStructuredSecondMessage BuildStructuredSecondMessage(string line1, string line2, string state, int year)
+ static MaxiCodeStructuredSecondMessage BuildStructuredSecondMessage(string[] addressLines, string city, string state, int year)
{
- // Create a new structured message container.
- var message = new MaxiCodeStructuredSecondMessage();
+ // Validate input parameters
+ if (addressLines == null) throw new ArgumentNullException(nameof(addressLines));
+ if (addressLines.Length == 0) throw new ArgumentException("At least one address line is required.", nameof(addressLines));
+ if (string.IsNullOrWhiteSpace(city)) throw new ArgumentException("City is required.", nameof(city));
+ if (string.IsNullOrWhiteSpace(state)) throw new ArgumentException("State is required.", nameof(state));
+ if (year < 0 || year > 99) throw new ArgumentOutOfRangeException(nameof(year), "Year must be a two‑digit value (0‑99).");
- // Add address components to the message in the required order.
- message.Add(line1);
- message.Add(line2);
- message.Add(state);
+ var structuredMessage = new MaxiCodeStructuredSecondMessage();
- // Set the year field.
- message.Year = year;
+ // Add each address line to the structured message
+ foreach (var line in addressLines)
+ {
+ structuredMessage.Add(line);
+ }
+
+ // Append city and state
+ structuredMessage.Add(city);
+ structuredMessage.Add(state);
- return message;
+ // Set the two‑digit year field
+ structuredMessage.Year = year;
+
+ return structuredMessage;
}
///
- /// Entry point. Generates a MaxiCode barcode using address components and saves it as an image.
+ /// Entry point of the program. Generates a MaxiCode barcode image and writes its size to the console.
///
static void Main()
{
- // Sample address components.
- string street = "634 ALPHA DRIVE";
+ // Sample address components used to build the secondary message
+ string[] addressLines = { "634 ALPHA DRIVE" };
string city = "PITTSBURGH";
string state = "PA";
int year = 99;
- // Configure MaxiCode codetext for Mode 2 (postal code, country, service category).
- var maxiCodeCodetext = new MaxiCodeCodetextMode2
+ // Configure MaxiCode codetext for Mode 2 (USA postal code)
+ var maxiCodeData = new MaxiCodeCodetextMode2
{
- PostalCode = "524032140", // 9‑digit US postal code.
- CountryCode = 056, // USA numeric country code.
- ServiceCategory = 999 // Example service category.
+ PostalCode = "524032140",
+ CountryCode = 56,
+ ServiceCategory = 999,
+ SecondMessage = BuildStructuredSecondMessage(addressLines, city, state, year)
};
- // Assign the structured secondary message built from the address components.
- maxiCodeCodetext.SecondMessage = BuildStructuredSecondMessage(street, city, state, year);
-
- // Generate the MaxiCode barcode and save it as a PNG image.
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ // Generate the barcode using ComplexBarcodeGenerator
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
{
- generator.Save("maxicode.png");
+ generator.GenerateBarCodeImage();
+
+ // Save the generated image to a memory stream in PNG format
+ using (var ms = new MemoryStream())
+ {
+ generator.Save(ms, BarCodeImageFormat.Png);
+ Console.WriteLine($"Generated MaxiCode barcode image size: {ms.Length} bytes");
+ }
}
- Console.WriteLine("MaxiCode barcode generated: maxicode.png");
+ // Program terminates without waiting for user input
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/create-maxicode-mode-3-barcode-using-structured-secondary-message-and-export-image-as-jpeg.cs b/maxicode-barcode/create-maxicode-mode-3-barcode-using-structured-secondary-message-and-export-image-as-jpeg.cs
index 0759e77..da1ac7a 100644
--- a/maxicode-barcode/create-maxicode-mode-3-barcode-using-structured-secondary-message-and-export-image-as-jpeg.cs
+++ b/maxicode-barcode/create-maxicode-mode-3-barcode-using-structured-secondary-message-and-export-image-as-jpeg.cs
@@ -1,49 +1,52 @@
-// Title: Create MaxiCode Mode 3 Barcode with Structured Secondary Message
-// Description: Demonstrates how to generate a MaxiCode Mode 3 barcode that includes a structured secondary message and export the result as a JPEG image.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, focusing on complex barcode types such as MaxiCode. It showcases the use of MaxiCodeCodetextMode3, MaxiCodeStructuredSecondMessage, and ComplexBarcodeGenerator classes to create high‑density 2‑D barcodes for shipping and logistics applications. Developers often need to embed address information and other structured data within MaxiCode symbols for automated sorting and tracking.
+// Title: Create MaxiCode Mode 3 barcode with structured secondary message and save as JPEG
+// Description: Demonstrates how to build a MaxiCode Mode 3 barcode, include a structured secondary message, and export the result as a JPEG image.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as MaxiCode. It shows usage of the MaxiCodeCodetextMode3, MaxiCodeStructuredSecondMessage, and ComplexBarcodeGenerator classes to configure postal information and secondary messages. Developers working with shipping labels, logistics, or any application that requires MaxiCode symbology can use this pattern to create and render barcodes in various image formats.
// Prompt: Create a MaxiCode Mode 3 barcode using a structured secondary message and export the image as JPEG.
-// Tags: maxicode, mode3, structured-secondary-message, jpeg, barcode-generation, aspose.barcode, complexbarcode
+// Tags: maxicode, barcode, generation, jpeg, complexbarcode, aspose.barcode
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.Drawing.Imaging;
///
-/// Example program that creates a MaxiCode Mode 3 barcode with a structured secondary message
-/// and saves it as a JPEG file.
+/// Example program that generates a MaxiCode Mode 3 barcode with a structured secondary message
+/// and saves the resulting image as a JPEG file.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Builds the secondary message, configures the MaxiCode payload,
+ /// generates the barcode, and writes the JPEG image to disk.
///
static void Main()
{
- // Initialize a structured secondary message with address lines and year.
+ // Build a structured secondary message containing address lines and year
var structuredMessage = new MaxiCodeStructuredSecondMessage();
- structuredMessage.Add("634 ALPHA DRIVE"); // Street address
- structuredMessage.Add("PITTSBURGH"); // City
- structuredMessage.Add("PA"); // State
- structuredMessage.Year = 99; // Two‑digit year
+ structuredMessage.Add("634 ALPHA DRIVE");
+ structuredMessage.Add("PITTSBURGH");
+ structuredMessage.Add("PA");
+ structuredMessage.Year = 99;
- // Configure the MaxiCode Mode 3 codetext, including postal code, country code,
- // service category, and the previously created secondary message.
- var maxiCode = new MaxiCodeCodetextMode3
+ // Configure the MaxiCode Mode 3 codetext with postal data and the secondary message
+ var maxiCodeCodetext = new MaxiCodeCodetextMode3
{
- PostalCode = "B1050", // 6 alphanumeric characters
- CountryCode = 56, // 3‑digit country code
+ PostalCode = "B1050",
+ CountryCode = 56,
ServiceCategory = 999,
SecondMessage = structuredMessage
};
- // Generate the barcode using ComplexBarcodeGenerator and save it as a JPEG image.
- using (var generator = new ComplexBarcodeGenerator(maxiCode))
+ // Generate the barcode using ComplexBarcodeGenerator and save it as a JPEG image
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
{
- generator.Save("maxicode_mode3.jpeg");
+ using (var memoryStream = new MemoryStream())
+ {
+ generator.Save(memoryStream, BarCodeImageFormat.Jpeg);
+ File.WriteAllBytes("maxicode_mode3.jpg", memoryStream.ToArray());
+ }
}
-
- // Inform the user that the barcode has been saved.
- Console.WriteLine("MaxiCode Mode 3 barcode saved as maxicode_mode3.jpeg");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/create-maxicode-mode-6-barcode-apply-transparent-background-and-write-file-to-memory-stream.cs b/maxicode-barcode/create-maxicode-mode-6-barcode-apply-transparent-background-and-write-file-to-memory-stream.cs
index f5985a2..b1ca99f 100644
--- a/maxicode-barcode/create-maxicode-mode-6-barcode-apply-transparent-background-and-write-file-to-memory-stream.cs
+++ b/maxicode-barcode/create-maxicode-mode-6-barcode-apply-transparent-background-and-write-file-to-memory-stream.cs
@@ -1,8 +1,8 @@
-// Title: Generate MaxiCode Mode 6 Barcode with Transparent Background
-// Description: Creates a MaxiCode Mode 6 barcode, applies a transparent background, and writes the PNG image to a memory stream.
-// Category-Description: This example demonstrates the use of Aspose.BarCode's ComplexBarcodeGenerator to produce MaxiCode symbols, a 2‑D barcode used in logistics and shipping. It showcases setting barcode parameters such as mode and background color, and saving the result to a stream in PNG format. Developers working with advanced barcode symbologies, custom rendering options, or in‑memory image handling will find this pattern useful.
+// Title: Generate MaxiCode Mode 6 barcode with transparent background and save to memory stream
+// Description: Demonstrates how to create a MaxiCode Mode 6 barcode, set a transparent background, and write the PNG image to a MemoryStream using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode symbologies such as MaxiCode. It showcases the use of ComplexBarcodeGenerator, MaxiCodeStandardCodetext, and image formatting options. Developers often need to generate high‑density 2‑D barcodes for logistics and apply custom visual settings like transparent backgrounds before streaming the result.
// Prompt: Create a MaxiCode Mode 6 barcode, apply a transparent background, and write the file to a memory stream.
-// Tags: maxicode, mode6, transparent background, memory stream, png, aspose.barcode, barcode generation
+// Tags: maxicode, mode6, transparent background, memory stream, png, aspose.barcode, complexbarcodegenerator
using System;
using System.IO;
@@ -12,36 +12,37 @@
using Aspose.Drawing;
///
-/// Demonstrates generating a MaxiCode Mode 6 barcode with a transparent background
-/// and saving it to a memory stream as a PNG image.
+/// Demonstrates generating a MaxiCode Mode 6 barcode with a transparent background and saving it to a memory stream.
///
class Program
{
///
- /// Entry point of the example. Builds the barcode, configures rendering options,
- /// and writes the image to a .
+ /// Entry point of the example. Generates the barcode, applies visual settings, and outputs the image size.
///
static void Main()
{
- // Initialize MaxiCode codetext for Mode 6 and set the message payload.
- var maxiCodeCodetext = new MaxiCodeStandardCodetext
+ // Prepare MaxiCode standard codetext for Mode 6
+ var maxiCode = new MaxiCodeStandardCodetext
{
Mode = MaxiCodeMode.Mode6,
- Message = "Test message"
+ Message = "Sample message"
};
- // Create a ComplexBarcodeGenerator using the prepared codetext.
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ // Create a memory stream to hold the generated image
+ using (var ms = new MemoryStream())
{
- // Configure the barcode to have a transparent background.
- generator.Parameters.BackColor = Color.Transparent;
-
- // Save the generated barcode image to a memory stream in PNG format.
- using (var memoryStream = new MemoryStream())
+ // Initialize the complex barcode generator with the MaxiCode settings
+ using (var generator = new ComplexBarcodeGenerator(maxiCode))
{
- generator.Save(memoryStream, BarCodeImageFormat.Png);
- Console.WriteLine($"Barcode generated. Stream length: {memoryStream.Length} bytes.");
+ // Apply a transparent background to the barcode image
+ generator.Parameters.BackColor = Color.Transparent;
+
+ // Save the barcode as a PNG image into the memory stream
+ generator.Save(ms, BarCodeImageFormat.Png);
}
+
+ // Output the size of the generated image (for demonstration purposes)
+ Console.WriteLine($"Generated barcode image size: {ms.Length} bytes");
}
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/create-unit-test-that-verifies-generated-maxicode-mode-2-codetext-matches-expected-formatted-string.cs b/maxicode-barcode/create-unit-test-that-verifies-generated-maxicode-mode-2-codetext-matches-expected-formatted-string.cs
index 56d4382..ce2ef29 100644
--- a/maxicode-barcode/create-unit-test-that-verifies-generated-maxicode-mode-2-codetext-matches-expected-formatted-string.cs
+++ b/maxicode-barcode/create-unit-test-that-verifies-generated-maxicode-mode-2-codetext-matches-expected-formatted-string.cs
@@ -1,83 +1,100 @@
-// Title: Verify MaxiCode Mode 2 Codetext Generation
-// Description: Demonstrates a unit‑test‑style verification that the MaxiCode Mode 2 codetext produced by Aspose.BarCode matches the expected formatted string.
-// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on MaxiCode symbology. It shows how to use MaxiCodeCodetextMode2, MaxiCodeStandardSecondMessage, and ComplexBarcodeGenerator to construct and validate codetext without rendering an image. Developers working with shipping or logistics barcode solutions often need to ensure the encoded data follows the required format before creating the barcode image.
+// Title: Verify MaxiCode Mode 2 Codetext Generation with Aspose.BarCode
+// Description: Demonstrates how to generate a MaxiCode Mode 2 barcode, decode it, and assert that the codetext matches the expected formatted string.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, focusing on complex barcode types such as MaxiCode. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and BarCodeReader to create, save, and validate barcodes, a common task for developers implementing shipping or logistics solutions that require precise MaxiCode data encoding.
// Prompt: Create a unit test that verifies the generated MaxiCode Mode 2 codetext matches the expected formatted string.
-// Tags: maxicode, mode2, codetext, unit-test, aspose.barcode, complexbarcodegenerator
+// Tags: barcode, maxicode, mode2, unit-test, generation, recognition, aspose.barcode
using System;
-using Aspose.BarCode;
+using System.IO;
using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that builds a MaxiCode Mode 2 codetext, generates a barcode generator instance,
-/// and validates that the constructed codetext matches the expected formatted string.
+/// Contains the entry point that generates a MaxiCode Mode 2 barcode,
+/// decodes it, and validates the codetext against the expected value.
///
class Program
{
///
- /// Entry point of the example. Prepares expected values, constructs the codetext object,
- /// instantiates the generator, and verifies the resulting codetext.
+ /// Generates a temporary MaxiCode image, reads it back, and checks that
+ /// the decoded codetext and mode are as expected.
///
static void Main()
{
- // ------------------------------------------------------------
- // Prepare expected values for the MaxiCode components
- // ------------------------------------------------------------
- string expectedPostalCode = "524032140";
- int expectedCountryCode = 56; // will be formatted as three digits "056"
- int expectedServiceCategory = 999;
- string expectedMessage = "Test message";
-
- // Build the expected formatted codetext string according to MaxiCode Mode 2 rules
- string expectedCodetext = expectedPostalCode +
- expectedCountryCode.ToString("D3") +
- expectedServiceCategory.ToString("D3") +
- expectedMessage;
-
- // ------------------------------------------------------------
- // Create and populate the MaxiCode Mode 2 codetext object
- // ------------------------------------------------------------
- var maxiCodeCodetext = new MaxiCodeCodetextMode2
+ // Prepare test data for MaxiCode Mode 2
+ var maxiCodeData = new MaxiCodeCodetextMode2
{
- PostalCode = expectedPostalCode,
- CountryCode = expectedCountryCode,
- ServiceCategory = expectedServiceCategory
+ PostalCode = "524032140", // 9‑digit postal code
+ CountryCode = 56, // 3‑digit country code (leading zeros are optional)
+ ServiceCategory = 999 // 3‑digit service category
};
- // Attach the standard second message to the codetext
- var secondMessage = new MaxiCodeStandardSecondMessage
- {
- Message = expectedMessage
- };
- maxiCodeCodetext.SecondMessage = secondMessage;
+ // Optional: add a standard second message
+ var secondMessage = new MaxiCodeStandardSecondMessage { Message = "Test message" };
+ maxiCodeData.SecondMessage = secondMessage;
- // ------------------------------------------------------------
- // Initialize the ComplexBarcodeGenerator (required lifecycle)
- // ------------------------------------------------------------
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ // Expected codetext constructed by the complex barcode object itself
+ string expectedCodetext = maxiCodeData.GetConstructedCodetext();
+
+ // Generate the barcode image to a temporary file
+ string tempImagePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".png");
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
{
- // Image generation is unnecessary for this test, but the generator must be instantiated.
+ // Enable strict validation of codetext
+ generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = true;
generator.GenerateBarCodeImage();
+ generator.Save(tempImagePath);
}
- // ------------------------------------------------------------
- // Retrieve the constructed codetext from the object for verification
- // ------------------------------------------------------------
- string actualCodetext = maxiCodeCodetext.GetConstructedCodetext();
+ // Read and decode the generated barcode
+ bool testPassed = false;
+ using (var reader = new BarCodeReader(tempImagePath, DecodeType.MaxiCode))
+ {
+ var results = reader.ReadBarCodes();
+ foreach (var result in results)
+ {
+ // Verify that a codetext was decoded
+ if (string.IsNullOrEmpty(result.CodeText))
+ {
+ Console.WriteLine("FAILED: Decoded CodeText is null or empty.");
+ break;
+ }
+
+ // Verify that the decoded codetext matches the expected value
+ if (!result.CodeText.Equals(expectedCodetext, StringComparison.Ordinal))
+ {
+ Console.WriteLine($"FAILED: Expected CodeText '{expectedCodetext}' but got '{result.CodeText}'.");
+ break;
+ }
+
+ // Verify that the decoded mode is Mode2
+ if (result.Extended.MaxiCode.Mode != MaxiCodeMode.Mode2)
+ {
+ Console.WriteLine($"FAILED: Expected MaxiCode mode 'Mode2' but got '{result.Extended.MaxiCode.Mode}'.");
+ break;
+ }
+
+ // All checks passed
+ testPassed = true;
+ break; // only need first barcode
+ }
+ }
+
+ // Clean up temporary file
+ if (File.Exists(tempImagePath))
+ {
+ try { File.Delete(tempImagePath); } catch { /* ignore cleanup errors */ }
+ }
- // ------------------------------------------------------------
- // Verify that the generated codetext matches the expected format
- // ------------------------------------------------------------
- if (actualCodetext == expectedCodetext)
+ // Report result
+ if (testPassed)
{
- Console.WriteLine("Test Passed: Generated codetext matches expected.");
+ Console.WriteLine("PASSED: MaxiCode Mode 2 codetext matches expected formatted string.");
}
else
{
- Console.WriteLine("Test Failed:");
- Console.WriteLine($"Expected: \"{expectedCodetext}\"");
- Console.WriteLine($"Actual: \"{actualCodetext}\"");
+ Console.WriteLine("FAILED: One or more verification steps did not succeed.");
}
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/develop-web-api-endpoint-that-accepts-json-builds-maxicode-mode-3-codetext-and-returns-png-data.cs b/maxicode-barcode/develop-web-api-endpoint-that-accepts-json-builds-maxicode-mode-3-codetext-and-returns-png-data.cs
index c21912f..dd7f975 100644
--- a/maxicode-barcode/develop-web-api-endpoint-that-accepts-json-builds-maxicode-mode-3-codetext-and-returns-png-data.cs
+++ b/maxicode-barcode/develop-web-api-endpoint-that-accepts-json-builds-maxicode-mode-3-codetext-and-returns-png-data.cs
@@ -1,8 +1,8 @@
-// Title: Generate MaxiCode Mode 3 barcode and output PNG as Base64
-// Description: Demonstrates building a MaxiCode Mode 3 codetext from JSON input and returning the barcode image in PNG format.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as MaxiCode. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode3, and related classes to encode postal and service data. Developers creating shipping, logistics, or tracking solutions often need to generate MaxiCode barcodes for UPS and other carriers, and this snippet illustrates the typical workflow of parsing input, constructing codetext, and producing a PNG image.
+// Title: Generate MaxiCode Mode 3 Barcode and Return PNG via Web API Simulation
+// Description: Demonstrates how to deserialize a JSON request, build a MaxiCode Mode 3 codetext, and produce a PNG barcode image.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode3, and related classes to create MaxiCode symbols, a common requirement for shipping and logistics applications. Developers often need to accept JSON payloads, construct codetext, and return barcode images in web services.
// Prompt: Develop a Web API endpoint that accepts JSON, builds a MaxiCode Mode 3 codetext, and returns PNG data.
-// Tags: maxicode, barcode, generation, png, json, aspnet, aspose.barcode, complexbarcode
+// Tags: maxicode, mode3, barcode generation, png, aspnet, aspose.barcode, json, web api
using System;
using System.IO;
@@ -12,90 +12,83 @@
using Aspose.BarCode.ComplexBarcode;
using Aspose.Drawing.Imaging;
-namespace MaxiCodeConsoleApp
+namespace MaxiCodeMode3Demo
{
///
- /// Simple DTO matching the expected JSON structure for MaxiCode input data.
+ /// Represents the JSON payload that a client would POST to the API.
///
- public class MaxiCodeInput
+ public class MaxiCodeRequest
{
- public string PostalCode { get; set; }
- public int CountryCode { get; set; }
- public int ServiceCategory { get; set; }
- public string Message { get; set; }
+ public string PostalCode { get; set; } // 6‑character alphanumeric postal code
+ public int CountryCode { get; set; } // 3‑digit numeric country code
+ public int ServiceCategory { get; set; } // 3‑digit service category
+ public string Message { get; set; } // Standard second message text
}
///
- /// Console application that demonstrates generating a MaxiCode Mode 3 barcode from JSON input and outputting the PNG image as a Base64 string.
+ /// Simulates a Web API endpoint that creates a MaxiCode Mode 3 barcode from JSON input and returns PNG data.
///
class Program
{
///
- /// Entry point. Parses JSON input, creates MaxiCode codetext, generates a PNG barcode, and writes the image bytes as Base64 to the console.
+ /// Entry point that mimics handling a single HTTP request.
///
- /// Command‑line arguments; the first argument may contain a JSON payload.
- static void Main(string[] args)
+ static void Main()
{
- // NOTE:
- // The original request was for a Web API endpoint.
- // The snippet runner environment does not support hosting an HTTP server,
- // so this console application demonstrates the core logic:
- // - Parse JSON input (from command‑line argument or default)
- // - Build a MaxiCode Mode 3 codetext
- // - Generate a PNG image
- // - Output the PNG bytes as a Base64 string to the console
+ // -----------------------------------------------------------------
+ // NOTE: The snippet runner is a plain .NET console application.
+ // A real Web API host is not started; instead we simulate a single
+ // HTTP request/response flow in‑process.
+ // -----------------------------------------------------------------
- // Use the first command‑line argument as JSON if provided; otherwise fall back to a default payload.
- string json = args.Length > 0
- ? args[0]
- : "{\"PostalCode\":\"B1050\",\"CountryCode\":56,\"ServiceCategory\":999,\"Message\":\"Test message\"}";
-
- MaxiCodeInput input;
- try
+ // Example JSON payload that a client would POST to the API
+ string jsonPayload = @"
{
- // Deserialize the JSON payload into the DTO, ignoring case differences in property names.
- input = JsonSerializer.Deserialize(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
+ ""PostalCode"": ""B1050"",
+ ""CountryCode"": 56,
+ ""ServiceCategory"": 999,
+ ""Message"": ""Test message""
+ }";
- // Validate required fields.
- if (input == null ||
- string.IsNullOrWhiteSpace(input.PostalCode) ||
- string.IsNullOrWhiteSpace(input.Message))
- {
- throw new ArgumentException("Invalid JSON payload.");
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Error parsing input JSON: {ex.Message}");
- return;
- }
+ // Deserialize the JSON into a request object
+ MaxiCodeRequest request = JsonSerializer.Deserialize(jsonPayload);
- // Build the MaxiCode Mode 3 codetext using the input data.
- var codetext = new MaxiCodeCodetextMode3
+ // Build the MaxiCode Mode 3 codetext using the deserialized values
+ var maxiCodeData = new MaxiCodeCodetextMode3
{
- PostalCode = input.PostalCode,
- CountryCode = input.CountryCode,
- ServiceCategory = input.ServiceCategory
+ PostalCode = request.PostalCode,
+ CountryCode = request.CountryCode,
+ ServiceCategory = request.ServiceCategory
};
- // Attach the secondary message (free‑form text) to the codetext.
+ // Attach a standard second message (optional but commonly used)
var secondMessage = new MaxiCodeStandardSecondMessage
{
- Message = input.Message
+ Message = request.Message
};
- codetext.SecondMessage = secondMessage;
+ maxiCodeData.SecondMessage = secondMessage;
- // Generate the barcode and write PNG data to a memory stream.
- using (var generator = new ComplexBarcodeGenerator(codetext))
- using (var ms = new MemoryStream())
+ // Generate the barcode image and obtain PNG bytes
+ byte[] pngBytes;
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
{
- generator.Save(ms, BarCodeImageFormat.Png);
- byte[] pngBytes = ms.ToArray();
+ // Enable validation of the constructed codetext; throws if invalid
+ generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = true;
+
+ // Generate the image (optional – Save will invoke it if needed)
+ generator.GenerateBarCodeImage();
- // Convert the PNG bytes to a Base64 string for easy console output or API response.
- string base64 = Convert.ToBase64String(pngBytes);
- Console.WriteLine(base64);
+ // Save the generated image to a memory stream in PNG format
+ using (var ms = new MemoryStream())
+ {
+ generator.Save(ms, BarCodeImageFormat.Png);
+ pngBytes = ms.ToArray();
+ }
}
+
+ // Output the PNG data as a Base64 string (simulating HTTP response body)
+ string base64Png = Convert.ToBase64String(pngBytes);
+ Console.WriteLine(base64Png);
}
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/encode-numeric-postal-code-in-primary-message-of-maxicode-mode-2-and-verify-decoding-accuracy.cs b/maxicode-barcode/encode-numeric-postal-code-in-primary-message-of-maxicode-mode-2-and-verify-decoding-accuracy.cs
index 6db9a76..b5c0b7e 100644
--- a/maxicode-barcode/encode-numeric-postal-code-in-primary-message-of-maxicode-mode-2-and-verify-decoding-accuracy.cs
+++ b/maxicode-barcode/encode-numeric-postal-code-in-primary-message-of-maxicode-mode-2-and-verify-decoding-accuracy.cs
@@ -1,80 +1,74 @@
// Title: Encode and Verify MaxiCode Mode 2 Postal Code
-// Description: Demonstrates encoding a numeric postal code into the primary message of a MaxiCode Mode 2 barcode and validates the result by decoding the generated image.
-// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation and recognition category. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and BarCodeReader to create and read MaxiCode symbols. Developers working with high‑density 2‑D barcodes such as MaxiCode can use these APIs to embed structured data (e.g., postal codes) and verify encoding accuracy, a common requirement in logistics and shipping applications.
+// Description: Demonstrates encoding a numeric postal code into the primary message of a MaxiCode Mode 2 barcode, generating the image, and decoding it to confirm the data matches the original.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation and recognition category. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and BarCodeReader to create and read MaxiCode symbols. Developers working with shipping, logistics, or retail applications often need to encode structured data such as postal codes, country codes, and service categories into MaxiCode barcodes and verify their integrity.
// Prompt: Encode a numeric postal code in the primary message of a MaxiCode Mode 2 and verify decoding accuracy.
-// Tags: maxicode, mode2, barcode, encoding, decoding, aspose.barcode, complexbarcode, png
+// Tags: maxicode, mode2, barcode, encoding, decoding, aspose.barcode, complexbarcode, c#
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 creates a MaxiCode Mode 2 barcode containing a numeric postal code,
-/// saves it as a PNG image, and then reads the image back to verify that the encoded data
-/// matches the original input.
+/// then reads the barcode back to verify the encoded data.
///
class Program
{
///
- /// Entry point of the example. Generates the barcode, saves it, and validates decoding.
+ /// Entry point of the example. Generates a MaxiCode barcode, decodes it, and prints verification results.
///
static void Main()
{
- // Define the output file path for the generated barcode image.
- string outputPath = "maxicode_mode2.png";
+ // Define the numeric postal code (9 digits) and related MaxiCode fields.
+ const string postalCode = "123456789";
+ const int countryCode = 840; // USA numeric country code
+ const int serviceCategory = 999; // Example service category
- // Build the MaxiCode Mode 2 codetext with required fields.
- var maxiCodeCodetext = new MaxiCodeCodetextMode2
+ // Build the complex codetext for MaxiCode Mode 2 using the provided values.
+ var maxiCodeData = new MaxiCodeCodetextMode2
{
- PostalCode = "123456789", // 9‑digit numeric postal code (primary message)
- CountryCode = 840, // Numeric ISO country code for USA
- ServiceCategory = 999 // Example service category identifier
+ PostalCode = postalCode,
+ CountryCode = countryCode,
+ ServiceCategory = serviceCategory,
+ // Optional second message; can contain any additional information.
+ SecondMessage = new MaxiCodeStandardSecondMessage { Message = "Sample data" }
};
- // Optional: add a standard secondary message to the MaxiCode.
- var secondMessage = new MaxiCodeStandardSecondMessage
+ // Generate the barcode image and store it in a memory stream.
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
{
- Message = "Sample secondary data"
- };
- maxiCodeCodetext.SecondMessage = secondMessage;
-
- // Generate the MaxiCode image using the ComplexBarcodeGenerator.
- using (var complexGenerator = new ComplexBarcodeGenerator(maxiCodeCodetext))
- {
- complexGenerator.Save(outputPath, BarCodeImageFormat.Png);
- }
-
- // Verify that the image file was created successfully.
- if (!File.Exists(outputPath))
- {
- Console.WriteLine("Failed to create barcode image.");
- return;
- }
-
- // Read and decode the generated barcode image.
- using (var reader = new BarCodeReader(outputPath, DecodeType.MaxiCode))
- {
- foreach (var result in reader.ReadBarCodes())
+ using (var bitmap = generator.GenerateBarCodeImage())
{
- // Decode the raw codetext according to the detected MaxiCode mode.
- var decodedCodetext = ComplexCodetextReader.TryDecodeMaxiCode(
- result.Extended.MaxiCode.MaxiCodeMode,
- result.CodeText);
-
- // Check if the decoded data is of type MaxiCode Mode 2.
- if (decodedCodetext is MaxiCodeCodetextMode2 decodedMode2)
+ using (var ms = new MemoryStream())
{
- Console.WriteLine($"Decoded PostalCode: {decodedMode2.PostalCode}");
- Console.WriteLine($"Original PostalCode: {maxiCodeCodetext.PostalCode}");
- bool match = decodedMode2.PostalCode == maxiCodeCodetext.PostalCode;
- Console.WriteLine($"Match: {match}");
- }
- else
- {
- Console.WriteLine("Decoded codetext is not MaxiCode Mode 2.");
+ // Save the generated bitmap as PNG into the memory stream.
+ bitmap.Save(ms, ImageFormat.Png);
+ ms.Position = 0; // Reset stream position for reading.
+
+ // Decode the barcode from the memory stream using MaxiCode decoder.
+ using (var reader = new BarCodeReader(ms, DecodeType.MaxiCode))
+ {
+ foreach (var result in reader.ReadBarCodes())
+ {
+ // Attempt to decode the complex codetext based on the mode reported by the reader.
+ var decoded = ComplexCodetextReader.TryDecodeMaxiCode(result.Extended.MaxiCode.Mode, result.CodeText);
+ if (decoded is MaxiCodeCodetextMode2 decodedMode2)
+ {
+ // Verify that the decoded postal code matches the original value.
+ bool isMatch = decodedMode2.PostalCode == postalCode;
+ Console.WriteLine($"Decoded PostalCode: {decodedMode2.PostalCode}");
+ Console.WriteLine($"Match original: {isMatch}");
+ }
+ else
+ {
+ Console.WriteLine("Decoded codetext is not MaxiCode Mode 2.");
+ }
+ }
+ }
}
}
}
diff --git a/maxicode-barcode/export-generated-maxicode-barcode-as-base64-string-for-embedding-in-json-api-responses.cs b/maxicode-barcode/export-generated-maxicode-barcode-as-base64-string-for-embedding-in-json-api-responses.cs
index aa7aa76..2584f35 100644
--- a/maxicode-barcode/export-generated-maxicode-barcode-as-base64-string-for-embedding-in-json-api-responses.cs
+++ b/maxicode-barcode/export-generated-maxicode-barcode-as-base64-string-for-embedding-in-json-api-responses.cs
@@ -1,8 +1,8 @@
-// Title: Export MaxiCode barcode as Base64 string
-// Description: Generates a MaxiCode barcode (Mode 2) and converts the PNG image to a Base64 string suitable for inclusion in JSON API responses.
-// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, illustrating how to use ComplexBarcodeGenerator with MaxiCodeCodetextMode2, configure postal and secondary message data, and output the result in a web‑friendly format. Developers working with shipping, logistics, or inventory systems often need to embed barcode images directly in JSON payloads, and this snippet shows the typical workflow using Aspose.BarCode classes.
+// Title: Export MaxiCode barcode as Base64 PNG string
+// Description: Generates a MaxiCode barcode (Mode 2) and converts the PNG image to a Base64 string for embedding in JSON responses.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as MaxiCode. It demonstrates using the ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and related classes to create shipping‑label barcodes, then exporting the image in PNG format and encoding it as Base64 for API payloads. Developers working with logistics, inventory, or any system that needs to embed barcode images in JSON will find this pattern useful.
// Prompt: Export a generated MaxiCode barcode as a base64 string for embedding in JSON API responses.
-// Tags: maxicode, barcode, base64, json, aspose.barcode, complexbarcode, generation
+// Tags: maxicode, barcode generation, base64, png, aspose.barcode, json, api response, complex barcode
using System;
using System.IO;
@@ -11,41 +11,43 @@
using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates generating a MaxiCode barcode and converting it to a Base64 string for JSON embedding.
+/// Demonstrates exporting a generated MaxiCode barcode as a Base64‑encoded PNG string.
///
class Program
{
///
- /// Entry point of the example. Creates a MaxiCode (Mode 2) barcode, saves it to a memory stream,
- /// converts the image to Base64, and writes the string to the console.
+ /// Entry point. Creates a MaxiCode barcode, saves it to a memory stream, converts to Base64, and writes the result to the console.
///
static void Main()
{
- // Prepare MaxiCode codetext for Mode 2 (postal information + data)
- var maxiCodeCodetext = new MaxiCodeCodetextMode2
+ // ------------------------------------------------------------
+ // 1. Prepare MaxiCode codetext (Mode 2) with a standard second message
+ // ------------------------------------------------------------
+ var maxiCodeData = new MaxiCodeCodetextMode2
{
- PostalCode = "524032140", // 9‑digit US postal code
- CountryCode = 56, // Country code (e.g., USA = 56)
- ServiceCategory = 999 // Example service category
+ PostalCode = "524032140",
+ CountryCode = 56,
+ ServiceCategory = 999
};
- // Add a simple second message
var secondMessage = new MaxiCodeStandardSecondMessage
{
- Message = "Sample MaxiCode"
+ Message = "Sample message"
};
- maxiCodeCodetext.SecondMessage = secondMessage;
+ maxiCodeData.SecondMessage = secondMessage;
- // Generate the barcode image into a memory stream
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ // ------------------------------------------------------------
+ // 2. Generate the barcode and export it as a Base64‑encoded PNG string
+ // ------------------------------------------------------------
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
{
- using (var ms = new MemoryStream())
+ using (var memoryStream = new MemoryStream())
{
- // Save the barcode as PNG to the stream
- generator.Save(ms, BarCodeImageFormat.Png);
+ // Save the barcode image to the memory stream in PNG format
+ generator.Save(memoryStream, BarCodeImageFormat.Png);
- // Convert the image bytes to a Base64 string
- string base64 = Convert.ToBase64String(ms.ToArray());
+ // Convert the PNG byte array to a Base64 string
+ string base64 = Convert.ToBase64String(memoryStream.ToArray());
// Output the Base64 string (can be embedded in JSON)
Console.WriteLine(base64);
diff --git a/maxicode-barcode/generate-maxicode-barcode-with-custom-margin-of-10-pixels-on-all-sides-for-better-visual-separation.cs b/maxicode-barcode/generate-maxicode-barcode-with-custom-margin-of-10-pixels-on-all-sides-for-better-visual-separation.cs
index f88fb45..5434a7e 100644
--- a/maxicode-barcode/generate-maxicode-barcode-with-custom-margin-of-10-pixels-on-all-sides-for-better-visual-separation.cs
+++ b/maxicode-barcode/generate-maxicode-barcode-with-custom-margin-of-10-pixels-on-all-sides-for-better-visual-separation.cs
@@ -1,42 +1,63 @@
// Title: Generate MaxiCode barcode with custom margins
-// Description: Creates a MaxiCode barcode (Mode 4) and applies a 10‑pixel margin on all sides before saving as PNG.
-// Category-Description: This example demonstrates how to use Aspose.BarCode's ComplexBarcodeGenerator to produce two‑dimensional barcodes with custom layout settings. It focuses on the MaxiCode symbology, showing how to configure padding via the Parameters.Barcode.Padding properties. Developers working with shipping labels, logistics, or any application requiring MaxiCode can reuse this pattern to adjust visual spacing and output format.
+// Description: Demonstrates how to create a MaxiCode barcode (Mode 2) and apply a 10‑pixel margin on all sides for visual separation.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator together with MaxiCodeCodetextMode2 and MaxiCodeStandardSecondMessage to produce a MaxiCode symbol. Developers commonly need to customize padding, colors, and output formats when integrating MaxiCode into packaging or shipping labels.
// Prompt: Generate a MaxiCode barcode with a custom margin of 10 pixels on all sides for better visual separation.
-// Tags: maxicode, barcode, margin, padding, png, aspose.barcode, complexbarcodegenerator
+// Tags: maxicode, generate, png, complexbarcodegenerator, maxicodecodetextmode2, maxicodestandardsecondmessage
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.Drawing;
///
-/// Demonstrates generation of a MaxiCode barcode with a uniform 10‑pixel margin using Aspose.BarCode.
+/// Example program that creates a MaxiCode barcode with a 10‑pixel margin on each side
+/// and saves it as a PNG image.
///
class Program
{
///
- /// Entry point of the example. Creates a MaxiCode (Mode 4) barcode, sets padding, and saves it as a PNG file.
+ /// Entry point of the application.
///
static void Main()
{
- // Define the MaxiCode content: Mode 4 with a simple message.
- var maxiCodeCodetext = new MaxiCodeStandardCodetext
+ // Prepare MaxiCode codetext (Mode 2 with a standard second message)
+ var maxiCodeCodetext = new MaxiCodeCodetextMode2
+ {
+ PostalCode = "524032140", // 9‑digit US postal code
+ CountryCode = 56, // Example country code
+ ServiceCategory = 999 // Example service category
+ };
+
+ // Define the optional second message displayed beneath the MaxiCode symbol
+ var secondMessage = new MaxiCodeStandardSecondMessage
{
- Mode = MaxiCodeMode.Mode4,
Message = "Sample MaxiCode"
};
+ maxiCodeCodetext.SecondMessage = secondMessage;
- // Initialize the ComplexBarcodeGenerator with the defined codetext.
+ // Determine the output file path in the current working directory
+ string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "maxicode.png");
+
+ // Generate the barcode with custom padding (10 pixels on each side)
using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
{
- // Apply a 10‑pixel margin on all four sides of the barcode.
+ // Apply 10‑pixel margins using the Padding properties
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 resulting barcode image to a PNG file.
- generator.Save("maxicode.png");
+ // Optional: set foreground (barcode) and background colors
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ generator.Parameters.BackColor = Aspose.Drawing.Color.White;
+
+ // Save the generated barcode image to the specified path
+ generator.Save(outputPath);
}
+
+ // Inform the user where the barcode image was saved
+ Console.WriteLine($"MaxiCode barcode saved to: {outputPath}");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/generate-maxicode-barcode-with-custom-quiet-zone-size-to-meet-specific-scanning-requirements.cs b/maxicode-barcode/generate-maxicode-barcode-with-custom-quiet-zone-size-to-meet-specific-scanning-requirements.cs
index ae3d142..96f6aee 100644
--- a/maxicode-barcode/generate-maxicode-barcode-with-custom-quiet-zone-size-to-meet-specific-scanning-requirements.cs
+++ b/maxicode-barcode/generate-maxicode-barcode-with-custom-quiet-zone-size-to-meet-specific-scanning-requirements.cs
@@ -1,82 +1,67 @@
-// Title: Generate MaxiCode Barcode with Custom Quiet Zone
-// Description: Demonstrates creating a MaxiCode barcode (Mode 2) with a custom quiet zone 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, MaxiCodeCodetextMode2, and related classes to produce a MaxiCode symbol. Typical use cases include shipping labels, parcel tracking, and inventory management where MaxiCode is required. Developers often need to adjust quiet zone (padding) settings to meet scanner specifications, making this example a useful reference for customizing barcode layout.
+// Title: Generate MaxiCode barcode with custom quiet zone
+// Description: Demonstrates creating a MaxiCode barcode and customizing its quiet zone (padding) to meet specific scanning requirements.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, focusing on complex barcode types such as MaxiCode. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode3, and related parameter settings to control barcode appearance, including quiet zone and module size. Developers working with shipping, logistics, or inventory systems often need to generate MaxiCode symbols with precise layout constraints for reliable scanning.
/// Prompt: Generate a MaxiCode barcode with a custom quiet zone size to meet specific scanning requirements.
-/// Tags: maxicode, barcode, quiet zone, complexbarcode, generation, png, aspose.barcode
+// Tags: maxicode, barcode, quiet zone, padding, generation, aspose.barcode, png, complexbarcode
using System;
using System.IO;
-using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
+using Aspose.BarCode.ComplexBarcode;
+using Aspose.Drawing.Imaging;
///
-/// Example program that generates a MaxiCode barcode with a custom quiet zone,
-/// saves it to a file, and optionally reads it back to verify decoding.
+/// Example program that creates a MaxiCode barcode with a custom quiet zone (padding) and saves it as a PNG image.
///
class Program
{
///
- /// Entry point of the example. Creates a MaxiCode (Mode 2) barcode,
- /// applies a 10‑point padding on all sides, saves the image, and
- /// demonstrates decoding the saved barcode.
+ /// Entry point of the application. Generates the barcode, applies custom padding, and writes the output file.
///
static void Main()
{
- // Prepare MaxiCode codetext (Mode 2 with a standard second message)
- var maxiCodeCodetext = new MaxiCodeCodetextMode2
+ // Define the output file path
+ string outputPath = "maxicode.png";
+
+ // Ensure the output directory exists
+ string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath));
+ if (!Directory.Exists(outputDir))
+ {
+ Directory.CreateDirectory(outputDir);
+ }
+
+ // Prepare MaxiCode codetext (Mode 3) with a standard second message
+ var maxiCodeData = new MaxiCodeCodetextMode3
{
- PostalCode = "524032140", // 9‑digit US postal code
- CountryCode = 56, // USA
- ServiceCategory = 999
+ PostalCode = "B1050", // 6‑character alphanumeric postal code
+ CountryCode = 56, // Country code (e.g., USA = 56)
+ ServiceCategory = 999 // Example service category
};
+
+ // Create the standard second message
var secondMessage = new MaxiCodeStandardSecondMessage
{
Message = "Sample MaxiCode"
};
- maxiCodeCodetext.SecondMessage = secondMessage;
+ maxiCodeData.SecondMessage = secondMessage;
- // Create the complex barcode generator with the codetext
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ // Generate the barcode with custom quiet zone (padding)
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
{
- // Set a custom quiet zone (padding) – 10 points on each side
- generator.Parameters.Barcode.Padding.Left.Point = 10f;
- generator.Parameters.Barcode.Padding.Right.Point = 10f;
- generator.Parameters.Barcode.Padding.Top.Point = 10f;
- generator.Parameters.Barcode.Padding.Bottom.Point = 10f;
+ // Set individual padding values (quiet zone) in points
+ generator.Parameters.Barcode.Padding.Left.Point = 15f;
+ generator.Parameters.Barcode.Padding.Top.Point = 15f;
+ generator.Parameters.Barcode.Padding.Right.Point = 15f;
+ generator.Parameters.Barcode.Padding.Bottom.Point = 15f;
- // Save the generated MaxiCode image
- string outputPath = "maxicode.png";
- generator.Save(outputPath);
- Console.WriteLine($"MaxiCode barcode saved to: {Path.GetFullPath(outputPath)}");
- }
+ // Optionally adjust the module size (X dimension) in points
+ generator.Parameters.Barcode.XDimension.Point = 2f;
- // Optional: read back the barcode to verify it can be decoded
- if (File.Exists("maxicode.png"))
- {
- using (var reader = new BarCodeReader("maxicode.png", DecodeType.MaxiCode))
- {
- foreach (var result in reader.ReadBarCodes())
- {
- // Decode the MaxiCode codetext using the complex codetext reader
- var decoded = ComplexCodetextReader.TryDecodeMaxiCode(
- result.Extended.MaxiCode.MaxiCodeMode,
- result.CodeText);
-
- if (decoded is MaxiCodeCodetextMode2 decodedMode2)
- {
- Console.WriteLine("Decoded MaxiCode:");
- Console.WriteLine($" PostalCode: {decodedMode2.PostalCode}");
- Console.WriteLine($" CountryCode: {decodedMode2.CountryCode}");
- Console.WriteLine($" ServiceCategory: {decodedMode2.ServiceCategory}");
- if (decodedMode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
- {
- Console.WriteLine($" Message: {stdMsg.Message}");
- }
- }
- }
- }
+ // Save the generated barcode as a PNG image
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
+
+ // Inform the user where the file was saved
+ Console.WriteLine($"MaxiCode barcode saved to: {Path.GetFullPath(outputPath)}");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/generate-maxicode-barcode-with-structured-secondary-message-containing-recipient-name-street-and-city-fields.cs b/maxicode-barcode/generate-maxicode-barcode-with-structured-secondary-message-containing-recipient-name-street-and-city-fields.cs
index 21e558c..1dbb9da 100644
--- a/maxicode-barcode/generate-maxicode-barcode-with-structured-secondary-message-containing-recipient-name-street-and-city-fields.cs
+++ b/maxicode-barcode/generate-maxicode-barcode-with-structured-secondary-message-containing-recipient-name-street-and-city-fields.cs
@@ -1,58 +1,51 @@
// Title: Generate MaxiCode barcode with structured secondary message
-// Description: Demonstrates creating a MaxiCode (Mode 2) barcode that includes a structured secondary message containing recipient name, street, and city.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as MaxiCode. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and MaxiCodeStructuredSecondMessage classes to encode both primary and secondary data. Developers often need to generate shipping labels or logistics barcodes where additional address information is embedded in the secondary message.
-// Prompt: Generate a MaxiCode barcode with a structured secondary message containing recipient name, street, and city fields.
-// Tags: maxicode, complex barcode, secondary message, shipping label, aspnet.barcode, generation, png
+// Description: Demonstrates how to create a MaxiCode barcode (Mode 2) that includes a structured secondary message containing recipient name, street, and city, and save it as a PNG image.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of MaxiCodeCodetextMode2, MaxiCodeStructuredSecondMessage, and ComplexBarcodeGenerator to produce a MaxiCode symbol. Typical use cases include shipping labels and logistics where a structured secondary message conveys address details. Developers often need to configure postal information, service categories, and visual appearance when generating such barcodes.
+/// Prompt: Generate a MaxiCode barcode with a structured secondary message containing recipient name, street, and city fields.
+/// Tags: maxicode, generate, png, complexbarcodegenerator, maxicodecodetextmode2, maxicodestructuredsecondmessage
using System;
using System.IO;
-using Aspose.BarCode;
-using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.BarCode.Generation;
using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating a MaxiCode barcode with a structured secondary message.
+/// Example program that creates a MaxiCode barcode with a structured secondary message and saves it as an image file.
///
class Program
{
///
- /// Entry point. Generates the barcode and saves it as a PNG file.
+ /// Entry point of the application. Builds the secondary message, configures the MaxiCode payload,
+ /// generates the barcode, and writes the output file path to the console.
///
static void Main()
{
- // Define the output file path for the generated barcode image
- string outputPath = "maxicode.png";
+ // Build a structured secondary message containing recipient details.
+ var secondMessage = new MaxiCodeStructuredSecondMessage();
+ secondMessage.Add("John Doe"); // Recipient name
+ secondMessage.Add("123 Main St"); // Street address
+ secondMessage.Add("Anytown"); // City
- // Prepare MaxiCode codetext for Mode 2, including required primary fields
- var maxiCodeCodetext = new MaxiCodeCodetextMode2
+ // Configure the MaxiCode payload (Mode 2) with required postal data and the secondary message.
+ var maxiCode = new MaxiCodeCodetextMode2
{
- PostalCode = "123456789", // 9‑digit postal code required for Mode 2
- CountryCode = 840, // USA numeric country code
- ServiceCategory = 999 // Example service category
+ PostalCode = "524032140", // 9‑digit postal code required for Mode 2
+ CountryCode = 56, // Example country code
+ ServiceCategory = 999, // Example service category
+ SecondMessage = secondMessage
};
- // Build the structured secondary message with recipient address details
- var secondaryMessage = new MaxiCodeStructuredSecondMessage();
- secondaryMessage.Add("John Doe"); // Recipient name
- secondaryMessage.Add("123 Main St"); // Street address
- secondaryMessage.Add("Anytown"); // City
-
- // Assign the secondary message to the MaxiCode codetext
- maxiCodeCodetext.SecondMessage = secondaryMessage;
-
- // Generate the MaxiCode barcode using the complex barcode generator
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ // Generate the MaxiCode barcode and save it as a PNG image.
+ using (var generator = new ComplexBarcodeGenerator(maxiCode))
{
- using (Image barcodeImage = generator.GenerateBarCodeImage())
- {
- // Save the generated barcode image as a PNG file
- barcodeImage.Save(outputPath, ImageFormat.Png);
- }
- }
+ // Optional visual settings: black bars on a white background.
+ generator.Parameters.Barcode.BarColor = Color.Black;
+ generator.Parameters.BackColor = Color.White;
- // Output the full path of the saved barcode image to the console
- Console.WriteLine($"MaxiCode barcode saved to: {Path.GetFullPath(outputPath)}");
+ string outputPath = "maxicode.png";
+ generator.Save(outputPath);
+ Console.WriteLine($"MaxiCode barcode saved to {Path.GetFullPath(outputPath)}");
+ }
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/generate-maxicode-mode-2-barcode-with-unstructured-secondary-message-and-save-it-as-png.cs b/maxicode-barcode/generate-maxicode-mode-2-barcode-with-unstructured-secondary-message-and-save-it-as-png.cs
index 10934cf..f459c2b 100644
--- a/maxicode-barcode/generate-maxicode-mode-2-barcode-with-unstructured-secondary-message-and-save-it-as-png.cs
+++ b/maxicode-barcode/generate-maxicode-mode-2-barcode-with-unstructured-secondary-message-and-save-it-as-png.cs
@@ -1,47 +1,53 @@
-// Title: Generate MaxiCode Mode 2 barcode with secondary message
-// Description: Demonstrates creating a MaxiCode Mode 2 barcode, adding an unstructured secondary message, and saving it as a PNG image.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as MaxiCode. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and related secondary message classes to produce high‑density 2‑D barcodes for shipping and logistics applications. Developers often need to encode postal information and custom messages for automated sorting systems.
+// Title: Generate MaxiCode Mode 2 barcode with secondary message
+// Description: Demonstrates creating a MaxiCode Mode 2 barcode that includes an unstructured secondary message and saving it as a PNG image.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as MaxiCode. It showcases the use of ComplexBarcodeGenerator together with MaxiCodeCodetextMode2 and MaxiCodeStandardSecondMessage classes to produce a MaxiCode with custom data. Developers working with shipping, logistics, or inventory systems often need to generate MaxiCode symbols for package tracking and require secondary message support.
// Prompt: Generate a MaxiCode Mode 2 barcode with an unstructured secondary message and save it as PNG.
-// Tags: maxicode, mode2, secondary-message, png, generation, complexbarcodegenerator, maxicodecodetextmode2, maxicodesstandardsecondmessage
+// Tags: maxicode, barcode generation, png, complexbarcode, aspose.barcode
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating a MaxiCode Mode 2 barcode with an unstructured secondary message and saving it as a PNG file.
+/// Example program that creates a MaxiCode Mode 2 barcode with an unstructured secondary message
+/// and saves the result as a PNG file.
///
class Program
{
///
- /// Entry point of the example. Creates the codetext, configures the generator, and saves the barcode image.
+ /// Entry point. Builds the MaxiCode codetext, generates the barcode image, and writes it to disk.
///
static void Main()
{
- // Initialize MaxiCode Mode 2 codetext object
- var codetext = new MaxiCodeCodetextMode2();
-
- // Set required postal information
- codetext.PostalCode = "524032140"; // 9‑digit US postal code
- codetext.CountryCode = 56; // Example country code
- codetext.ServiceCategory = 999; // Example service category
+ // Prepare MaxiCode Mode 2 codetext with an unstructured (standard) secondary message
+ var maxiCode = new MaxiCodeCodetextMode2
+ {
+ PostalCode = "524032140", // 9‑digit postal code required for Mode 2
+ CountryCode = 56, // 3‑digit country code
+ ServiceCategory = 999 // 3‑digit service category
+ };
- // Create an unstructured (standard) secondary message
+ // Define the secondary message (unstructured)
var secondMessage = new MaxiCodeStandardSecondMessage
{
- Message = "Sample secondary message"
+ Message = "Unstructured secondary message"
};
- codetext.SecondMessage = secondMessage; // Attach secondary message to codetext
+ maxiCode.SecondMessage = secondMessage;
// Generate the barcode using ComplexBarcodeGenerator
- using (var generator = new ComplexBarcodeGenerator(codetext))
+ using (var generator = new ComplexBarcodeGenerator(maxiCode))
{
- // Optional: set image resolution (dots per inch)
- generator.Parameters.Resolution = 300;
-
- // Save the generated barcode as a PNG file
- generator.Save("maxicode_mode2.png");
+ // Create the barcode image
+ using (Bitmap image = generator.GenerateBarCodeImage())
+ {
+ // Save the image as PNG
+ image.Save("maxicode_mode2.png", ImageFormat.Png);
+ }
}
+
+ Console.WriteLine("MaxiCode Mode 2 barcode saved as maxicode_mode2.png");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/generate-maxicode-mode-4-barcode-with-default-primary-data-and-store-result-in-bmp-format.cs b/maxicode-barcode/generate-maxicode-mode-4-barcode-with-default-primary-data-and-store-result-in-bmp-format.cs
index 5660b23..a14decf 100644
--- a/maxicode-barcode/generate-maxicode-mode-4-barcode-with-default-primary-data-and-store-result-in-bmp-format.cs
+++ b/maxicode-barcode/generate-maxicode-mode-4-barcode-with-default-primary-data-and-store-result-in-bmp-format.cs
@@ -1,43 +1,44 @@
-// Title: Generate MaxiCode Mode 4 Barcode and Save as BMP
-// Description: Creates a MaxiCode Mode 4 barcode with default primary data and writes it to a BMP image file.
-// Category-Description: This example demonstrates how to use Aspose.BarCode's ComplexBarcodeGenerator to produce a MaxiCode barcode, specifically Mode 4, which is commonly used for shipping and logistics. It showcases the MaxiCodeStandardCodetext class for setting mode and message, configuring image resolution, and saving the result in BMP format. Developers working with advanced barcode symbologies can refer to this pattern for generating other complex barcodes.
+// Title: Generate MaxiCode Mode 4 barcode and save as BMP
+// Description: Demonstrates creating a MaxiCode Mode 4 barcode with default primary data using Aspose.BarCode and saving the image in BMP format.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode symbologies such as MaxiCode. It showcases the use of ComplexBarcodeGenerator and MaxiCodeStandardCodetext classes to configure mode and data, a common task for developers needing high‑density 2‑D barcodes for logistics and tracking applications. Typical use cases include generating shipping labels and parcel identifiers where MaxiCode is required.
// Prompt: Generate a MaxiCode Mode 4 barcode with default primary data and store the result in BMP format.
-// Tags: maxicode, barcode generation, bmp, aspose.barcode, complexbarcode, csharp
+// Tags: maxicode, barcode generation, bmp, complexbarcode, aspose.barcode
using System;
-using Aspose.BarCode;
+using System.IO;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates generation of a MaxiCode Mode 4 barcode and saving it as a BMP image using Aspose.BarCode.
+/// Example program that generates a MaxiCode Mode 4 barcode and saves it as a BMP image.
///
class Program
{
///
- /// Entry point of the example. Creates a MaxiCode barcode, configures parameters, and saves the image.
+ /// Entry point of the application.
///
static void Main()
{
- // Initialize standard codetext for MaxiCode Mode 4
- var maxiCodeCodetext = new MaxiCodeStandardCodetext();
- maxiCodeCodetext.Mode = MaxiCodeMode.Mode4; // Set barcode mode to Mode 4
- maxiCodeCodetext.Message = "Test message"; // Set the primary data message
+ // Define the output file path for the generated barcode image.
+ string outputPath = "maxicode_mode4.bmp";
- // Generate the barcode using ComplexBarcodeGenerator
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ // Initialize standard codetext for MaxiCode Mode 4.
+ var maxiCodeData = new MaxiCodeStandardCodetext
{
- // Optional: define image resolution (dots per inch)
- generator.Parameters.Resolution = 300;
+ // Set the barcode mode to Mode 4.
+ Mode = MaxiCodeMode.Mode4,
+ // Provide default primary data (a simple message).
+ Message = "Test message"
+ };
- // Define output file name and format
- string outputFile = "maxicode_mode4.bmp";
-
- // Save the generated barcode as BMP
- generator.Save(outputFile, BarCodeImageFormat.Bmp);
+ // Create a ComplexBarcodeGenerator with the configured codetext.
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
+ {
+ // Save the generated barcode image in BMP format to the specified path.
+ generator.Save(outputPath, BarCodeImageFormat.Bmp);
}
- // Inform the user that the barcode has been saved
- Console.WriteLine("MaxiCode Mode 4 barcode saved successfully.");
+ // Output the full path of the saved barcode image.
+ Console.WriteLine($"MaxiCode Mode 4 barcode saved to {Path.GetFullPath(outputPath)}");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/implement-batch-generation-of-maxicode-mode-2-barcodes-from-csv-file-containing-primary-and-secondary-data-rows.cs b/maxicode-barcode/implement-batch-generation-of-maxicode-mode-2-barcodes-from-csv-file-containing-primary-and-secondary-data-rows.cs
index becd01e..8fc5a78 100644
--- a/maxicode-barcode/implement-batch-generation-of-maxicode-mode-2-barcodes-from-csv-file-containing-primary-and-secondary-data-rows.cs
+++ b/maxicode-barcode/implement-batch-generation-of-maxicode-mode-2-barcodes-from-csv-file-containing-primary-and-secondary-data-rows.cs
@@ -1,8 +1,8 @@
// Title: Batch Generation of MaxiCode Mode 2 Barcodes from CSV
-// Description: Demonstrates reading a CSV file containing primary and secondary data rows and creating MaxiCode Mode 2 barcodes for each record.
-// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of MaxiCodeCodetextMode2, MaxiCodeStandardSecondMessage, and MaxiCodeStructuredSecondMessage classes to build MaxiCode data structures, and the ComplexBarcodeGenerator to render PNG images. Developers working with shipping, logistics, or any application that requires bulk creation of MaxiCode symbols will find this pattern useful for automating barcode production from data sources such as CSV files.
+// Description: Demonstrates how to read a CSV file containing postal, country, service, and secondary message data and generate a series of MaxiCode Mode 2 barcode images.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as MaxiCode. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and related classes to create image files. Developers often need to automate bulk barcode creation for shipping, logistics, or inventory systems, and this snippet provides a template for reading input data and producing PNG outputs.
// Prompt: Implement batch generation of MaxiCode Mode 2 barcodes from a CSV file containing primary and secondary data rows.
-// Tags: maxicode, batch, csv, barcode generation, aspose.barcode, complexbarcode, png
+// Tags: maxicode, batch, csv, barcode generation, image, aspose.barcode, complexbarcode, png
using System;
using System.IO;
@@ -10,108 +10,110 @@
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.Drawing;
///
-/// Provides a console application that reads a CSV file and generates a batch of MaxiCode Mode 2 barcodes.
+/// Generates MaxiCode Mode 2 barcodes in batch from a CSV file.
///
class Program
{
///
- /// Entry point of the application. Reads input data, creates MaxiCode objects, and saves barcode images.
+ /// Entry point. Reads CSV, creates output folder, and generates barcode images.
///
static void Main()
{
- // Input CSV path (relative to executable)
- string csvPath = "input.csv";
+ // Path to the input CSV file (relative to the executable)
+ string csvPath = "maxicode_input.csv";
- // If the CSV does not exist, create a small sample file
+ // Folder where generated PNG images will be saved
+ string outputFolder = "Output";
+
+ // Ensure the output directory exists
+ if (!Directory.Exists(outputFolder))
+ {
+ Directory.CreateDirectory(outputFolder);
+ }
+
+ // If the CSV file is missing, create a small sample file for demonstration
if (!File.Exists(csvPath))
{
- var sampleLines = new[]
+ var sampleLines = new List
{
- "PostalCode,CountryCode,ServiceCategory,SecondMessageType,SecondMessageContent",
- "524032140,056,999,Standard,Test message 1",
- "123456789,840,100,Standard,Hello World",
- "987654321,124,200,Structured,634 ALPHA DRIVE|PITTSBURGH|PA",
- "111222333,036,300,Standard,Sample Text",
- "444555666,124,400,Structured,123 MAIN ST|ANYTOWN|CA"
+ "PostalCode,CountryCode,ServiceCategory,SecondMessage",
+ "524032140,056,999,Sample message 1",
+ "123456789,840,100,Sample message 2",
+ "987654321,124,200,Sample message 3"
};
File.WriteAllLines(csvPath, sampleLines);
+ Console.WriteLine($"Sample CSV created at '{csvPath}'.");
}
- // Ensure output directory exists
- string outputDir = "output";
- if (!Directory.Exists(outputDir))
+ // Read all lines from the CSV, preserving empty lines for later filtering
+ string[] allLines = File.ReadAllLines(csvPath);
+ if (allLines.Length <= 1)
{
- Directory.CreateDirectory(outputDir);
+ Console.WriteLine("CSV file does not contain data rows.");
+ return;
}
- // Read all lines from CSV (including header)
- var lines = File.ReadAllLines(csvPath);
- int barcodesGenerated = 0;
-
- // Process each data line, limiting to 5 barcodes for the demo
- for (int i = 1; i < lines.Length && barcodesGenerated < 5; i++)
+ // Process each data row, skipping the header line (index 0)
+ for (int i = 1; i < allLines.Length; i++)
{
- string line = lines[i];
- if (string.IsNullOrWhiteSpace(line))
- continue; // Skip empty lines
+ string line = allLines[i].Trim();
+ if (string.IsNullOrEmpty(line))
+ {
+ // Skip blank lines
+ continue;
+ }
- // Split CSV fields
+ // Split the CSV line into its constituent fields
string[] parts = line.Split(',');
- if (parts.Length < 5)
- continue; // Skip malformed lines
+ if (parts.Length < 4)
+ {
+ Console.WriteLine($"Skipping malformed line {i + 1}: '{line}'");
+ continue;
+ }
- // Trim whitespace from each field
- for (int p = 0; p < parts.Length; p++)
- parts[p] = parts[p].Trim();
+ // Extract and validate individual fields
+ string postalCode = parts[0].Trim();
- // Build MaxiCode codetext for Mode 2 using primary fields
- var maxiCode = new MaxiCodeCodetextMode2
+ if (!int.TryParse(parts[1].Trim(), out int countryCode))
{
- PostalCode = parts[0],
- CountryCode = int.Parse(parts[1]),
- ServiceCategory = int.Parse(parts[2])
- };
+ Console.WriteLine($"Invalid CountryCode on line {i + 1}");
+ continue;
+ }
- // Determine and assign the appropriate second message type
- if (parts[3].Equals("Standard", StringComparison.OrdinalIgnoreCase))
+ if (!int.TryParse(parts[2].Trim(), out int serviceCategory))
{
- var stdMsg = new MaxiCodeStandardSecondMessage
- {
- Message = parts[4]
- };
- maxiCode.SecondMessage = stdMsg;
+ Console.WriteLine($"Invalid ServiceCategory on line {i + 1}");
+ continue;
}
- else if (parts[3].Equals("Structured", StringComparison.OrdinalIgnoreCase))
- {
- var structMsg = new MaxiCodeStructuredSecondMessage();
- // Structured content parts are separated by '|'
- string[] identifiers = parts[4].Split('|');
- foreach (var id in identifiers)
- {
- structMsg.Add(id.Trim());
- }
+ string secondMessageText = parts[3].Trim();
- // Year is optional; not provided in this sample
- maxiCode.SecondMessage = structMsg;
- }
- else
+ // Build the MaxiCode codetext (Mode 2) with a standard second message
+ var maxiCodeData = new MaxiCodeCodetextMode2
{
- // Unknown message type – skip this record
- continue;
- }
+ PostalCode = postalCode,
+ CountryCode = countryCode,
+ ServiceCategory = serviceCategory,
+ SecondMessage = new MaxiCodeStandardSecondMessage { Message = secondMessageText }
+ };
- // Generate and save the barcode image as PNG
- string outputPath = Path.Combine(outputDir, $"MaxiCode_{barcodesGenerated + 1}.png");
- using (var generator = new ComplexBarcodeGenerator(maxiCode))
+ // Generate the barcode image using the complex barcode generator
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
{
- generator.Save(outputPath, BarCodeImageFormat.Png);
- }
+ using (Aspose.Drawing.Bitmap image = generator.GenerateBarCodeImage())
+ {
+ // Construct a unique file name for each barcode
+ string fileName = $"MaxiCode_{i:D3}.png";
+ string outputPath = Path.Combine(outputFolder, fileName);
- Console.WriteLine($"Generated barcode {barcodesGenerated + 1}: {outputPath}");
- barcodesGenerated++;
+ // Save the image as PNG
+ image.Save(outputPath);
+ Console.WriteLine($"Saved barcode to '{outputPath}'.");
+ }
+ }
}
Console.WriteLine("Batch generation completed.");
diff --git a/maxicode-barcode/implement-error-handling-that-catches-barcodeexception-when-decoding-unreadable-maxicode-image.cs b/maxicode-barcode/implement-error-handling-that-catches-barcodeexception-when-decoding-unreadable-maxicode-image.cs
index 9734938..2d97cdc 100644
--- a/maxicode-barcode/implement-error-handling-that-catches-barcodeexception-when-decoding-unreadable-maxicode-image.cs
+++ b/maxicode-barcode/implement-error-handling-that-catches-barcodeexception-when-decoding-unreadable-maxicode-image.cs
@@ -1,57 +1,69 @@
+// Title: Decode MaxiCode with error handling using Aspose.BarCode
+// Description: Demonstrates how to decode a MaxiCode barcode from an image while handling potential decoding errors.
+// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing the use of BarCodeReader, DecodeType, and QualitySettings to read MaxiCode symbols. Typical scenarios include processing shipping labels or inventory tags where MaxiCode is common, and developers often need robust error handling for damaged or unreadable images.
+// Prompt: Implement error handling that catches BarcodeException when decoding an unreadable MaxiCode image.
+// Tags: maxicode, barcode decoding, error handling, aspose.barcode, barcodereader, qualitysettings
+
using System;
using System.IO;
-using Aspose.BarCode.BarCodeRecognition;
-using Aspose.BarCode.ComplexBarcode;
+using Aspose.BarCode.BarCodeRecognition; // Provides BarCodeReader, DecodeType, QualitySettings
+using Aspose.BarCode.Generation; // Provides DecodeType enum (static members)
-class Program
+///
+/// Example program that attempts to read a MaxiCode barcode from an image file
+/// and demonstrates error handling for unreadable or damaged barcodes.
+///
+class MaxiCodeDecoder
{
+ ///
+ /// Entry point of the program. Reads the specified image, configures the reader,
+ /// and outputs any detected MaxiCode values while safely handling decoding exceptions.
+ ///
static void Main()
{
- // Path to the MaxiCode image (replace with an actual file path if needed)
+ // Path to the image that may contain an unreadable MaxiCode
string imagePath = "unreadable_maxicode.png";
- // Validate that the image file exists
+ // Verify that the file exists before attempting to read it
if (!File.Exists(imagePath))
{
Console.WriteLine($"File not found: {imagePath}");
return;
}
- try
+ // DecodeType is a static class; store the specific type in a BaseDecodeType variable
+ BaseDecodeType decodeType = DecodeType.MaxiCode;
+
+ // Create the reader and assign the image source
+ using (var reader = new BarCodeReader(imagePath, decodeType))
{
- // Create a BarCodeReader for MaxiCode symbology
- using (var reader = new BarCodeReader(imagePath, DecodeType.MaxiCode))
+ // Use the highest quality preset to improve chances of reading a damaged barcode
+ reader.QualitySettings = QualitySettings.MaxQuality;
+
+ try
{
- // Read all barcodes from the image
- var results = reader.ReadBarCodes();
+ // Attempt to read all barcodes in the image
+ BarCodeResult[] results = reader.ReadBarCodes();
if (results.Length == 0)
{
- Console.WriteLine("No barcodes detected.");
+ Console.WriteLine("No MaxiCode detected in the image.");
}
-
- foreach (var result in results)
+ else
{
- // Attempt to decode the MaxiCode codetext using ComplexCodetextReader
- var decoded = ComplexCodetextReader.TryDecodeMaxiCode(
- result.Extended.MaxiCode.MaxiCodeMode,
- result.CodeText);
-
- if (decoded != null)
+ foreach (var result in results)
{
- Console.WriteLine($"Decoded MaxiCode codetext: {decoded.GetConstructedCodetext()}");
- }
- else
- {
- Console.WriteLine("Failed to decode MaxiCode codetext.");
+ Console.WriteLine($"Detected MaxiCode: {result.CodeText}");
+ // Additional extended parameters can be accessed if needed, e.g.:
+ // var mode = result.Extended.MaxiCode.Mode;
}
}
}
- }
- catch (Exception ex)
- {
- // Handle any errors that occur during decoding (e.g., unreadable image)
- Console.WriteLine($"Error decoding barcode: {ex.Message}");
+ // Catch any exception that occurs during decoding (e.g., unreadable image)
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Error decoding MaxiCode: {ex.Message}");
+ }
}
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/implement-retry-mechanism-that-attempts-to-decode-maxicode-barcode-up-to-three-times-on-failure.cs b/maxicode-barcode/implement-retry-mechanism-that-attempts-to-decode-maxicode-barcode-up-to-three-times-on-failure.cs
index a7dc76b..0563b67 100644
--- a/maxicode-barcode/implement-retry-mechanism-that-attempts-to-decode-maxicode-barcode-up-to-three-times-on-failure.cs
+++ b/maxicode-barcode/implement-retry-mechanism-that-attempts-to-decode-maxicode-barcode-up-to-three-times-on-failure.cs
@@ -1,14 +1,14 @@
-// Title: Decode MaxiCode barcode with retry mechanism
-// Description: Demonstrates generating a MaxiCode barcode in memory and attempting to decode it up to three times, handling failures gracefully.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, showcasing the use of ComplexBarcodeGenerator, BarCodeReader, and related classes for MaxiCode symbology. Developers often need to generate complex barcodes, read them from streams, and implement retry logic for unreliable scans. The snippet illustrates typical workflow and error handling for MaxiCode decoding.
+// Title: MaxiCode barcode generation and retry decode example
+// Description: Demonstrates generating a MaxiCode barcode, saving it to a memory stream, and attempting to decode it up to three times with retry logic.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category, illustrating how to use BarcodeGenerator, BarCodeReader, and related classes to create and read MaxiCode symbology. Developers often need to generate barcodes for packaging and then verify them by decoding, handling transient failures with retry loops. The snippet shows typical usage patterns for encoding, saving to streams, and robust decoding.
// Prompt: Implement a retry mechanism that attempts to decode a MaxiCode barcode up to three times on failure.
-// Tags: maxicode, barcode generation, barcode recognition, retry, aspose.barcode, complexbarcode
+// Tags: maxicode, barcode generation, barcode recognition, retry, aspose.barcode, c#
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.BarCode.ComplexBarcode;
///
/// Demonstrates generating a MaxiCode barcode and decoding it with retry logic.
@@ -16,104 +16,65 @@
class Program
{
///
- /// Entry point of the example. Generates a MaxiCode barcode in memory, then attempts to decode it up to three times.
+ /// Entry point. Generates a MaxiCode barcode, saves it to a memory stream, and tries to decode it up to three times.
///
static void Main()
{
- // Create a sample MaxiCode barcode (Mode 2) in memory
- var maxiCode = new MaxiCodeCodetextMode2
+ // Create a MaxiCode barcode generator with sample codetext
+ using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, "Sample MaxiCode"))
{
- PostalCode = "524032140",
- CountryCode = 56,
- ServiceCategory = 999
- };
-
- // Add a second message to the barcode
- var secondMessage = new MaxiCodeStandardSecondMessage
- {
- Message = "Sample message"
- };
- maxiCode.SecondMessage = secondMessage;
-
- // Generate the barcode image and store it in a memory stream
- using (var generator = new ComplexBarcodeGenerator(maxiCode))
- using (var imageStream = new MemoryStream())
- {
- // Save the barcode image to the memory stream in PNG format
- generator.Save(imageStream, BarCodeImageFormat.Png);
-
- // Reset stream position to the beginning for reading
- imageStream.Position = 0;
-
- const int maxAttempts = 3; // Maximum number of decode attempts
- bool decoded = false; // Flag indicating successful decode
-
- // Retry loop: attempt to read and decode the barcode up to maxAttempts times
- for (int attempt = 1; attempt <= maxAttempts && !decoded; attempt++)
+ // Save the generated barcode to a memory stream in PNG format
+ using (var ms = new MemoryStream())
{
- // Ensure the stream is positioned at the start before each read
- imageStream.Position = 0;
-
- // Initialize the barcode reader for MaxiCode symbology
- using (var reader = new BarCodeReader(imageStream, DecodeType.MaxiCode))
- {
- // Use high-quality settings to improve detection reliability
- reader.QualitySettings = QualitySettings.MaxQuality;
+ generator.Save(ms, BarCodeImageFormat.Png);
- // Read all barcodes found in the stream
- var results = reader.ReadBarCodes();
+ // Reset stream position for reading
+ ms.Position = 0;
- if (results.Length == 0)
- {
- Console.WriteLine($"Attempt {attempt}: No barcode detected.");
- continue; // Proceed to next attempt
- }
+ const int maxAttempts = 3;
+ bool decoded = false;
- // Process each detected barcode
- foreach (var result in results)
+ // Retry loop: attempt to decode up to maxAttempts times
+ for (int attempt = 1; attempt <= maxAttempts && !decoded; attempt++)
+ {
+ try
{
- // Attempt to decode the MaxiCode codetext using the structured reader
- var decodedCodetext = ComplexCodetextReader.TryDecodeMaxiCode(
- result.Extended.MaxiCode.MaxiCodeMode,
- result.CodeText);
+ // Ensure the stream is positioned at the beginning before each decode attempt
+ ms.Position = 0;
- if (decodedCodetext != null)
+ // Decode the barcode from the memory stream
+ using (var reader = new BarCodeReader(ms, DecodeType.MaxiCode))
{
- // Decoding succeeded – output the extracted information
- Console.WriteLine($"Attempt {attempt}: Decoding succeeded.");
- var structured = (MaxiCodeStructuredCodetext)decodedCodetext;
- Console.WriteLine($"Postal Code: {structured.PostalCode}");
- Console.WriteLine($"Country Code: {structured.CountryCode}");
- Console.WriteLine($"Service Category: {structured.ServiceCategory}");
+ var results = reader.ReadBarCodes();
- // If the barcode is Mode 2, display the second message
- if (decodedCodetext is MaxiCodeCodetextMode2 mode2 &&
- mode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
+ if (results != null && results.Length > 0)
{
- Console.WriteLine($"Message: {stdMsg.Message}");
+ // Successful decode – output details
+ var result = results[0];
+ Console.WriteLine($"Decoded on attempt {attempt}:");
+ Console.WriteLine($" Code Type: {result.CodeType}");
+ Console.WriteLine($" Code Text: {result.CodeText}");
+ decoded = true;
+ }
+ else
+ {
+ Console.WriteLine($"Attempt {attempt}: No barcode detected.");
}
-
- decoded = true; // Mark as successfully decoded
- break; // Exit the foreach loop
- }
- else
- {
- Console.WriteLine($"Attempt {attempt}: Decoding failed for detected barcode.");
}
}
-
- // If not decoded and more attempts remain, indicate a retry
- if (!decoded && attempt < maxAttempts)
+ catch (Exception ex)
{
- Console.WriteLine($"Retrying... (attempt {attempt + 1} of {maxAttempts})");
+ // Log exception and continue to next attempt
+ Console.WriteLine($"Attempt {attempt}: Exception - {ex.Message}");
}
+
+ // Optional: add a small delay here before the next attempt if needed
}
- }
- // Final outcome after all attempts
- if (!decoded)
- {
- Console.WriteLine("Failed to decode the MaxiCode barcode after maximum attempts.");
+ if (!decoded)
+ {
+ Console.WriteLine("Failed to decode the MaxiCode barcode after 3 attempts.");
+ }
}
}
}
diff --git a/maxicode-barcode/include-iso-country-identifier-in-secondary-structured-message-of-maxicode-mode-3-barcode.cs b/maxicode-barcode/include-iso-country-identifier-in-secondary-structured-message-of-maxicode-mode-3-barcode.cs
index 4c28afe..76ac2a1 100644
--- a/maxicode-barcode/include-iso-country-identifier-in-secondary-structured-message-of-maxicode-mode-3-barcode.cs
+++ b/maxicode-barcode/include-iso-country-identifier-in-secondary-structured-message-of-maxicode-mode-3-barcode.cs
@@ -1,65 +1,61 @@
-// Title: Generate MaxiCode Mode 3 barcode with ISO country identifier in secondary message
-// Description: Demonstrates how to create a MaxiCode Mode 3 barcode and embed an ISO country identifier in its structured secondary message.
-// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on MaxiCode symbology. It showcases the use of MaxiCodeCodetextMode3, MaxiCodeStructuredSecondMessage, and ComplexBarcodeGenerator classes to build and render a MaxiCode with custom postal, country, and service data—common tasks for shipping and logistics applications. Developers often need to encode address information and ISO country codes for automated parcel sorting systems.
+// Title: Generate a MaxiCode Mode 3 barcode with ISO country identifier in secondary message
+// Description: Demonstrates how to create a MaxiCode Mode 3 barcode using Aspose.BarCode, setting postal code, numeric ISO country code, service category, and adding a two‑letter ISO country identifier to the structured secondary message.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on MaxiCode symbology and complex barcode creation. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode3, and MaxiCodeStructuredSecondMessage to build barcodes with detailed address information, a common requirement for shipping and logistics applications. Developers often need to embed structured messages and ISO identifiers for automated scanning systems.
// Prompt: Include an ISO country identifier in the secondary structured message of a MaxiCode Mode 3 barcode.
-// Tags: maxicode, mode3, secondarymessage, iso country code, barcode generation, aspnet, aspose.barcode, png output
+// Tags: maxicode, barcode, generation, secondary message, iso country, aspose.barcode, complexbarcode
-using System;
-using System.IO;
-using Aspose.BarCode.ComplexBarcode;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
+using Aspose.BarCode.ComplexBarcode;
+using Aspose.Drawing;
///
-/// Entry point for the example that generates a MaxiCode Mode 3 barcode with a structured secondary message containing an ISO country identifier.
+/// Example program that generates a MaxiCode Mode 3 barcode with a structured secondary message
+/// containing a two‑letter ISO country identifier.
///
-class Program
+public static class Program
{
///
- /// Generates the barcode, saves it as PNG, and writes the output path to the console.
+ /// Entry point of the example. Creates the barcode data, builds the secondary message,
+ /// generates the image, and saves it to disk.
///
- static void Main()
+ public static void Main()
{
- // Define the output file name for the generated barcode image
- const string outputFile = "maxicode_mode3.png";
+ // Output file path for the generated barcode image
+ string outputPath = "maxicode_mode3.png";
- // Create MaxiCode codetext for Mode 3 with required fields
- var maxiCode = new MaxiCodeCodetextMode3
+ // --------------------------------------------------------------------
+ // Create MaxiCode Mode 3 codetext with required fields
+ // --------------------------------------------------------------------
+ var maxiCodeData = new MaxiCodeCodetextMode3
{
- // 6‑character alphanumeric postal code (example)
- PostalCode = "B1050",
- // 3‑digit numeric ISO country code (example: 056 = Belgium)
- CountryCode = 056,
- // Service category (example)
- ServiceCategory = 999
+ PostalCode = "B1050", // 6‑character alphanumeric postal code
+ CountryCode = 56, // Numeric ISO country code (e.g., 56 = Belgium)
+ ServiceCategory = 999 // Example service category
};
- // Build the structured secondary message
- var secondaryMessage = new MaxiCodeStructuredSecondMessage();
-
- // Include ISO country identifier as the first line (e.g., "US")
- secondaryMessage.Add("US");
- // Additional address lines
- secondaryMessage.Add("634 ALPHA DRIVE");
- secondaryMessage.Add("PITTSBURGH");
- secondaryMessage.Add("PA");
- // Set the year (last two digits)
- secondaryMessage.Year = 99;
-
- // Assign the structured second message to the codetext
- maxiCode.SecondMessage = secondaryMessage;
-
- // Generate the MaxiCode barcode using ComplexBarcodeGenerator
- using (var generator = new ComplexBarcodeGenerator(maxiCode))
+ // --------------------------------------------------------------------
+ // Build the structured secondary message (address lines, state, country)
+ // --------------------------------------------------------------------
+ var structuredMessage = new MaxiCodeStructuredSecondMessage();
+ structuredMessage.Add("634 ALPHA DRIVE"); // Street address
+ structuredMessage.Add("PITTSBURGH"); // City
+ structuredMessage.Add("PA"); // State / province
+ structuredMessage.Add("US"); // ISO country identifier (2‑letter code)
+ structuredMessage.Year = 99; // Two‑digit year
+
+ // Assign the secondary message to the MaxiCode data object
+ maxiCodeData.SecondMessage = structuredMessage;
+
+ // --------------------------------------------------------------------
+ // Generate the barcode image using ComplexBarcodeGenerator and save it
+ // --------------------------------------------------------------------
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
{
- // Generate the barcode image
- generator.GenerateBarCodeImage();
-
- // Save the image to a PNG file
- generator.Save(outputFile, BarCodeImageFormat.Png);
+ using (Bitmap image = generator.GenerateBarCodeImage())
+ {
+ image.Save(outputPath);
+ }
}
-
- // Inform the user where the barcode image was saved
- Console.WriteLine($"MaxiCode Mode 3 barcode saved to: {Path.GetFullPath(outputFile)}");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/produce-maxicode-mode-5-barcode-set-custom-image-width-and-height-and-save-it-as-tiff.cs b/maxicode-barcode/produce-maxicode-mode-5-barcode-set-custom-image-width-and-height-and-save-it-as-tiff.cs
index 33b7f09..9e7cd64 100644
--- a/maxicode-barcode/produce-maxicode-mode-5-barcode-set-custom-image-width-and-height-and-save-it-as-tiff.cs
+++ b/maxicode-barcode/produce-maxicode-mode-5-barcode-set-custom-image-width-and-height-and-save-it-as-tiff.cs
@@ -1,40 +1,44 @@
// Title: Generate MaxiCode Mode 5 barcode and save as TIFF
-// Description: Demonstrates creating a MaxiCode Mode 5 barcode, customizing its image size, and exporting it to a TIFF file.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on MaxiCode symbology. It showcases the use of BarcodeGenerator, EncodeTypes, and MaxiCodeMode classes to produce high‑density 2‑D barcodes, a common requirement for shipping and logistics applications where compact data encoding and error correction are needed. Developers often need to adjust image dimensions and output formats, which this sample illustrates.
+// Description: Demonstrates creating a MaxiCode Mode 5 barcode with custom image dimensions using Aspose.BarCode and saving it as a TIFF file.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as MaxiCode. It shows how to use the ComplexBarcodeGenerator with MaxiCodeStandardCodetext, configure image size via generator parameters, and export the result in TIFF format. Developers working with shipping labels, logistics, or retail can use similar code to produce high‑density 2‑D barcodes for scanning systems.
// Prompt: Produce a MaxiCode Mode 5 barcode, set custom image width and height, and save it as TIFF.
-// Tags: maxicode, mode5, barcode generation, image size, tiff, aspose.barcode
+// Tags: maxicode, barcode generation, tiff, complexbarcode, aspose.barcode, image size
using System;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
+using Aspose.BarCode.ComplexBarcode;
using Aspose.Drawing.Imaging;
///
-/// Entry point for the MaxiCode Mode 5 barcode generation example.
+/// Example program that creates a MaxiCode Mode 5 barcode,
+/// customizes its image dimensions, and saves it as a TIFF file.
///
class Program
{
///
- /// Generates a MaxiCode Mode 5 barcode with custom dimensions and saves it as a TIFF image.
+ /// Entry point of the example. Generates the barcode and writes it to disk.
///
static void Main()
{
- // Initialize a barcode generator for the MaxiCode symbology
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MaxiCode))
- {
- // Assign the data to be encoded (standard test message for Mode 5)
- generator.CodeText = "Test message";
+ // Define the output file path for the generated TIFF image.
+ string outputPath = "maxicode_mode5.tiff";
- // Configure the generator to use MaxiCode Mode 5 (data with long ECC correction)
- generator.Parameters.Barcode.MaxiCode.MaxiCodeMode = MaxiCodeMode.Mode5;
+ // Prepare the MaxiCode data: select Mode 5 and provide the message to encode.
+ var maxiCodeData = new MaxiCodeStandardCodetext
+ {
+ Mode = MaxiCodeMode.Mode5,
+ Message = "Sample MaxiCode Mode5"
+ };
- // Set custom image dimensions (width and height in points)
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 200f;
+ // Create a ComplexBarcodeGenerator using the prepared MaxiCode data.
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
+ {
+ // Set custom image dimensions (in points). Adjust as needed for your layout.
+ generator.Parameters.ImageWidth.Point = 400f;
+ generator.Parameters.ImageHeight.Point = 300f;
- // Save the generated barcode as a TIFF file
- generator.Save("maxicode_mode5.tiff");
+ // Save the generated barcode image in TIFF format to the specified path.
+ generator.Save(outputPath, BarCodeImageFormat.Tiff);
}
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/rotate-generated-maxicode-barcode-by-90-degrees-and-save-rotated-image-as-gif.cs b/maxicode-barcode/rotate-generated-maxicode-barcode-by-90-degrees-and-save-rotated-image-as-gif.cs
index fc7fc03..1345ca7 100644
--- a/maxicode-barcode/rotate-generated-maxicode-barcode-by-90-degrees-and-save-rotated-image-as-gif.cs
+++ b/maxicode-barcode/rotate-generated-maxicode-barcode-by-90-degrees-and-save-rotated-image-as-gif.cs
@@ -1,56 +1,40 @@
-// Title: Rotate MaxiCode Barcode and Save as GIF
-// Description: Generates a MaxiCode barcode, rotates it 90 degrees, and saves the rotated image as a GIF file.
-// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It demonstrates how to use the ComplexBarcodeGenerator with MaxiCodeCodetextMode2 to create a MaxiCode symbol, then employs Aspose.Drawing to manipulate the resulting image (rotation) before saving. Developers working with high‑density 2‑D barcodes often need to adjust orientation for printing or display purposes, and this pattern shows the typical workflow using key API classes such as ComplexBarcodeGenerator, MaxiCodeCodetextMode2, Image, and RotateFlipType.
-/// Prompt: Rotate a generated MaxiCode barcode by 90 degrees and save the rotated image as GIF.
-/// Tags: maxicode, rotation, gif, aspose.barcode, complexbarcode, imageprocessing
+// Title: Rotate MaxiCode barcode and save as GIF
+// Description: Demonstrates generating a MaxiCode barcode, rotating it 90 degrees, and saving the result as a GIF image.
+// Category-Description: This example belongs to the Aspose.BarCode image manipulation category, illustrating how to use the BarcodeGenerator class to create a barcode, adjust its rotation via the Parameters.RotationAngle property, and export the image in a specific format such as GIF. Typical use cases include preparing barcodes for printing on rotated media, integrating rotated barcodes into UI assets, or meeting layout requirements. Developers working with barcode generation often need to control orientation and output format, and this snippet shows the essential steps.
+// Prompt: Rotate a generated MaxiCode barcode by 90 degrees and save the rotated image as GIF.
+// Tags: maxicode, rotation, gif, barcode generation, aspose.barcode, image export
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.ComplexBarcode;
-using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating a MaxiCode barcode, rotating it 90°,
-/// and saving the rotated image as a GIF file.
+/// Generates a MaxiCode barcode, rotates it by 90 degrees, and saves the image as a GIF file.
///
class Program
{
///
- /// Entry point of the example. Creates a MaxiCode barcode, rotates the image,
- /// and writes the result to disk.
+ /// Entry point of the example. Creates the barcode, applies rotation, and writes the output file.
///
static void Main()
{
- // Prepare MaxiCode codetext (Mode 2 example) with required fields.
- var maxiCode = new MaxiCodeCodetextMode2
- {
- PostalCode = "524032140",
- CountryCode = 56,
- ServiceCategory = 999
- };
-
- // Add a second message to the MaxiCode payload.
- var secondMessage = new MaxiCodeStandardSecondMessage
- {
- Message = "Sample Message"
- };
- maxiCode.SecondMessage = secondMessage;
+ // Define the output file path for the rotated GIF image.
+ string outputPath = "maxicode_rotated.gif";
- // Generate the MaxiCode image into a memory stream using ComplexBarcodeGenerator.
- using (var generator = new ComplexBarcodeGenerator(maxiCode))
- using (var memory = new MemoryStream())
+ // Initialize a BarcodeGenerator for the MaxiCode symbology with the desired code text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, "Test"))
{
- generator.Save(memory, BarCodeImageFormat.Png);
- memory.Position = 0; // Reset stream position for reading.
+ // Set the rotation angle to 90 degrees to rotate the generated barcode image.
+ generator.Parameters.RotationAngle = 90f;
- // Load the image with Aspose.Drawing, rotate 90 degrees, and save as GIF.
- using (var image = Image.FromStream(memory))
+ // Save the rotated barcode to a memory stream in GIF format.
+ using (var memoryStream = new MemoryStream())
{
- image.RotateFlip(RotateFlipType.Rotate90FlipNone);
- image.Save("maxicode_rotated.gif", ImageFormat.Gif);
+ generator.Save(memoryStream, BarCodeImageFormat.Gif);
+
+ // Write the GIF data from the memory stream to the specified output file.
+ File.WriteAllBytes(outputPath, memoryStream.ToArray());
}
}
}
diff --git a/maxicode-barcode/set-barcode-image-dpi-to-300-when-generating-maxicode-to-improve-print-quality.cs b/maxicode-barcode/set-barcode-image-dpi-to-300-when-generating-maxicode-to-improve-print-quality.cs
index ae12f44..0922121 100644
--- a/maxicode-barcode/set-barcode-image-dpi-to-300-when-generating-maxicode-to-improve-print-quality.cs
+++ b/maxicode-barcode/set-barcode-image-dpi-to-300-when-generating-maxicode-to-improve-print-quality.cs
@@ -1,54 +1,35 @@
-// Title: Generate MaxiCode barcode with 300 DPI resolution
-// Description: Demonstrates creating a MaxiCode barcode and setting its image DPI to 300 for high‑quality printing.
-// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and related classes to produce MaxiCode symbols. Developers often need to adjust image resolution, embed secondary messages, and export to common formats like PNG for printing or scanning applications.
+// Title: Generate a MaxiCode barcode with 300 DPI resolution
+// Description: Demonstrates how to set the image resolution to 300 DPI when creating a MaxiCode barcode, improving print quality for high‑resolution output.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on image resolution settings. It showcases the use of BarcodeGenerator, EncodeTypes, and the Resolution property to control DPI. Developers often need to adjust DPI for printing or publishing barcodes at higher quality, and this snippet illustrates the typical steps for configuring and saving a high‑resolution barcode image.
// Prompt: Set the barcode image DPI to 300 when generating a MaxiCode to improve print quality.
-// Tags: maxicode, barcode generation, dpi, image resolution, aspose.barcode, png
+// Tags: maxicode, dpi, resolution, barcode generation, aspose.barcode, image output, png
-using System;
-using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.ComplexBarcode;
+using Aspose.Drawing;
///
-/// Example program that creates a MaxiCode barcode with a 300 DPI image resolution.
+/// Example program that generates a MaxiCode barcode image with a resolution of 300 DPI.
///
class Program
{
///
- /// Entry point of the application. Generates a MaxiCode, sets its DPI, and saves it as a PNG file.
+ /// Entry point. Creates a MaxiCode barcode, sets its DPI to 300, and saves it as a PNG file.
///
static void Main()
{
- // Define the output file name
- string outputPath = "maxicode.png";
-
- // Prepare MaxiCode codetext (Mode 2 example) with required fields
- var maxiCodeCodetext = new MaxiCodeCodetextMode2
- {
- PostalCode = "524032140", // 9‑digit US postal code
- CountryCode = 056, // USA country code
- ServiceCategory = 999 // Example service category
- };
-
- // Add a simple second message to the MaxiCode
- var secondMessage = new MaxiCodeStandardSecondMessage
+ // Initialize a MaxiCode generator with sample codetext
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MaxiCode, "Sample MaxiCode"))
{
- Message = "Sample MaxiCode"
- };
- maxiCodeCodetext.SecondMessage = secondMessage;
-
- // Generate the MaxiCode using the complex barcode generator
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
- {
- // Set image resolution to 300 DPI for high‑quality print output
+ // Configure the image resolution (dots per inch) to 300
generator.Parameters.Resolution = 300f;
- // Save the generated barcode image as a PNG file
- generator.Save(outputPath, BarCodeImageFormat.Png);
+ // Generate the barcode image as a bitmap
+ using (Aspose.Drawing.Bitmap image = generator.GenerateBarCodeImage())
+ {
+ // Persist the bitmap to a PNG file
+ image.Save("maxicode_300dpi.png");
+ }
}
-
- // Inform the user where the file was saved
- Console.WriteLine($"MaxiCode saved to '{Path.GetFullPath(outputPath)}' with 300 DPI.");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/set-generator-s-imageformat-property-to-gif-and-produce-series-of-maxicode-images.cs b/maxicode-barcode/set-generator-s-imageformat-property-to-gif-and-produce-series-of-maxicode-images.cs
index 68f81e8..78130bf 100644
--- a/maxicode-barcode/set-generator-s-imageformat-property-to-gif-and-produce-series-of-maxicode-images.cs
+++ b/maxicode-barcode/set-generator-s-imageformat-property-to-gif-and-produce-series-of-maxicode-images.cs
@@ -1,58 +1,122 @@
-// Title: Generate MaxiCode Barcodes as GIF Images
-// Description: Demonstrates creating multiple MaxiCode barcodes and saving them as GIF files.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use the BarcodeGenerator class with EncodeTypes.MaxiCode and BarCodeImageFormat to produce barcode images. Typical use cases include batch creation of shipping labels, inventory tags, or any scenario requiring MaxiCode symbols in a lightweight GIF format. Developers often need to automate image format selection and file naming for large sets of barcodes.
-/// Prompt: Set the generator's ImageFormat property to GIF and produce a series of MaxiCode images.
-/// Tags: maxicode, barcode generation, gif, aspose.barcode, imageformat, encode types
+// Title: Generate MaxiCode barcodes in GIF format using Aspose.BarCode
+// Description: Demonstrates how to create MaxiCode barcodes for various modes and save them as GIF images.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator together with MaxiCode codetext classes (e.g., MaxiCodeCodetextMode2, MaxiCodeStandardCodetext) to produce different MaxiCode modes. Developers commonly need to generate MaxiCode symbols for shipping and logistics applications, selecting appropriate modes and output image formats such as GIF.
+// Prompt: Set the generator's ImageFormat property to GIF and produce a series of MaxiCode images.
+// Tags: maxicode, barcode generation, gif, aspose.barcode, complexbarcode, imageformat, c#
using System;
-using System.IO;
-using Aspose.BarCode;
+using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode;
///
-/// Example program that generates a series of MaxiCode barcodes and saves each as a GIF image.
+/// Example program that creates MaxiCode barcodes in GIF format for several modes
+/// using Aspose.BarCode's ComplexBarcodeGenerator.
///
class Program
{
///
- /// Entry point of the application. Creates an output directory, iterates over sample messages,
- /// generates a MaxiCode barcode for each, and saves the result as a GIF file.
+ /// Entry point. Generates MaxiCode images for modes 2‑6 and saves them as GIF files.
///
static void Main()
{
- // Define the directory where generated images will be stored
- string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "MaxiCodeOutputs");
- if (!Directory.Exists(outputDir))
+ // ---------- Mode 2 with a standard second message ----------
+ var mode2Standard = new MaxiCodeCodetextMode2
+ {
+ PostalCode = "524032140",
+ CountryCode = 56,
+ ServiceCategory = 999,
+ SecondMessage = new MaxiCodeStandardSecondMessage { Message = "Standard message" }
+ };
+ using (var generator = new ComplexBarcodeGenerator(mode2Standard))
{
- // Create the directory if it does not already exist
- Directory.CreateDirectory(outputDir);
+ generator.Save("MaxiCode_Mode2_Standard.gif");
}
- // Sample messages to encode in the MaxiCode barcodes
- string[] messages = new string[]
+ // ---------- Mode 2 with a structured second message ----------
+ var structuredMsg2 = new MaxiCodeStructuredSecondMessage();
+ structuredMsg2.Add("634 ALPHA DRIVE");
+ structuredMsg2.Add("PITTSBURGH");
+ structuredMsg2.Add("PA");
+ structuredMsg2.Year = 99;
+
+ var mode2Structured = new MaxiCodeCodetextMode2
{
- "Sample Message 1",
- "Sample Message 2",
- "Sample Message 3",
- "Sample Message 4",
- "Sample Message 5"
+ PostalCode = "524032140",
+ CountryCode = 56,
+ ServiceCategory = 999,
+ SecondMessage = structuredMsg2
};
+ using (var generator = new ComplexBarcodeGenerator(mode2Structured))
+ {
+ generator.Save("MaxiCode_Mode2_Structured.gif");
+ }
- // Loop through each message, generate a barcode, and save it as a GIF image
- for (int i = 0; i < messages.Length; i++)
+ // ---------- Mode 3 with a standard second message ----------
+ var mode3Standard = new MaxiCodeCodetextMode3
{
- // Build the full file path for the current image
- string filePath = Path.Combine(outputDir, $"maxicode_{i + 1}.gif");
+ PostalCode = "B1050",
+ CountryCode = 56,
+ ServiceCategory = 999,
+ SecondMessage = new MaxiCodeStandardSecondMessage { Message = "Standard message" }
+ };
+ using (var generator = new ComplexBarcodeGenerator(mode3Standard))
+ {
+ generator.Save("MaxiCode_Mode3_Standard.gif");
+ }
- // Initialize the barcode generator with MaxiCode symbology and the current message
- using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, messages[i]))
- {
- // Save the generated barcode image in GIF format
- generator.Save(filePath, BarCodeImageFormat.Gif);
- }
+ // ---------- Mode 3 with a structured second message ----------
+ var structuredMsg3 = new MaxiCodeStructuredSecondMessage();
+ structuredMsg3.Add("634 ALPHA DRIVE");
+ structuredMsg3.Add("PITTSBURGH");
+ structuredMsg3.Add("PA");
+ structuredMsg3.Year = 99;
+
+ var mode3Structured = new MaxiCodeCodetextMode3
+ {
+ PostalCode = "B1050",
+ CountryCode = 56,
+ ServiceCategory = 999,
+ SecondMessage = structuredMsg3
+ };
+ using (var generator = new ComplexBarcodeGenerator(mode3Structured))
+ {
+ generator.Save("MaxiCode_Mode3_Structured.gif");
+ }
+
+ // ---------- Mode 4 (standard) ----------
+ var mode4 = new MaxiCodeStandardCodetext
+ {
+ Mode = MaxiCodeMode.Mode4,
+ Message = "Mode 4 message"
+ };
+ using (var generator = new ComplexBarcodeGenerator(mode4))
+ {
+ generator.Save("MaxiCode_Mode4.gif");
+ }
+
+ // ---------- Mode 5 (standard) ----------
+ var mode5 = new MaxiCodeStandardCodetext
+ {
+ Mode = MaxiCodeMode.Mode5,
+ Message = "Mode 5 message"
+ };
+ using (var generator = new ComplexBarcodeGenerator(mode5))
+ {
+ generator.Save("MaxiCode_Mode5.gif");
+ }
+
+ // ---------- Mode 6 (standard) ----------
+ var mode6 = new MaxiCodeStandardCodetext
+ {
+ Mode = MaxiCodeMode.Mode6,
+ Message = "Mode 6 message"
+ };
+ using (var generator = new ComplexBarcodeGenerator(mode6))
+ {
+ generator.Save("MaxiCode_Mode6.gif");
}
- // Inform the user about the successful generation
- Console.WriteLine($"Generated {messages.Length} MaxiCode GIF images in: {outputDir}");
+ Console.WriteLine("All MaxiCode GIF images have been generated.");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/set-generator-s-modulesize-property-to-2-to-produce-denser-maxicode-image-for-compact-labels.cs b/maxicode-barcode/set-generator-s-modulesize-property-to-2-to-produce-denser-maxicode-image-for-compact-labels.cs
index a08153b..d395c7a 100644
--- a/maxicode-barcode/set-generator-s-modulesize-property-to-2-to-produce-denser-maxicode-image-for-compact-labels.cs
+++ b/maxicode-barcode/set-generator-s-modulesize-property-to-2-to-produce-denser-maxicode-image-for-compact-labels.cs
@@ -1,43 +1,45 @@
// Title: Generate a dense MaxiCode barcode with custom module size
-// Description: Demonstrates how to set the ModuleSize (XDimension) to 2 points for a denser MaxiCode, suitable for compact label printing.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on MaxiCode symbology. It showcases the use of BarcodeGenerator, EncodeTypes, and XDimension properties to control barcode density. Developers creating packaging, shipping labels, or inventory tags often need to adjust module size for space‑constrained layouts.
+// Description: Demonstrates how to create a MaxiCode barcode (Mode 2) using Aspose.BarCode, set the module size to produce a denser image suitable for compact labels, and save it as PNG.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on MaxiCode symbology. It shows how to use the ComplexBarcodeGenerator with MaxiCodeCodetextMode2, configure barcode parameters such as XDimension and resolution, and output the result. Developers working with shipping, logistics, or inventory systems often need to generate high‑density MaxiCode images for small packaging.
// Prompt: Set the generator's ModuleSize property to 2 to produce a denser MaxiCode image for compact labels.
-// Tags: maxicode, module size, barcode generation, png, aspose.barcode, encoding
+// Tags: maxicode, barcode, module size, densify, complexbarcode, generation, png, aspnet.barcode
using System;
-using System.IO;
-using Aspose.BarCode;
+using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating a MaxiCode barcode with a custom module size for denser output.
+/// Demonstrates generating a dense MaxiCode barcode (Mode 2) and saving it as a PNG file.
///
class Program
{
///
- /// Entry point. Generates a MaxiCode barcode, sets XDimension to 2 points, and saves as PNG.
+ /// Entry point of the example. Creates a MaxiCode codetext, configures the generator,
+ /// and saves the barcode image.
///
static void Main()
{
- // Sample codetext for MaxiCode
- const string codeText = "Sample MaxiCode";
-
- // Output file path
- string outputPath = "maxicode.png";
+ // Create MaxiCode codetext for Mode 2 (postal + data)
+ var maxiCodeData = new MaxiCodeCodetextMode2
+ {
+ PostalCode = "524032140",
+ CountryCode = 56,
+ ServiceCategory = 999,
+ // Add a secondary message to the barcode
+ SecondMessage = new MaxiCodeStandardSecondMessage { Message = "Sample data" }
+ };
- // Create a MaxiCode generator
- using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, codeText))
+ // Initialize the ComplexBarcodeGenerator with the codetext
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
{
- // Set module size (XDimension) to 2 points for a denser image
+ // Set the module size (XDimension) to 2 points for a denser MaxiCode
generator.Parameters.Barcode.XDimension.Point = 2f;
- // Save the generated barcode as PNG
- generator.Save(outputPath, BarCodeImageFormat.Png);
- }
+ // Optional: set image resolution (dots per inch)
+ generator.Parameters.Resolution = 300;
- // Inform the user where the file was saved
- Console.WriteLine($"MaxiCode barcode saved to: {Path.GetFullPath(outputPath)}");
+ // Generate and save the barcode image to a file
+ generator.Save("maxicode_dense.png");
+ }
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/upload-generated-maxicode-png-file-to-azure-blob-storage-using-azure-sdk-after-successful-creation.cs b/maxicode-barcode/upload-generated-maxicode-png-file-to-azure-blob-storage-using-azure-sdk-after-successful-creation.cs
index 142a58b..183cc43 100644
--- a/maxicode-barcode/upload-generated-maxicode-png-file-to-azure-blob-storage-using-azure-sdk-after-successful-creation.cs
+++ b/maxicode-barcode/upload-generated-maxicode-png-file-to-azure-blob-storage-using-azure-sdk-after-successful-creation.cs
@@ -1,90 +1,70 @@
-// Title: Generate MaxiCode PNG and upload to Azure Blob Storage
-// Description: Demonstrates creating a MaxiCode barcode (Mode 2) as a PNG image using Aspose.BarCode and outlines how to upload the generated file to Azure Blob storage.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as MaxiCode. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and related classes to produce high‑density 2‑D barcodes, a common requirement for logistics and shipping applications. Developers often need to generate these barcodes programmatically and store them in cloud services like Azure for further processing or distribution.
+// Title: Generate MaxiCode barcode and upload to Azure Blob storage
+// Description: Demonstrates creating a MaxiCode barcode image in PNG format using Aspose.BarCode and outlines how to upload the file to Azure Blob storage with the Azure SDK.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat to produce barcode images. Typical use cases include creating shipping labels or inventory tags, after which developers often need to store the generated images in cloud storage such as Azure Blob. The snippet illustrates the workflow from barcode creation to cloud upload, useful for developers integrating barcode generation into cloud‑based applications.
// Prompt: Upload a generated MaxiCode PNG file to Azure Blob storage using the Azure SDK after successful creation.
-// Tags: maxicode, generation, png, complexbarcode, azureblob, aspnet, barcode
+// Tags: maxicode, barcode generation, png, azure blob storage, aspose.barcode, upload
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.ComplexBarcode;
+using Aspose.Drawing;
///
-/// Example program that creates a MaxiCode barcode image and demonstrates how to upload it to Azure Blob storage.
+/// Generates a MaxiCode barcode image and demonstrates how to upload it to Azure Blob storage.
///
class Program
{
///
- /// Entry point of the application. Generates a MaxiCode PNG and optionally uploads it to Azure Blob storage.
+ /// Entry point of the example. Creates a MaxiCode PNG file and (optionally) uploads it to Azure Blob storage.
///
static void Main()
{
- // Prepare MaxiCode codetext (Mode 2) with sample data
- var maxiCodeCodetext = new MaxiCodeCodetextMode2
- {
- PostalCode = "524032140", // 9‑digit US postal code
- CountryCode = 56, // USA numeric country code
- ServiceCategory = 999 // Sample service category
- };
-
- // Standard second message (optional additional data)
- var secondMessage = new MaxiCodeStandardSecondMessage
- {
- Message = "Sample MaxiCode message"
- };
- maxiCodeCodetext.SecondMessage = secondMessage;
+ // Define the local file path where the generated MaxiCode image will be saved.
+ string localPath = Path.Combine(Directory.GetCurrentDirectory(), "maxicode.png");
- // Generate the MaxiCode image into a memory stream
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ // Create a BarcodeGenerator for the MaxiCode symbology with the desired message.
+ using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, "Test message"))
{
- using (var ms = new MemoryStream())
- {
- // Save the barcode as PNG to the memory stream
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for subsequent reads
+ // Save the generated barcode directly to a PNG file.
+ generator.Save(localPath, BarCodeImageFormat.Png);
+ }
- // Write the PNG to a local file (fallback for environments without Azure SDK)
- const string localPath = "maxicode.png";
- using (var fileStream = new FileStream(localPath, FileMode.Create, FileAccess.Write))
- {
- ms.CopyTo(fileStream);
- }
+ // ----------------------------------------------------------------------
+ // Azure Blob Storage upload (commented out because the Azure SDK is not
+ // available in the current execution environment). Uncomment and adjust
+ // the code below when running in an environment with Azure.Storage.Blobs
+ // installed and a valid connection string.
+ // ----------------------------------------------------------------------
+ /*
+ // Install-Package Azure.Storage.Blobs
+ using Azure.Storage.Blobs;
+ using Azure.Storage.Blobs.Specialized;
- Console.WriteLine($"MaxiCode image saved locally to '{localPath}'.");
+ string connectionString = "";
+ string containerName = "";
+ string blobName = "maxicode.png";
- // ------------------------------------------------------------
- // Azure Blob Storage upload (requires Azure.Storage.Blobs package)
- // The following code demonstrates the intended upload logic.
- // Uncomment and ensure the Azure.Storage.Blobs NuGet package is referenced
- // when running in an environment where Azure SDK is available.
- // ------------------------------------------------------------
- /*
- try
- {
- // Replace with your actual Azure Storage connection string and container name
- string connectionString = "";
- string containerName = "";
- string blobName = "maxicode.png";
+ // Create a client to interact with the Azure storage account.
+ BlobServiceClient serviceClient = new BlobServiceClient(connectionString);
- // Create a BlobServiceClient to interact with the storage account
- var blobServiceClient = new Azure.Storage.Blobs.BlobServiceClient(connectionString);
- var containerClient = blobServiceClient.GetBlobContainerClient(containerName);
- containerClient.CreateIfNotExists();
+ // Get a reference to the container (creates it if it does not exist).
+ BlobContainerClient containerClient = serviceClient.GetBlobContainerClient(containerName);
+ containerClient.CreateIfNotExists();
- // Get a reference to the blob and upload the image
- var blobClient = containerClient.GetBlobClient(blobName);
- ms.Position = 0; // Reset stream position before upload
- blobClient.Upload(ms, overwrite: true);
+ // Get a reference to the target blob within the container.
+ BlobClient blobClient = containerClient.GetBlobClient(blobName);
- Console.WriteLine($"MaxiCode image uploaded to Azure Blob storage as '{blobName}'.");
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Azure upload failed: {ex.Message}");
- }
- */
- }
+ // Open the local PNG file and upload its contents to the blob.
+ using (FileStream fileStream = File.OpenRead(localPath))
+ {
+ blobClient.Upload(fileStream, overwrite: true);
}
+
+ Console.WriteLine($"Uploaded '{localPath}' to blob '{blobName}' in container '{containerName}'.");
+ */
+
+ // Indicate that the barcode image has been generated (and would be uploaded if enabled).
+ Console.WriteLine($"Generated MaxiCode image saved to: {localPath}");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/use-async-methods-to-generate-maxicode-image-and-write-it-to-file-without-blocking-ui.cs b/maxicode-barcode/use-async-methods-to-generate-maxicode-image-and-write-it-to-file-without-blocking-ui.cs
index 3fa3e32..e25f23d 100644
--- a/maxicode-barcode/use-async-methods-to-generate-maxicode-image-and-write-it-to-file-without-blocking-ui.cs
+++ b/maxicode-barcode/use-async-methods-to-generate-maxicode-image-and-write-it-to-file-without-blocking-ui.cs
@@ -1,14 +1,14 @@
-// Title: Generate MaxiCode barcode asynchronously and save as PNG
-// Description: Demonstrates using async/await to create a MaxiCode barcode image without blocking the UI thread.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, focusing on complex barcode symbologies such as MaxiCode. It showcases the ComplexBarcodeGenerator and MaxiCodeCodetextMode2 classes for creating high‑density 2‑D barcodes, a common requirement in logistics and shipping applications. Developers often need to generate these barcodes in background tasks to keep UI responsive.
+// Title: Generate MaxiCode barcode image asynchronously
+// Description: Demonstrates how to create a MaxiCode barcode using Aspose.BarCode and save it to a PNG file without blocking the UI thread.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode symbologies such as MaxiCode. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and asynchronous file I/O to produce barcode images efficiently. Developers working with shipping, logistics, or inventory systems often need to generate MaxiCode symbols programmatically for labeling and tracking purposes.
// Prompt: Use async methods to generate a MaxiCode image and write it to a file without blocking the UI.
-// Tags: maxicode, barcode, async, generation, png, aspose.barcode, complexbarcodegenerator
+// Tags: maxicode, barcode, async, file-io, png, aspose.barcode, complexbarcodegenerator
using System;
using System.IO;
using System.Threading.Tasks;
-using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.BarCode.Generation;
///
/// Demonstrates asynchronous generation of a MaxiCode barcode image and saving it to a file.
@@ -16,51 +16,43 @@
class Program
{
///
- /// Entry point of the console application. Calls the asynchronous barcode generation method.
+ /// Asynchronous entry point that creates a MaxiCode barcode and writes it to a PNG file without blocking the UI thread.
///
- /// Command‑line arguments (not used).
- static async Task Main(string[] args)
+ /// A task representing the asynchronous operation.
+ static async Task Main()
{
- // Define the output file path for the generated PNG image
+ // Define the output file path for the generated PNG image.
string outputPath = "maxicode.png";
- // Generate the MaxiCode barcode asynchronously
- await GenerateMaxiCodeAsync(outputPath);
-
- // Inform the user that the image has been saved
- Console.WriteLine($"MaxiCode image saved to: {outputPath}");
- }
+ // Prepare MaxiCode data using Mode 2 (postal code, country code, service category).
+ var maxiCodeData = new MaxiCodeCodetextMode2
+ {
+ PostalCode = "524032140", // 9‑digit postal code for Mode 2
+ CountryCode = 56, // Example country code
+ ServiceCategory = 999 // Example service category
+ };
- ///
- /// Generates a MaxiCode barcode using the ComplexBarcodeGenerator and saves it to the specified path.
- /// The operation runs on a background thread to avoid blocking the UI.
- ///
- /// File system path where the PNG image will be saved.
- static async Task GenerateMaxiCodeAsync(string path)
- {
- // Execute the barcode generation on a thread‑pool thread
- await Task.Run(() =>
+ // Use a memory stream to hold the generated barcode image in memory.
+ using (var memoryStream = new MemoryStream())
{
- // Prepare MaxiCode codetext (Mode 2 with a standard second message)
- var maxiCode = new MaxiCodeCodetextMode2
+ // Generate the barcode image on a background thread to avoid UI blocking.
+ await Task.Run(() =>
{
- PostalCode = "524032140",
- CountryCode = 56,
- ServiceCategory = 999
- };
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
+ {
+ // Save the barcode directly to the memory stream in PNG format.
+ generator.Save(memoryStream, BarCodeImageFormat.Png);
+ }
+ });
- // Create the optional second message for the MaxiCode
- var secondMessage = new MaxiCodeStandardSecondMessage
- {
- Message = "Sample message"
- };
- maxiCode.SecondMessage = secondMessage;
+ // Reset the stream position to the beginning before reading its contents.
+ memoryStream.Position = 0;
- // Generate and save the barcode image using the ComplexBarcodeGenerator
- using (var generator = new ComplexBarcodeGenerator(maxiCode))
- {
- generator.Save(path, BarCodeImageFormat.Png);
- }
- });
+ // Asynchronously write the image bytes from the memory stream to the file system.
+ await File.WriteAllBytesAsync(outputPath, memoryStream.ToArray());
+ }
+
+ // Inform the user where the image has been saved.
+ Console.WriteLine($"MaxiCode image saved to '{Path.GetFullPath(outputPath)}'.");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/use-barcodereader-to-decode-maxicode-image-streamed-from-network-socket-without-saving-to-disk.cs b/maxicode-barcode/use-barcodereader-to-decode-maxicode-image-streamed-from-network-socket-without-saving-to-disk.cs
index 1877dce..eb593e7 100644
--- a/maxicode-barcode/use-barcodereader-to-decode-maxicode-image-streamed-from-network-socket-without-saving-to-disk.cs
+++ b/maxicode-barcode/use-barcodereader-to-decode-maxicode-image-streamed-from-network-socket-without-saving-to-disk.cs
@@ -1,111 +1,107 @@
-// Title: Decode MaxiCode from Network Stream using BarcodeReader
-// Description: Demonstrates decoding a MaxiCode barcode received over a TCP socket without writing the image to disk.
-// Category-Description: This example belongs to the Aspose.BarCode reading and complex barcode handling category. It showcases the use of BarCodeReader, ComplexCodetextReader, and related classes to decode MaxiCode symbols directly from a streamed image. Developers working with real‑time barcode scanning, networked devices, or in‑memory image processing will find such patterns useful for building low‑latency barcode solutions.
+// Title: Decode MaxiCode barcode from a network stream using BarCodeReader
+// Description: Demonstrates how to generate a MaxiCode barcode, transmit it over a TCP socket, and decode it directly from the received stream without writing to disk.
+// Category-Description: This example belongs to the Aspose.BarCode reading category, showcasing in‑memory barcode processing. It uses BarcodeGenerator to create a barcode, TcpListener/TcpClient for network transmission, and BarCodeReader with DecodeType.MaxiCode to extract data. Developers working with real‑time barcode scanning, networked devices, or streaming scenarios can adapt this pattern for efficient, disk‑free decoding.
// Prompt: Use the BarcodeReader to decode a MaxiCode image streamed from a network socket without saving to disk.
-// Tags: maxicode, barcode decoding, network stream, barcodereader, aspose.barcode, complexbarcode, tcp
+// Tags: maxicode, barcode reading, streaming, network socket, aspose.barcode, in‑memory processing
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
-using System.Threading.Tasks;
+using System.Threading;
+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 generates a MaxiCode barcode, streams it over a TCP socket,
-/// and decodes it directly from the received network stream using Aspose.BarCode APIs.
+/// Example program that generates a MaxiCode barcode, sends it over a TCP socket,
+/// and decodes it directly from the received stream using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the example. Generates a MaxiCode image in memory, sends it via a TCP server,
- /// receives it as a client, and decodes the barcode without persisting the image to disk.
+ /// Entry point. Performs in‑memory barcode generation, network transmission,
+ /// and decoding without persisting any files to disk.
///
static void Main()
{
// ------------------------------------------------------------
- // Generate a sample MaxiCode image in memory
+ // 1. Generate a sample MaxiCode barcode image into a memory stream.
// ------------------------------------------------------------
- var maxiCode = new MaxiCodeCodetextMode2();
- maxiCode.PostalCode = "524032140";
- maxiCode.CountryCode = 56;
- maxiCode.ServiceCategory = 999;
- var secondMessage = new MaxiCodeStandardSecondMessage();
- secondMessage.Message = "Sample message";
- maxiCode.SecondMessage = secondMessage;
-
byte[] imageBytes;
- using (var generator = new ComplexBarcodeGenerator(maxiCode))
+ using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, "Test MaxiCode"))
{
+ // Set visual appearance of the barcode.
+ generator.Parameters.Barcode.BarColor = Color.Black;
+ generator.Parameters.BackColor = Color.White;
+
+ // Save the generated image to a temporary memory stream.
using (var ms = new MemoryStream())
{
- // Save the generated barcode as PNG into the memory stream
generator.Save(ms, BarCodeImageFormat.Png);
- imageBytes = ms.ToArray(); // Capture the image bytes for transmission
+ imageBytes = ms.ToArray(); // Capture the raw PNG bytes.
}
}
// ------------------------------------------------------------
- // Start a simple TCP server that sends the image bytes
+ // 2. Set up a TCP listener on a dynamic (ephemeral) port.
// ------------------------------------------------------------
- var listener = new TcpListener(IPAddress.Loopback, 5000);
- listener.Start();
- var serverTask = Task.Run(() =>
+ int port;
+ using (var listener = new TcpListener(IPAddress.Loopback, 0))
{
- using (var client = listener.AcceptTcpClient())
- using (var networkStream = client.GetStream())
+ listener.Start();
+ port = ((IPEndPoint)listener.LocalEndpoint).Port;
+
+ // --------------------------------------------------------
+ // 3. Start a client thread that connects to the listener and
+ // streams the generated image bytes.
+ // --------------------------------------------------------
+ var clientThread = new Thread(() =>
{
- // Write the entire image byte array to the connected client
- networkStream.Write(imageBytes, 0, imageBytes.Length);
- }
- });
+ using (var client = new TcpClient())
+ {
+ client.Connect(IPAddress.Loopback, port);
+ using (var netStream = client.GetStream())
+ {
+ netStream.Write(imageBytes, 0, imageBytes.Length);
+ }
+ }
+ });
+ clientThread.Start();
- // ------------------------------------------------------------
- // Connect as a client and read the image stream
- // ------------------------------------------------------------
- using (var client = new TcpClient())
- {
- client.Connect(IPAddress.Loopback, 5000);
- using (var netStream = client.GetStream())
+ // --------------------------------------------------------
+ // 4. Accept the incoming connection and read the image data
+ // into a memory stream for decoding.
+ // --------------------------------------------------------
+ using (var serverClient = listener.AcceptTcpClient())
+ using (var netStream = serverClient.GetStream())
using (var receivedMs = new MemoryStream())
{
- // Copy the incoming data into a memory stream for decoding
netStream.CopyTo(receivedMs);
- receivedMs.Position = 0; // Reset position to the beginning
+ receivedMs.Position = 0; // Reset position for reading.
- // --------------------------------------------------------
- // Decode the MaxiCode from the received stream
- // --------------------------------------------------------
+ // ----------------------------------------------------
+ // 5. Decode the received image using BarCodeReader for
+ // MaxiCode without writing to disk.
+ // ----------------------------------------------------
using (var reader = new BarCodeReader(receivedMs, DecodeType.MaxiCode))
{
foreach (var result in reader.ReadBarCodes())
{
- // Attempt to parse the complex MaxiCode codetext into a strongly‑typed object
- var decoded = ComplexCodetextReader.TryDecodeMaxiCode(
- result.Extended.MaxiCode.MaxiCodeMode,
- result.CodeText);
-
- if (decoded is MaxiCodeCodetextMode2 decodedMode2)
- {
- Console.WriteLine("Postal Code: " + decodedMode2.PostalCode);
- Console.WriteLine("Country Code: " + decodedMode2.CountryCode);
- Console.WriteLine("Service Category: " + decodedMode2.ServiceCategory);
- if (decodedMode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
- {
- Console.WriteLine("Message: " + stdMsg.Message);
- }
- }
+ Console.WriteLine($"Decoded Text: {result.CodeText}");
+ var bounds = result.Region.Rectangle;
+ Console.WriteLine($"Region - X:{bounds.X}, Y:{bounds.Y}, Width:{bounds.Width}, Height:{bounds.Height}");
}
}
}
- }
- // ------------------------------------------------------------
- // Ensure the server task completes and clean up resources
- // ------------------------------------------------------------
- serverTask.Wait();
- listener.Stop();
+ // ------------------------------------------------------------
+ // 6. Clean up: ensure the client thread finishes and stop the listener.
+ // ------------------------------------------------------------
+ clientThread.Join();
+ listener.Stop();
+ }
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/use-maxicodecodetext-helper-to-concatenate-multiple-secondary-messages-into-single-unstructured-field.cs b/maxicode-barcode/use-maxicodecodetext-helper-to-concatenate-multiple-secondary-messages-into-single-unstructured-field.cs
index 96cd045..e267cb3 100644
--- a/maxicode-barcode/use-maxicodecodetext-helper-to-concatenate-multiple-secondary-messages-into-single-unstructured-field.cs
+++ b/maxicode-barcode/use-maxicodecodetext-helper-to-concatenate-multiple-secondary-messages-into-single-unstructured-field.cs
@@ -1,55 +1,62 @@
-// Title: Generate MaxiCode barcode with concatenated secondary messages
-// Description: Demonstrates how to use MaxiCodeCodetext helper to combine multiple secondary messages into a single unstructured field and generate a MaxiCode barcode.
-// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, focusing on MaxiCode symbology. It showcases the use of MaxiCodeCodetextMode2, MaxiCodeStandardSecondMessage, and ComplexBarcodeGenerator classes to create postal‑oriented MaxiCode barcodes. Developers often need to embed additional data such as secondary messages, postal codes, and service categories when generating MaxiCode for shipping and logistics applications.
+// Title: MaxiCode barcode generation with concatenated secondary messages
+// Description: Demonstrates how to create a MaxiCode barcode using Aspose.BarCode, concatenating several secondary messages into a single unstructured field for Mode 2.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of MaxiCodeCodetextMode2, MaxiCodeStandardSecondMessage, and ComplexBarcodeGenerator to produce a MaxiCode image. Developers working with logistics, shipping, or inventory systems often need to embed multiple data elements in a MaxiCode; this pattern illustrates how to combine secondary messages into one field before encoding.
// Prompt: Use the MaxiCodeCodetext helper to concatenate multiple secondary messages into a single unstructured field.
-// Tags: maxicode, secondary messages, concatenation, complex barcode, generation, aspnet, csharp
+// Tags: maxicode, barcode-generation, secondary-message, concatenation, aspose.barcode, complexbarcode
using System;
-using System.IO;
-using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.ComplexBarcode;
-///
-/// Demonstrates generating a MaxiCode barcode (Mode 2) with concatenated secondary messages using Aspose.BarCode.
-///
-class Program
+namespace MaxiCodeExample
{
///
- /// Entry point. Concatenates secondary messages, builds MaxiCode codetext, and saves the barcode as PNG.
+ /// Generates a MaxiCode barcode (Mode 2) with a concatenated secondary message.
///
- static void Main()
+ class Program
{
- // Sample secondary messages to be concatenated
- string[] secondaryMessages = { "Item A", "Item B", "Item C" };
+ ///
+ /// Entry point of the example. Builds the MaxiCode data, concatenates secondary messages,
+ /// and saves the resulting barcode image to disk.
+ ///
+ static void Main()
+ {
+ // Prepare the primary data required for MaxiCode Mode 2
+ var maxiCodeData = new MaxiCodeCodetextMode2
+ {
+ PostalCode = "524032140", // 9‑digit US postal code
+ CountryCode = 56, // Country code (e.g., USA = 56)
+ ServiceCategory = 999 // Service category identifier
+ };
- // Concatenate messages into a single unstructured string (space‑separated)
- string combinedMessage = string.Join(" ", secondaryMessages);
+ // Define multiple secondary messages that need to be combined
+ string[] secondaryMessages = new[]
+ {
+ "First part of the message",
+ "Second part of the message",
+ "Additional info"
+ };
- // Create MaxiCode codetext for Mode 2 (postal info + data)
- var maxiCodeCodetext = new MaxiCodeCodetextMode2
- {
- PostalCode = "524032140", // 9‑digit US postal code
- CountryCode = 056, // USA numeric country code
- ServiceCategory = 999 // Example service category
- };
+ // Concatenate the secondary messages into a single unstructured string
+ string concatenatedMessage = string.Join(" ", secondaryMessages);
- // Assign the concatenated message as a standard (unstructured) second message
- var standardSecondMessage = new MaxiCodeStandardSecondMessage
- {
- Message = combinedMessage
- };
- maxiCodeCodetext.SecondMessage = standardSecondMessage;
+ // Create a standard (unstructured) second message and assign the concatenated text
+ var secondMessage = new MaxiCodeStandardSecondMessage
+ {
+ Message = concatenatedMessage
+ };
+ maxiCodeData.SecondMessage = secondMessage;
- // Generate the MaxiCode barcode and save it to a PNG file
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
- {
- using (var memoryStream = new MemoryStream())
+ // Generate the MaxiCode barcode using ComplexBarcodeGenerator.
+ // ComplexBarcodeGenerator implements IDisposable, so it is wrapped in a using block.
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
{
- generator.Save(memoryStream, BarCodeImageFormat.Png);
- File.WriteAllBytes("maxicode.png", memoryStream.ToArray());
+ // Produce the barcode image in memory
+ generator.GenerateBarCodeImage();
+
+ // Save the generated image to a file (PNG format by default)
+ generator.Save("maxicode_output.png");
}
}
-
- Console.WriteLine("MaxiCode barcode generated and saved as 'maxicode.png'.");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/use-maxicodecodetextmode2-helper-to-build-complex-primary-data-and-generate-barcode-image.cs b/maxicode-barcode/use-maxicodecodetextmode2-helper-to-build-complex-primary-data-and-generate-barcode-image.cs
index 3134150..ce36684 100644
--- a/maxicode-barcode/use-maxicodecodetextmode2-helper-to-build-complex-primary-data-and-generate-barcode-image.cs
+++ b/maxicode-barcode/use-maxicodecodetextmode2-helper-to-build-complex-primary-data-and-generate-barcode-image.cs
@@ -1,78 +1,58 @@
-// Title: Generate MaxiCode (Mode 2) with Complex Primary Data
-// Description: Demonstrates building a MaxiCode Mode 2 codetext using the MaxiCodeCodetextMode2 helper, then generating and decoding the barcode image.
-// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation and recognition category. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and BarCodeReader to create and read MaxiCode symbols, a common requirement for shipping and logistics applications where detailed routing information is encoded. Developers often need to construct complex codetext structures, render them to images, and verify correctness via decoding.
+// Title: Generate MaxiCode Mode 2 barcode with complex data using Aspose.BarCode
+// Description: Demonstrates building complex primary data for MaxiCode Mode 2 with the MaxiCodeCodetextMode2 helper and saving the barcode 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 MaxiCodeCodetextMode2 and MaxiCodeStructuredSecondMessage to create shipping‑label style barcodes. Developers working with logistics, parcel tracking, or any scenario requiring MaxiCode symbology can follow this pattern to construct detailed primary and secondary messages before rendering the image.
// Prompt: Use the MaxiCodeCodetextMode2 helper to build complex primary data and generate the barcode image.
-// Tags: maxicode, mode2, complex barcode, generation, decoding, aspose.barcode, c#
+// Tags: maxicode, barcode generation, complex barcode, aspose.barcode, image output, shipping label
using System;
-using System.IO;
using Aspose.BarCode.ComplexBarcode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
///
-/// Demonstrates creating a MaxiCode (Mode 2) barcode with complex primary data,
-/// saving it as an image, and decoding it back using Aspose.BarCode.
+/// Example program that creates a MaxiCode Mode 2 barcode with structured primary and secondary data
+/// and saves it as a PNG file.
///
class Program
{
///
- /// Entry point of the example. Builds the codetext, generates the barcode,
- /// saves it to a PNG file, and then reads the file to verify the encoded data.
+ /// Entry point. Builds the MaxiCode data, generates the barcode image, and writes it to disk.
///
static void Main()
{
- // Build MaxiCode codetext for Mode 2 with a standard second message
- var maxiCodeCodetext = new MaxiCodeCodetextMode2();
- maxiCodeCodetext.PostalCode = "524032140"; // 9‑digit US postal code
- maxiCodeCodetext.CountryCode = 56; // Numeric country code
- maxiCodeCodetext.ServiceCategory = 999; // Example service category
-
- // Create and assign the optional standard second message
- var secondMessage = new MaxiCodeStandardSecondMessage();
- secondMessage.Message = "Test message";
- maxiCodeCodetext.SecondMessage = secondMessage;
-
- // Generate and save the MaxiCode image to a PNG file
+ // Define the output file path for the generated barcode image.
string outputPath = "maxicode.png";
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
- {
- generator.Save(outputPath);
- }
- // Verify that the image was created and read it back for validation
- if (File.Exists(outputPath))
+ // Build primary data for MaxiCode Mode 2 using the helper class.
+ var maxiCodeData = new MaxiCodeCodetextMode2
{
- // Initialize a reader for MaxiCode symbols
- using (var reader = new BarCodeReader(outputPath, DecodeType.MaxiCode))
- {
- // Iterate through all detected barcodes (should be one)
- foreach (var result in reader.ReadBarCodes())
- {
- // Decode the complex codetext from the raw CodeText
- var decoded = ComplexCodetextReader.TryDecodeMaxiCode(
- result.Extended.MaxiCode.MaxiCodeMode,
- result.CodeText);
+ PostalCode = "524032140", // 9‑digit US postal code
+ CountryCode = 56, // Example country code
+ ServiceCategory = 999 // Example service category
+ };
- // Cast to the specific Mode 2 type to access its properties
- if (decoded is MaxiCodeCodetextMode2 decodedMode2)
- {
- Console.WriteLine($"PostalCode: {decodedMode2.PostalCode}");
- Console.WriteLine($"CountryCode: {decodedMode2.CountryCode}");
- Console.WriteLine($"ServiceCategory: {decodedMode2.ServiceCategory}");
+ // Build the structured second message (address lines and year).
+ var secondMessage = new MaxiCodeStructuredSecondMessage();
+ secondMessage.Add("634 ALPHA DRIVE");
+ secondMessage.Add("PITTSBURGH");
+ secondMessage.Add("PA");
+ secondMessage.Year = 99; // Two‑digit year
- // Output the optional second message if present
- if (decodedMode2.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
- {
- Console.WriteLine($"Second Message: {stdMsg.Message}");
- }
- }
- }
- }
- }
- else
+ // Assign the second message to the MaxiCode data object.
+ maxiCodeData.SecondMessage = secondMessage;
+
+ // Generate the complex MaxiCode barcode using the ComplexBarcodeGenerator.
+ using (var complexGenerator = new ComplexBarcodeGenerator(maxiCodeData))
{
- Console.WriteLine("Failed to generate the MaxiCode image.");
+ // Produce the barcode image as an Aspose.Drawing.Bitmap.
+ using (Bitmap image = complexGenerator.GenerateBarCodeImage())
+ {
+ // Save the bitmap to the specified file path.
+ image.Save(outputPath);
+ }
}
+
+ // Inform the user where the barcode image was saved.
+ Console.WriteLine($"MaxiCode barcode saved to: {outputPath}");
}
}
\ No newline at end of file
diff --git a/maxicode-barcode/validate-input-fields-for-maxicode-mode-3-using-provided-structured-codetext-classes-before-generation.cs b/maxicode-barcode/validate-input-fields-for-maxicode-mode-3-using-provided-structured-codetext-classes-before-generation.cs
index b2357b5..ecad701 100644
--- a/maxicode-barcode/validate-input-fields-for-maxicode-mode-3-using-provided-structured-codetext-classes-before-generation.cs
+++ b/maxicode-barcode/validate-input-fields-for-maxicode-mode-3-using-provided-structured-codetext-classes-before-generation.cs
@@ -1,118 +1,103 @@
-// Title: Validate MaxiCode Mode 3 Input Fields Using Structured Codetext Classes
-// Description: Demonstrates how to validate the required fields of a MaxiCode Mode 3 codetext object before generating the barcode image.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as MaxiCode. It showcases the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode3, and related second‑message classes to prepare and validate data before rendering. Developers working with shipping or logistics barcodes often need to ensure data conforms to MaxiCode specifications, making validation a common prerequisite.
+// Title: Validate MaxiCode Mode 3 Input and Generate PNG Barcode
+// Description: Demonstrates how to validate required fields for MaxiCode Mode 3 using Aspose.BarCode's structured codetext classes, then generate a PNG barcode image.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on complex barcode types such as MaxiCode. It showcases the use of ComplexBarcodeGenerator together with MaxiCodeCodetextMode3 and related second‑message classes, a common scenario for developers needing to ensure data integrity before creating shipping or logistics barcodes. Typical use cases include validating postal codes, country codes, and service categories prior to barcode rendering.
// Prompt: Validate input fields for MaxiCode Mode 3 using the provided structured codetext classes before generation.
-// Tags: maxicode, validation, image, complexbarcodegenerator, codetext, aspnet, csharp
+// Tags: maxicode, validation, generation, png, complexbarcodegenerator, maxicodecodetextmode3, maxicodestandardsecondmessage, maxicodestructuredsecondmessage
using System;
+using System.IO;
using System.Text.RegularExpressions;
-using Aspose.BarCode.ComplexBarcode;
-using Aspose.BarCode.Generation;
using Aspose.BarCode;
+using Aspose.BarCode.Generation;
+using Aspose.BarCode.ComplexBarcode;
+using Aspose.BarCode.BarCodeRecognition;
///
-/// Example program that validates MaxiCode Mode 3 data and generates a barcode image.
+/// Demonstrates validation of MaxiCode Mode 3 data and barcode generation using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application. Builds a MaxiCode Mode 3 codetext, validates it,
- /// and generates a PNG image using Aspose.BarCode.
+ /// Validates the fields required for MaxiCode Mode 3.
+ /// Throws if any field is invalid.
///
- static void Main()
+ /// The MaxiCode codetext object containing mode‑3 data.
+ static void ValidateMaxiCodeMode3(MaxiCodeCodetextMode3 data)
{
- // ------------------------------------------------------------
- // Prepare sample data for MaxiCode Mode 3
- // ------------------------------------------------------------
- var codetext = new MaxiCodeCodetextMode3
- {
- PostalCode = "B1050A", // 6 alphanumeric characters
- CountryCode = 56, // 3‑digit numeric country code
- ServiceCategory = 999 // 3‑digit service category
- };
+ if (data == null)
+ throw new ArgumentException("MaxiCode data object cannot be null.");
- // Optional standard second message (e.g., additional textual information)
- var secondMessage = new MaxiCodeStandardSecondMessage
+ // PostalCode must be exactly 6 alphanumeric characters.
+ if (string.IsNullOrEmpty(data.PostalCode) ||
+ data.PostalCode.Length != 6 ||
+ !Regex.IsMatch(data.PostalCode, @"^[A-Za-z0-9]{6}$"))
{
- Message = "Sample message"
- };
- codetext.SecondMessage = secondMessage;
+ throw new ArgumentException("PostalCode must be exactly 6 alphanumeric characters for MaxiCode Mode 3.");
+ }
- // ------------------------------------------------------------
- // Validate the codetext before attempting barcode generation
- // ------------------------------------------------------------
- try
+ // CountryCode must be a three‑digit number (0‑999).
+ if (data.CountryCode < 0 || data.CountryCode > 999)
{
- ValidateMaxiCodeMode3(codetext);
+ throw new ArgumentException("CountryCode must be between 0 and 999.");
}
- catch (ArgumentException ex)
+
+ // ServiceCategory must be a three‑digit number (0‑999).
+ if (data.ServiceCategory < 0 || data.ServiceCategory > 999)
{
- Console.WriteLine($"Validation error: {ex.Message}");
- return; // Abort if validation fails
+ throw new ArgumentException("ServiceCategory must be between 0 and 999.");
}
- // ------------------------------------------------------------
- // Generate the barcode image and save it to disk
- // ------------------------------------------------------------
- using (var generator = new ComplexBarcodeGenerator(codetext))
+ // Optional: if a second message is supplied, ensure it is of a supported type.
+ if (data.SecondMessage != null &&
+ !(data.SecondMessage is MaxiCodeStandardSecondMessage) &&
+ !(data.SecondMessage is MaxiCodeStructuredSecondMessage))
{
- generator.GenerateBarCodeImage(); // Render the barcode
- generator.Save("maxicode_mode3.png"); // Save as PNG
+ throw new ArgumentException("SecondMessage must be either MaxiCodeStandardSecondMessage or MaxiCodeStructuredSecondMessage.");
}
-
- Console.WriteLine("MaxiCode Mode 3 barcode generated successfully.");
}
///
- /// Validates the fields of a MaxiCodeCodetextMode3 instance according to
- /// MaxiCode Mode 3 specifications, including optional second‑message validation.
+ /// Entry point of the example. Creates sample data, validates it, and generates a MaxiCode Mode 3 PNG barcode.
///
- /// The codetext object to validate.
- static void ValidateMaxiCodeMode3(MaxiCodeCodetextMode3 codetext)
+ static void Main()
{
- if (codetext == null)
- throw new ArgumentException("Codetext object cannot be null.");
-
- // PostalCode: exactly 6 alphanumeric characters
- if (string.IsNullOrEmpty(codetext.PostalCode) ||
- codetext.PostalCode.Length != 6 ||
- !Regex.IsMatch(codetext.PostalCode, @"^[A-Za-z0-9]{6}$"))
+ // Sample valid data for MaxiCode Mode 3.
+ var maxiCodeData = new MaxiCodeCodetextMode3
{
- throw new ArgumentException("PostalCode must be exactly 6 alphanumeric characters for MaxiCode Mode 3.");
- }
+ PostalCode = "B1050A", // 6 alphanumeric characters
+ CountryCode = 56, // example country code
+ ServiceCategory = 999 // example service category
+ };
- // CountryCode: numeric value between 0 and 999 (inclusive)
- if (codetext.CountryCode < 0 || codetext.CountryCode > 999)
+ // Optional: add a standard second message.
+ var secondMessage = new MaxiCodeStandardSecondMessage
{
- throw new ArgumentException("CountryCode must be a 3‑digit integer between 0 and 999.");
- }
+ Message = "Sample message"
+ };
+ maxiCodeData.SecondMessage = secondMessage;
- // ServiceCategory: numeric value between 0 and 999 (inclusive)
- if (codetext.ServiceCategory < 0 || codetext.ServiceCategory > 999)
+ try
{
- throw new ArgumentException("ServiceCategory must be a 3‑digit integer between 0 and 999.");
- }
+ // Perform manual validation before generation.
+ ValidateMaxiCodeMode3(maxiCodeData);
- // Validate second message if it is provided
- if (codetext.SecondMessage != null)
- {
- if (codetext.SecondMessage is MaxiCodeStandardSecondMessage stdMsg)
+ // Generate the barcode using ComplexBarcodeGenerator.
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeData))
{
- // Standard second message must contain non‑empty text
- if (string.IsNullOrWhiteSpace(stdMsg.Message))
- throw new ArgumentException("Standard second message must contain non‑empty text.");
- }
- else if (codetext.SecondMessage is MaxiCodeStructuredSecondMessage structMsg)
- {
- // Structured second message must have at least one identifier
- if (structMsg.Identifiers == null || structMsg.Identifiers.Count == 0)
- throw new ArgumentException("Structured second message must contain at least one identifier.");
- }
- else
- {
- // Any other type is not supported in this example
- throw new ArgumentException("Unsupported second message type.");
+ // Save the image to a PNG file in the current directory.
+ string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "maxicode_mode3.png");
+ generator.Save(outputPath, BarCodeImageFormat.Png);
+ Console.WriteLine($"MaxiCode Mode 3 barcode saved to: {outputPath}");
}
}
+ catch (ArgumentException ex)
+ {
+ Console.WriteLine($"Validation error: {ex.Message}");
+ }
+ catch (Exception ex)
+ {
+ // Catch any unexpected errors from the Aspose library.
+ Console.WriteLine($"An error occurred during barcode generation: {ex.Message}");
+ }
}
}
\ No newline at end of file