GenerateBarcodeAsync(BaseEncodeType type, string codeText, string outputPath)
+ /// Command‑line arguments (not used).
+ static async Task Main(string[] args)
{
- // Offload the generation to a thread‑pool thread to avoid blocking the caller.
- return await Task.Run(() =>
- {
- // Create a BarcodeGenerator with the specified type and text.
- using (var generator = new BarcodeGenerator(type, codeText))
- {
- // Optional: set image resolution (dots per inch).
- generator.Parameters.Resolution = 300f;
+ // Asynchronously generate a barcode without blocking the calling thread.
+ await GenerateBarcodeAsync("async_barcode.png", EncodeTypes.Code128, "AsyncDemo");
- // Save the generated barcode image to the specified path.
- generator.Save(outputPath);
- }
-
- // Return the path of the saved file to the caller.
- return outputPath;
- });
+ // Inform the user that the operation has finished.
+ Console.WriteLine("Barcode generation completed.");
}
///
- /// Asynchronous entry point of the console application.
+ /// Generates a barcode image on a background thread.
///
- /// Command‑line arguments (not used).
- static async Task Main(string[] args)
+ /// File path where the barcode image will be saved.
+ /// The barcode symbology to use (e.g., Code128).
+ /// The text to encode in the barcode.
+ /// A task representing the asynchronous operation.
+ private static Task GenerateBarcodeAsync(string outputPath, BaseEncodeType encodeType, string codeText)
{
- // Define the barcode symbology and the text to encode.
- BaseEncodeType barcodeType = EncodeTypes.Code128;
- string sampleText = "123ABC";
-
- // Define the output file name for the generated image.
- string outputFile = "barcode.png";
-
- // Generate the barcode image without blocking the main thread.
- string savedPath = await GenerateBarcodeAsync(barcodeType, sampleText, outputFile);
-
- // Output the location of the saved barcode image.
- Console.WriteLine($"Barcode image saved to: {savedPath}");
+ // Offload the generation to a background thread to keep the UI responsive.
+ return Task.Run(() =>
+ {
+ // BarcodeGenerator implements IDisposable; ensure resources are released promptly.
+ using (var generator = new BarcodeGenerator(encodeType, codeText))
+ {
+ // Save the generated barcode image to the specified file.
+ generator.Save(outputPath);
+ }
+ });
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/provide-example-showing-how-to-embed-generated-barcode-into-email-body-using-mime-multipart.cs b/two-dimensional-barcode-types/provide-example-showing-how-to-embed-generated-barcode-into-email-body-using-mime-multipart.cs
index d653c9a..a6385c7 100644
--- a/two-dimensional-barcode-types/provide-example-showing-how-to-embed-generated-barcode-into-email-body-using-mime-multipart.cs
+++ b/two-dimensional-barcode-types/provide-example-showing-how-to-embed-generated-barcode-into-email-body-using-mime-multipart.cs
@@ -1,77 +1,101 @@
+// Title: Embed Barcode Image into Email Body Using MIME Multipart
+// Description: Demonstrates generating a Code128 barcode with Aspose.BarCode, embedding it as an inline image in an HTML email using MIME multipart, and saving the message to a pickup directory.
+// Category-Description: This example belongs to the Aspose.BarCode email integration category, showing how to combine barcode generation (BarcodeGenerator) with .NET System.Net.Mail classes (MailMessage, AlternateView, LinkedResource) to embed barcodes directly in email bodies. Typical use cases include sending invoices, tickets, or verification codes where the barcode must appear inline. Developers often need to generate barcodes on‑the‑fly and attach them as inline images without writing temporary files.
+// Prompt: Provide example showing how to embed generated barcode into an email body using MIME multipart.
+// Tags: code128, barcode generation, png, email, mime, aspose.barcode, aspose.drawing, system.net.mail
+
using System;
using System.IO;
using System.Net.Mail;
-using System.Net.Mime;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing.Imaging;
+using Aspose.Drawing;
///
-/// Demonstrates generating a barcode, embedding it in an HTML email, and saving the email to a pickup directory.
+/// Demonstrates generating a barcode and embedding it into an email body using MIME multipart.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a barcode, creates an email with the barcode embedded as an inline image,
- /// and writes the email to a temporary pickup directory.
+ /// Entry point of the example. Generates a Code128 barcode, embeds it in an HTML email,
+ /// and writes the resulting MIME message to a temporary .eml file.
///
static void Main()
{
- // Generate a barcode image and keep it in a memory stream
- using (var barcodeStream = new MemoryStream())
+ // Generate a Code128 barcode and keep it in a memory stream
+ using (MemoryStream barcodeStream = new MemoryStream())
{
- // Create a barcode generator for Code128 with the value "123ABC"
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC"))
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC"))
{
+ // Optional: customize appearance
+ generator.Parameters.Barcode.BarColor = Color.Black;
+ generator.Parameters.BackColor = Color.White;
+
// Save the barcode as PNG into the memory stream
generator.Save(barcodeStream, BarCodeImageFormat.Png);
}
- // Reset stream position for reading from the beginning
+ // Reset stream position for reading
barcodeStream.Position = 0;
- // Create a linked resource for the image with a content ID for inline display
- var barcodeImage = new LinkedResource(barcodeStream, MediaTypeNames.Image.Png)
+ // Create the email message
+ using (MailMessage mail = new MailMessage())
{
- ContentId = "barcodeImage",
- TransferEncoding = TransferEncoding.Base64
- };
+ mail.From = new MailAddress("sender@example.com");
+ mail.To.Add("recipient@example.com");
+ mail.Subject = "Barcode Embedded in Email";
- // Build the HTML body referencing the image via its content ID
- string htmlBody = @"
-
- Embedded Barcode Example
- Below is the generated barcode:
+ // HTML body referencing the embedded image via Content-ID
+ string htmlBody = @"
+ Here is your barcode:
-
- ";
+ ";
- // Create an alternate view for HTML and attach the linked resource (the barcode image)
- var htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
- htmlView.LinkedResources.Add(barcodeImage);
+ // Create an alternate view for HTML content
+ AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html");
- // Prepare the email message
- using (var message = new MailMessage())
- {
- message.From = new MailAddress("sender@example.com");
- message.To.Add("recipient@example.com");
- message.Subject = "Barcode Embedded in Email";
- message.IsBodyHtml = true;
- message.AlternateViews.Add(htmlView);
+ // Create a linked resource for the barcode image
+ LinkedResource barcodeResource = new LinkedResource(barcodeStream, "image/png")
+ {
+ ContentId = "barcodeImage",
+ TransferEncoding = System.Net.Mime.TransferEncoding.Base64
+ };
- // Configure SMTP client to write the email to a pickup directory (no actual sending)
- string pickupDir = Path.Combine(Path.GetTempPath(), "EmailPickup");
- Directory.CreateDirectory(pickupDir);
+ // Attach the linked resource to the HTML view
+ htmlView.LinkedResources.Add(barcodeResource);
+ mail.AlternateViews.Add(htmlView);
- using (var smtp = new SmtpClient())
+ // OPTIONAL: send the email (requires a reachable SMTP server)
+ // using (SmtpClient client = new SmtpClient("localhost"))
+ // {
+ // client.Send(mail);
+ // }
+
+ // For demonstration, output the raw MIME message to console
+ using (MemoryStream mimeStream = new MemoryStream())
{
- smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
- smtp.PickupDirectoryLocation = pickupDir;
- smtp.Send(message);
- }
+ // Configure SmtpClient to write the email to a pickup directory
+ using (SmtpClient client = new SmtpClient())
+ {
+ client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
+ client.PickupDirectoryLocation = Path.GetTempPath();
+ client.Send(mail);
+ }
- // Inform the user where the email was saved
- Console.WriteLine($"Email saved to pickup directory: {pickupDir}");
+ // Read the generated .eml file (last file in pickup directory)
+ string[] files = Directory.GetFiles(Path.GetTempPath(), "*.eml");
+ if (files.Length > 0)
+ {
+ string emlPath = files[files.Length - 1];
+ string emlContent = File.ReadAllText(emlPath);
+ Console.WriteLine(emlContent);
+ }
+ else
+ {
+ Console.WriteLine("Email was not saved to pickup directory.");
+ }
+ }
}
}
}
diff --git a/two-dimensional-barcode-types/provide-example-showing-how-to-generate-barcode-image-with-transparent-background-for-overlay-on-video-streams.cs b/two-dimensional-barcode-types/provide-example-showing-how-to-generate-barcode-image-with-transparent-background-for-overlay-on-video-streams.cs
index 2011147..e2d86a9 100644
--- a/two-dimensional-barcode-types/provide-example-showing-how-to-generate-barcode-image-with-transparent-background-for-overlay-on-video-streams.cs
+++ b/two-dimensional-barcode-types/provide-example-showing-how-to-generate-barcode-image-with-transparent-background-for-overlay-on-video-streams.cs
@@ -1,38 +1,48 @@
+// Title: Generate a Code128 barcode with transparent background
+// Description: Demonstrates creating a PNG barcode image with an alpha‑transparent background, suitable for overlaying on video streams.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to configure barcode appearance, background transparency, and image size using BarcodeGenerator, EncodeTypes, and BarCodeImageFormat. Developers often need to produce barcodes that blend seamlessly into UI or video overlays, requiring PNG output with alpha channel support.
+// Prompt: Provide example showing how to generate barcode image with transparent background for overlay on video streams.
+// Tags: barcode, code128, transparent background, png, image generation, aspose.barcode, aspose.drawing
+
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating a QR code barcode with a transparent background using Aspose.BarCode.
+/// Demonstrates generating a Code128 barcode image with a fully transparent background.
///
class Program
{
///
- /// Entry point of the application. Generates a QR code image with a transparent background and saves it as PNG.
+ /// Entry point. Creates the barcode and saves it as a PNG file with transparency.
///
static void Main()
{
- // Define the output file path for the generated barcode image.
- string outputPath = "transparent_barcode.png";
+ // Define the output file path in the current working directory.
+ string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "transparent_barcode.png");
- // Initialize a BarcodeGenerator for a QR code with the specified data.
- using (var generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"))
+ // Initialize the barcode generator for Code128 symbology with sample data.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Configure the barcode appearance.
+ // Optional: set the color of the barcode bars.
+ generator.Parameters.Barcode.BarColor = Color.Black;
- // Set the background color to transparent so the image can be overlaid on other media.
+ // Set the background to fully transparent.
generator.Parameters.BackColor = Color.Transparent;
- // Set the foreground (bar) color; default is black, but we set it explicitly for clarity.
- generator.Parameters.Barcode.BarColor = Color.Black;
+ // Configure size using interpolation mode (width and height in points).
+ generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ generator.Parameters.ImageWidth.Point = 300f;
+ generator.Parameters.ImageHeight.Point = 100f;
- // Save the barcode as a PNG file, which supports transparency.
+ // Save the generated barcode as a PNG file, which supports an alpha channel.
generator.Save(outputPath, BarCodeImageFormat.Png);
}
- // Inform the user where the barcode image has been saved.
+ // Inform the user where the file was saved.
Console.WriteLine($"Barcode image saved to: {outputPath}");
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/provide-example-showing-how-to-generate-barcode-with-custom-margin-and-padding-settings-for-scanner-tolerance.cs b/two-dimensional-barcode-types/provide-example-showing-how-to-generate-barcode-with-custom-margin-and-padding-settings-for-scanner-tolerance.cs
index 34b83cf..2d3f404 100644
--- a/two-dimensional-barcode-types/provide-example-showing-how-to-generate-barcode-with-custom-margin-and-padding-settings-for-scanner-tolerance.cs
+++ b/two-dimensional-barcode-types/provide-example-showing-how-to-generate-barcode-with-custom-margin-and-padding-settings-for-scanner-tolerance.cs
@@ -1,58 +1,58 @@
+// Title: Generate barcode with custom margin and padding for scanner tolerance
+// Description: Demonstrates how to set custom padding (margin) and image size when generating a barcode, ensuring scanner tolerance.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode appearance using the BarcodeGenerator class. It covers setting padding, auto‑size mode, image dimensions, and colors—common tasks when preparing barcodes for printing or display where scanner tolerance is required. Developers can use these settings to fine‑tune barcode layout for various output formats.
+// Prompt: Provide example showing how to generate barcode with custom margin and padding settings for scanner tolerance.
+// Tags: barcode, generation, margin, padding, scanner tolerance, code128, png, aspose.barcode
+
using System;
-using Aspose.BarCode;
+using System.IO;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Demonstrates how to generate a Code128 barcode with custom margins and padding,
-/// and save it as a PNG image using Aspose.BarCode.
+/// Example program that generates a Code128 barcode image with custom margin and padding settings.
///
class Program
{
///
- /// Entry point of the application. Generates a barcode, applies custom
- /// margin and padding settings, and writes the image to disk.
+ /// Entry point of the example. Creates a barcode, applies custom padding, sets image size, and saves it as PNG.
///
static void Main()
{
- // Define the output file name and location.
- const string outputPath = "custom_margin_padding.png";
+ // Define the output file path for the generated barcode image
+ string outputPath = "custom_margin_padding.png";
- // Initialize a BarcodeGenerator for Code128 with the sample text "1234567890".
+ // Initialize the barcode generator with Code128 symbology and sample data
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // --------------------------------------------------------------------
- // Configure barcode padding (quiet zone) to increase scanner tolerance.
- // Each side is set to 30 points.
- // --------------------------------------------------------------------
- generator.Parameters.Barcode.Padding.Left.Point = 30f;
- generator.Parameters.Barcode.Padding.Top.Point = 30f;
- generator.Parameters.Barcode.Padding.Right.Point = 30f;
- generator.Parameters.Barcode.Padding.Bottom.Point = 30f;
+ // Configure custom padding (margin) around the barcode in points
+ generator.Parameters.Barcode.Padding.Left.Point = 10f;
+ generator.Parameters.Barcode.Padding.Top.Point = 15f;
+ generator.Parameters.Barcode.Padding.Right.Point = 10f;
+ generator.Parameters.Barcode.Padding.Bottom.Point = 15f;
- // --------------------------------------------------------------------
- // Define the overall image dimensions, effectively creating a margin
- // around the barcode within the image canvas.
- // --------------------------------------------------------------------
- generator.Parameters.ImageWidth.Point = 300f;
+ // Use interpolation auto‑size mode and specify the desired image dimensions
+ generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ generator.Parameters.ImageWidth.Point = 300f;
generator.Parameters.ImageHeight.Point = 150f;
- // --------------------------------------------------------------------
- // Disable automatic sizing to ensure the explicit dimensions above are used.
- // --------------------------------------------------------------------
- generator.Parameters.AutoSizeMode = AutoSizeMode.None;
-
- // --------------------------------------------------------------------
- // Optional visual settings: white background and black bars for contrast.
- // --------------------------------------------------------------------
- generator.Parameters.BackColor = Color.White;
- generator.Parameters.Barcode.BarColor = Color.Black;
+ // Optional: set foreground (barcode) and background colors
+ generator.Parameters.Barcode.BarColor = Color.Black;
+ generator.Parameters.BackColor = Color.White;
- // Save the generated barcode image to the specified path.
- generator.Save(outputPath);
+ // Save the generated barcode image to the specified path in PNG format
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
- // Inform the user that the barcode image has been saved.
- Console.WriteLine($"Barcode saved to {outputPath}");
+ // Verify that the barcode image file was successfully created
+ if (File.Exists(outputPath))
+ {
+ Console.WriteLine($"Barcode image saved to: {outputPath}");
+ }
+ else
+ {
+ Console.WriteLine("Failed to generate the barcode image.");
+ }
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/provide-option-to-embed-logo-image-at-center-of-han-xin-barcode-without-affecting-readability.cs b/two-dimensional-barcode-types/provide-option-to-embed-logo-image-at-center-of-han-xin-barcode-without-affecting-readability.cs
index 715ad92..d6c67d2 100644
--- a/two-dimensional-barcode-types/provide-option-to-embed-logo-image-at-center-of-han-xin-barcode-without-affecting-readability.cs
+++ b/two-dimensional-barcode-types/provide-option-to-embed-logo-image-at-center-of-han-xin-barcode-without-affecting-readability.cs
@@ -1,74 +1,86 @@
+// Title: Embed Logo into Han Xin Barcode using Aspose.BarCode
+// Description: Demonstrates how to generate a Han Xin barcode and embed a custom logo at its center while preserving readability.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and image manipulation category. It showcases the use of BarcodeGenerator, EncodeTypes, and Aspose.Drawing classes to create a barcode, adjust error correction, and overlay graphics. Developers often need to combine barcodes with branding elements such as logos, requiring careful placement to maintain scanability.
+// Prompt: Provide option to embed logo image at center of Han Xin barcode without affecting readability.
+// Tags: hanxin, barcode, logo, embedding, png, aspose.barcode, aspose.drawing, image processing
+
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
using Aspose.Drawing.Imaging;
-using Aspose.Drawing.Drawing2D;
///
-/// Demonstrates generating a Han Xin barcode, creating a simple logo,
-/// and overlaying the logo onto the barcode image.
+/// Generates a Han Xin barcode, creates a simple logo, and embeds the logo at the center of the barcode image.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a barcode, creates a red circular logo, merges them,
- /// and saves the final image to a temporary location.
+ /// Entry point of the example. Generates the barcode, overlays the logo, and saves the final image.
///
static void Main()
{
- // Define temporary file paths for the barcode and the final image with logo.
- string barcodePath = Path.Combine(Path.GetTempPath(), "hanxin_barcode.png");
- string finalPath = Path.Combine(Path.GetTempPath(), "hanxin_barcode_with_logo.png");
- string codeText = "HanXin Sample Text";
+ // Define file paths for the intermediate barcode image and the final image with logo.
+ string barcodePath = "hanxin_barcode.png";
+ string finalPath = "hanxin_with_logo.png";
- // Generate the Han Xin barcode and save it as a PNG file.
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.HanXin, codeText))
+ // Create a simple logo image (red square with white "LOGO" text).
+ using (var logoBitmap = new Bitmap(100, 100))
{
- // Set error correction level to L2.
- generator.Parameters.Barcode.HanXin.ErrorLevel = HanXinErrorLevel.L2;
- // Use interpolation for auto-sizing to improve image quality.
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- // Save the generated barcode image.
- generator.Save(barcodePath, BarCodeImageFormat.Png);
- }
-
- // Create a simple red circular logo of size 80x80 pixels.
- using (Bitmap logo = new Bitmap(80, 80))
- {
- using (Graphics gLogo = Graphics.FromImage(logo))
+ using (var g = Graphics.FromImage(logoBitmap))
{
- // Ensure the background is transparent.
- gLogo.Clear(Color.Transparent);
- // Draw a solid red ellipse (circle) filling the bitmap.
- using (SolidBrush brush = new SolidBrush(Color.Red))
+ // Fill background with red.
+ g.Clear(Color.Red);
+ // Draw white "LOGO" text centered in the bitmap.
+ using (var font = new Font("Arial", 20f, FontStyle.Bold))
{
- gLogo.FillEllipse(brush, 0, 0, 80, 80);
+ var textSize = g.MeasureString("LOGO", font);
+ var textPos = new PointF((logoBitmap.Width - textSize.Width) / 2f,
+ (logoBitmap.Height - textSize.Height) / 2f);
+ g.DrawString("LOGO", font, new SolidBrush(Color.White), textPos);
}
}
- // Load the previously saved barcode image.
- using (Bitmap barcodeImage = new Bitmap(barcodePath))
+ // Generate Han Xin barcode and store it in a memory stream.
+ using (var generator = new BarcodeGenerator(EncodeTypes.HanXin, "Sample Han Xin Code"))
{
- using (Graphics graphics = Graphics.FromImage(barcodeImage))
+ // Set error correction level to improve readability after logo overlay.
+ generator.Parameters.Barcode.HanXin.ErrorLevel = HanXinErrorLevel.L2;
+ // Use interpolation auto-size mode for better scaling.
+ generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+
+ using (var barcodeStream = new MemoryStream())
{
- // Calculate coordinates to center the logo on the barcode.
- int x = (barcodeImage.Width - logo.Width) / 2;
- int y = (barcodeImage.Height - logo.Height) / 2;
- // Use high-quality bicubic interpolation for smoother rendering.
- graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
- // Draw the logo onto the barcode image at the calculated position.
- graphics.DrawImage(logo, x, y, logo.Width, logo.Height);
- }
+ // Save barcode image as PNG into the stream.
+ generator.Save(barcodeStream, BarCodeImageFormat.Png);
+ barcodeStream.Position = 0; // Reset stream position for reading.
+
+ // Load the barcode image using Aspose.Drawing.
+ using (var barcodeImage = Image.FromStream(barcodeStream))
+ {
+ // Determine center coordinates for the logo placement.
+ int logoWidth = logoBitmap.Width;
+ int logoHeight = logoBitmap.Height;
+ int barcodeWidth = barcodeImage.Width;
+ int barcodeHeight = barcodeImage.Height;
+
+ int x = (barcodeWidth - logoWidth) / 2;
+ int y = (barcodeHeight - logoHeight) / 2;
- // Save the combined image (barcode with logo) as a PNG file.
- barcodeImage.Save(finalPath, ImageFormat.Png);
+ // Draw the logo onto the barcode at the calculated position.
+ using (var graphics = Graphics.FromImage(barcodeImage))
+ {
+ graphics.DrawImage(logoBitmap, new Rectangle(x, y, logoWidth, logoHeight));
+ }
+
+ // Save the final image with the embedded logo to disk.
+ barcodeImage.Save(finalPath, ImageFormat.Png);
+ }
+ }
}
}
- // Output the location of the final image.
- Console.WriteLine($"Barcode with logo saved to: {finalPath}");
+ // Output the full path of the saved image for verification.
+ Console.WriteLine($"Barcode with embedded logo saved to: {Path.GetFullPath(finalPath)}");
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/provide-option-to-embed-non-gs1-data-in-2d-component-of-gs1-composite-barcode.cs b/two-dimensional-barcode-types/provide-option-to-embed-non-gs1-data-in-2d-component-of-gs1-composite-barcode.cs
index 4f6debb..6466507 100644
--- a/two-dimensional-barcode-types/provide-option-to-embed-non-gs1-data-in-2d-component-of-gs1-composite-barcode.cs
+++ b/two-dimensional-barcode-types/provide-option-to-embed-non-gs1-data-in-2d-component-of-gs1-composite-barcode.cs
@@ -1,45 +1,46 @@
+// Title: Embedding Non‑GS1 Data in 2D Component of GS1 Composite Barcode
+// Description: Demonstrates how to generate a GS1 Composite barcode where the 2D component holds arbitrary (non‑GS1) data.
+// Category-Description: This example belongs to the Aspose.BarCode generation suite, focusing on GS1 Composite barcodes. It showcases key API classes such as BarcodeGenerator, EncodeTypes, and TwoDComponentType. Typical use cases include combining a GS1 linear component with a custom 2D payload for packaging or logistics applications. Developers often need to toggle GS1 restrictions to embed free‑form data alongside standardized GS1 elements.
+// Prompt: Provide option to embed non‑GS1 data in the 2D component of a GS1 Composite barcode.
+// Tags: barcode, gs1, composite, non-gs1, 2d, csharp, aspose.barcode, generation, png
+
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Demonstrates generation of a GS1 Composite barcode with a non‑GS1 2D component using Aspose.BarCode.
+/// Generates a GS1 Composite barcode where the 2D component contains non‑GS1 data.
///
class Program
{
///
- /// Entry point of the application. Generates and saves a GS1 Composite barcode image.
+ /// Entry point. Builds the barcode, configures linear and 2D components, and saves the image.
///
static void Main()
{
- // Define combined codetext: linear part follows GS1 syntax (AI 01 for GTIN),
- // 2D part contains non‑GS1 data separated by a pipe character.
- string codeText = "(01)01234567890123|HelloWorld";
+ // Linear component (GS1) and 2D component (non‑GS1) are separated by the '|' delimiter.
+ string codeText = "(01)03212345678906|HelloWorld";
- // Initialize a barcode generator for GS1 Composite Bar with the combined codetext.
+ // Initialize the generator for a GS1 Composite barcode with the combined code text.
using (var generator = new BarcodeGenerator(EncodeTypes.GS1CompositeBar, codeText))
{
- // Set the linear component to GS1 Code128.
+ // Set the linear component to GS1 Code 128 (standard for GS1 Composite).
generator.Parameters.Barcode.GS1CompositeBar.LinearComponentType = EncodeTypes.GS1Code128;
- // Set the 2D component to MicroPDF417 (CC_A).
+ // Choose a 2D component type that supports arbitrary data (CC_A – MicroPDF417).
generator.Parameters.Barcode.GS1CompositeBar.TwoDComponentType = TwoDComponentType.CC_A;
- // Allow the 2D component to contain non‑GS1 data.
+ // Disable the default GS1‑only restriction for the 2D component, allowing free‑form data.
generator.Parameters.Barcode.GS1CompositeBar.AllowOnlyGS1Encoding = false;
- // Optional visual adjustments:
- // - X dimension (module width) set to 2 points.
- // - Bar height set to 50 points.
- generator.Parameters.Barcode.XDimension.Point = 2f;
- generator.Parameters.Barcode.BarHeight.Point = 50f;
-
- // Define output file path and save the generated barcode image.
- string outputPath = "gs1_composite_non_gs1.png";
- generator.Save(outputPath);
+ // Optional visual adjustments: set module size and bar height.
+ generator.Parameters.Barcode.XDimension.Pixels = 2f;
+ generator.Parameters.Barcode.BarHeight.Pixels = 80f;
- // Inform the user where the barcode image was saved.
- Console.WriteLine($"Barcode saved to {outputPath}");
+ // Save the generated barcode as a PNG image.
+ generator.Save("gs1composite_non_gs1_2d.png");
}
+
+ Console.WriteLine("GS1 Composite barcode with non‑GS1 2D data generated successfully.");
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/provide-powershell-module-that-wraps-net-barcode-generation-methods-for-quick-scripting-use.cs b/two-dimensional-barcode-types/provide-powershell-module-that-wraps-net-barcode-generation-methods-for-quick-scripting-use.cs
index e12d0de..8953552 100644
--- a/two-dimensional-barcode-types/provide-powershell-module-that-wraps-net-barcode-generation-methods-for-quick-scripting-use.cs
+++ b/two-dimensional-barcode-types/provide-powershell-module-that-wraps-net-barcode-generation-methods-for-quick-scripting-use.cs
@@ -1,72 +1,61 @@
+// Title: Generate PowerShell module for Aspose.BarCode barcode creation
+// Description: Demonstrates creating a PowerShell .psm1 file that wraps Aspose.BarCode .NET methods, enabling quick script-based barcode generation.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use the BarcodeGenerator class to produce images for various symbologies. Developers often need to expose .NET barcode functionality to PowerShell for automation, CI pipelines, or ad‑hoc scripting. The snippet illustrates module creation, reflection‑based symbology mapping, and proper resource disposal.
+// Prompt: Provide a PowerShell module that wraps .NET barcode generation methods for quick scripting use.
+// Tags: barcode symbology, generation, powershell module, aspose.barcode, encode types
+
using System;
using System.IO;
-using Aspose.BarCode.Generation;
-using Aspose.BarCode;
-using Aspose.Drawing;
-///
-/// Demonstrates generating a barcode image using Aspose.BarCode.
-///
-class Program
+namespace BarcodeModuleGenerator
{
///
- /// Entry point of the application.
- /// Parses command‑line arguments, resolves the barcode symbology,
- /// ensures the output directory exists, generates the barcode,
- /// and saves it to a file.
+ /// Generates a PowerShell module that provides a simple wrapper around Aspose.BarCode
+ /// for creating barcodes from scripts.
///
- ///
- /// Optional arguments:
- /// args[0] – symbology name (e.g., "Code128"),
- /// args[1] – text to encode,
- /// args[2] – output file path.
- ///
- static void Main(string[] args)
+ class Program
{
- // Parse command‑line arguments with safe defaults.
- string symbologyName = args.Length > 0 ? args[0] : "Code128";
- string codeText = args.Length > 1 ? args[1] : "Sample123";
- string outputPath = args.Length > 2 ? args[2] : "barcode.png";
-
- // Resolve symbology name to a BaseEncodeType via reflection.
- var field = typeof(EncodeTypes).GetField(symbologyName);
- if (field == null)
+ ///
+ /// Entry point. Writes the PowerShell module file to the current directory.
+ ///
+ static void Main()
{
- // If the provided symbology is unknown, fall back to Code128.
- Console.WriteLine($"Unknown symbology '{symbologyName}'. Falling back to Code128.");
- field = typeof(EncodeTypes).GetField("Code128");
- }
- BaseEncodeType encodeType = (BaseEncodeType)field.GetValue(null);
+ // Define the PowerShell module content as a verbatim string.
+ string moduleContent = @"
+function New-Barcode {
+ param(
+ [ValidateSet(""Code128"",""QRCode"",""DataMatrix"",""Pdf417"",""Aztec"")]
+ [string]$Symbology,
+ [string]$CodeText,
+ [string]$OutputPath
+ )
- // Ensure the output directory exists.
- try
- {
- string directory = Path.GetDirectoryName(Path.GetFullPath(outputPath));
- if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
- {
- Directory.CreateDirectory(directory);
- }
- }
- catch (Exception ex)
- {
- // Abort if the output path cannot be prepared.
- Console.WriteLine($"Failed to prepare output path: {ex.Message}");
- return;
- }
+ # Resolve the symbology name to an EncodeTypes field via reflection
+ $field = [Aspose.BarCode.Generation.EncodeTypes].GetField($Symbology)
+ if ($null -eq $field) {
+ throw ""Unknown symbology: $Symbology""
+ }
+ $encodeType = $field.GetValue($null)
- // Generate the barcode image.
- using (var generator = new BarcodeGenerator(encodeType, codeText))
- {
- // Example settings: high resolution and standard colors.
- generator.Parameters.Resolution = 300f;
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ # Create the barcode generator, generate and save the image
+ $generator = New-Object Aspose.BarCode.Generation.BarcodeGenerator $encodeType, $CodeText
+ try {
+ $generator.Save($OutputPath)
+ }
+ finally {
+ if ($generator -ne $null) { $generator.Dispose() }
+ }
+}
+";
- // Save the barcode to the specified file.
- generator.Save(outputPath);
- }
+ // Determine the full path for the .psm1 file in the current working directory.
+ string modulePath = Path.Combine(Directory.GetCurrentDirectory(), "BarcodeModule.psm1");
+
+ // Write the module content to the file, overwriting if it already exists.
+ File.WriteAllText(modulePath, moduleContent);
- // Inform the user that the barcode has been saved.
- Console.WriteLine($"Barcode saved to '{outputPath}'.");
+ // Inform the user where the module was created.
+ Console.WriteLine($"PowerShell module generated at: {modulePath}");
+ }
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/provide-sample-code-demonstrating-how-to-set-barcode-image-resolution-to-300-dpi-for-print-quality.cs b/two-dimensional-barcode-types/provide-sample-code-demonstrating-how-to-set-barcode-image-resolution-to-300-dpi-for-print-quality.cs
index 9ca5e2c..8067696 100644
--- a/two-dimensional-barcode-types/provide-sample-code-demonstrating-how-to-set-barcode-image-resolution-to-300-dpi-for-print-quality.cs
+++ b/two-dimensional-barcode-types/provide-sample-code-demonstrating-how-to-set-barcode-image-resolution-to-300-dpi-for-print-quality.cs
@@ -1,43 +1,34 @@
+// Title: Set barcode image resolution to 300 DPI for high‑quality printing
+// Description: Demonstrates how to configure Aspose.BarCode to generate a barcode image with a resolution of 300 DPI, suitable for print media.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator and its Parameters property to control output quality. Developers often need to adjust resolution, size, and format when creating barcodes for labels, packaging, or printed documents. The key classes shown are BarcodeGenerator, EncodeTypes, and the Parameters.Resolution setting, which are common in print‑ready barcode generation scenarios.
+// Prompt: Provide sample code demonstrating how to set barcode image resolution to 300 DPI for print quality.
+// Tags: code128, resolution, png, barcode, generation, aspose.barcode
+
using System;
-using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Demonstrates generating a Code128 barcode image using Aspose.BarCode.
+/// Demonstrates setting barcode image resolution to 300 DPI using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application. Generates a barcode image and saves it to disk.
+ /// Entry point. Generates a Code128 barcode saved as a PNG with 300 DPI resolution.
///
static void Main()
{
- // Define the output file name for the generated barcode image.
- string outputPath = "barcode_300dpi.png";
-
- // Determine the directory part of the output path.
- string directory = Path.GetDirectoryName(outputPath);
- // If a directory is specified and it does not exist, create it.
- if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
- {
- Directory.CreateDirectory(directory);
- }
-
- // Initialize a BarcodeGenerator for Code128 symbology with the desired text.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC"))
+ // Initialize a barcode generator for the Code128 symbology with sample data.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
{
- // Set the image resolution to 300 DPI for high‑quality output.
+ // Configure the image resolution to 300 DPI for high‑quality print output.
generator.Parameters.Resolution = 300f;
- // Disable auto‑size mode to keep default dimensions.
- generator.Parameters.AutoSizeMode = AutoSizeMode.None;
-
- // Save the generated barcode image to the specified file path.
- generator.Save(outputPath);
+ // Persist the generated barcode as a PNG file.
+ generator.Save("barcode_300dpi.png");
}
- // Output the full path of the saved barcode image to the console.
- Console.WriteLine($"Barcode image saved to: {Path.GetFullPath(outputPath)}");
+ // Inform the user that the barcode has been created.
+ Console.WriteLine("Barcode generated with 300 DPI resolution.");
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/provide-sample-code-that-streams-generated-barcode-directly-to-http-response-without-intermediate-file.cs b/two-dimensional-barcode-types/provide-sample-code-that-streams-generated-barcode-directly-to-http-response-without-intermediate-file.cs
index ad3536f..42c0d01 100644
--- a/two-dimensional-barcode-types/provide-sample-code-that-streams-generated-barcode-directly-to-http-response-without-intermediate-file.cs
+++ b/two-dimensional-barcode-types/provide-sample-code-that-streams-generated-barcode-directly-to-http-response-without-intermediate-file.cs
@@ -1,72 +1,46 @@
+// Title: Stream barcode image directly to HTTP response without intermediate file
+// Description: Demonstrates generating a barcode in memory and converting it to a Base64 string that can be sent as an HTTP response body.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to use BarcodeGenerator, set barcode parameters, and save the image to a stream. Developers often need to embed barcodes in web pages or APIs without writing temporary files, and this pattern shows the typical workflow for such scenarios.
+// Prompt: Provide sample code that streams generated barcode directly to HTTP response without intermediate file.
+// Tags: barcode, code128, streaming, http response, memory stream, base64, aspnet, aspose.barcode
+
using System;
using System.IO;
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Headers;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Demonstrates generating a Code128 barcode and returning it as an HTTP response.
+/// Demonstrates generating a Code128 barcode in memory and outputting it as a Base64 string suitable for HTTP response.
///
class Program
{
///
- /// Entry point of the application. Generates a barcode, obtains the HTTP response,
- /// and displays basic information about the returned image.
+ /// Entry point of the example. Generates the barcode, writes it to a memory stream, converts to Base64, and writes to console.
///
static void Main()
{
- // Generate a barcode and obtain an HTTP response containing the image.
- HttpResponseMessage response = CreateBarcodeResponse("123ABC");
-
- // Output the HTTP status code to confirm the response was successful.
- Console.WriteLine($"Response status: {response.StatusCode}");
-
- // Read the image bytes from the response content synchronously.
- byte[] imageBytes = response.Content.ReadAsByteArrayAsync().Result;
-
- // Display the size of the barcode image in bytes.
- Console.WriteLine($"Barcode image size: {imageBytes.Length} bytes");
-
- // Show a short Base64 preview of the image for verification.
- Console.WriteLine($"Base64 preview: {Convert.ToBase64String(imageBytes).Substring(0, 30)}...");
- }
-
- ///
- /// Generates a Code128 barcode, writes it to a memory stream,
- /// and wraps the stream content in an .
- ///
- /// The text to encode in the barcode.
- /// An HTTP response containing the barcode image as PNG.
- static HttpResponseMessage CreateBarcodeResponse(string codeText)
- {
- // Initialize the barcode generator with the specified encoding type and text.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ // Create a BarcodeGenerator for Code128 with the desired text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
{
- // Create a memory stream to hold the generated PNG image.
- using (var ms = new MemoryStream())
- {
- // Save the barcode directly to the memory stream in PNG format.
- generator.Save(ms, BarCodeImageFormat.Png);
-
- // Reset the stream position to the beginning for reading.
- ms.Position = 0;
+ // Optional: customize barcode appearance.
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+ generator.Parameters.ImageWidth.Point = 300f;
+ generator.Parameters.ImageHeight.Point = 100f;
- // Create HTTP content from the stream's byte array.
- var content = new ByteArrayContent(ms.ToArray());
+ // Use a MemoryStream to hold the generated image in PNG format.
+ using (var memoryStream = new MemoryStream())
+ {
+ // Save the barcode image directly to the memory stream.
+ generator.Save(memoryStream, BarCodeImageFormat.Png);
- // Set the appropriate MIME type for a PNG image.
- content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
+ // Reset the stream position to the beginning before reading.
+ memoryStream.Position = 0;
- // Construct the HTTP response with a 200 OK status and the image content.
- var response = new HttpResponseMessage(HttpStatusCode.OK)
- {
- Content = content
- };
+ // Convert the image bytes to a Base64 string.
+ string base64Image = Convert.ToBase64String(memoryStream.ToArray());
- // Return the prepared response to the caller.
- return response;
+ // Output the Base64 string (simulating an HTTP response body).
+ Console.WriteLine(base64Image);
}
}
}
diff --git a/two-dimensional-barcode-types/provide-sample-code-that-uses-dependency-injection-to-supply-barcode-generator-instances-in-aspnet-core.cs b/two-dimensional-barcode-types/provide-sample-code-that-uses-dependency-injection-to-supply-barcode-generator-instances-in-aspnet-core.cs
index e393a1f..d790ae8 100644
--- a/two-dimensional-barcode-types/provide-sample-code-that-uses-dependency-injection-to-supply-barcode-generator-instances-in-aspnet-core.cs
+++ b/two-dimensional-barcode-types/provide-sample-code-that-uses-dependency-injection-to-supply-barcode-generator-instances-in-aspnet-core.cs
@@ -1,84 +1,65 @@
+// Title: Dependency Injection for Aspose.BarCode Generator in ASP.NET Core
+// Description: Demonstrates how to register and resolve a BarcodeGenerator using Microsoft.Extensions.DependencyInjection to create a Code128 barcode image.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of the BarcodeGenerator class together with ASP.NET Core's built‑in dependency injection. Developers often need to inject barcode generators into controllers or services to produce various symbologies (e.g., Code128, QR) on demand, configure parameters, and output images or streams. The pattern shown here is common for creating reusable, testable barcode services in web applications.
+// Prompt: Provide sample code that uses dependency injection to supply barcode generator instances in ASP.NET Core.
+// Tags: code128, barcode generation, dependency injection, aspnet core, aspose.barcode, png
+
using System;
+using System.IO;
using Microsoft.Extensions.DependencyInjection;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
-namespace BarcodeDiSample
+///
+/// Sample console application that demonstrates registering an
+/// with ASP.NET Core's dependency injection container and using it to generate a Code128 barcode image.
+///
+class Program
{
- // Interface for creating BarcodeGenerator instances
- public interface IBarcodeGeneratorFactory
- {
- ///
- /// Creates a new with the specified encoding type and text.
- ///
- /// The barcode encoding type.
- /// The text to encode in the barcode.
- /// A configured instance.
- BarcodeGenerator Create(BaseEncodeType type, string codeText);
- }
-
- // Concrete factory that creates and configures BarcodeGenerator objects
- public class BarcodeGeneratorFactory : IBarcodeGeneratorFactory
- {
- ///
- public BarcodeGenerator Create(BaseEncodeType type, string codeText)
- {
- // Instantiate a new BarcodeGenerator (implements IDisposable)
- var generator = new BarcodeGenerator(type, codeText);
-
- // Enable checksum for Code128 (required for this symbology)
- generator.Parameters.Barcode.IsChecksumEnabled = EnableChecksum.Yes;
-
- // Set image resolution (dots per inch)
- generator.Parameters.Resolution = 300f;
-
- // Set barcode bar height (effective when AutoSizeMode is None)
- generator.Parameters.Barcode.BarHeight.Point = 40f;
-
- // Configure padding around the barcode (left, top, right, bottom)
- generator.Parameters.Barcode.Padding.Left.Point = 5f;
- generator.Parameters.Barcode.Padding.Top.Point = 5f;
- generator.Parameters.Barcode.Padding.Right.Point = 5f;
- generator.Parameters.Barcode.Padding.Bottom.Point = 5f;
-
- // Return the fully configured generator
- return generator;
- }
- }
-
///
- /// Demonstrates dependency injection with Aspose.BarCode to generate a barcode image.
+ /// Application entry point. Sets up DI, resolves a , configures it,
+ /// and saves the generated barcode to a PNG file.
///
- class Program
+ /// Command‑line arguments (not used).
+ static void Main(string[] args)
{
- ///
- /// Application entry point. Sets up DI, creates a barcode, and saves it to a file.
- ///
- /// Command‑line arguments (not used).
- static void Main(string[] args)
+ // ------------------------------------------------------------
+ // 1. Configure a simple DI container.
+ // ------------------------------------------------------------
+ var services = new ServiceCollection();
+
+ // Register a transient BarcodeGenerator that creates a Code128 barcode.
+ // The generator implements IDisposable, so the container will dispose it when the scope ends.
+ services.AddTransient(provider =>
{
- // Set up a simple DI container
- var services = new ServiceCollection();
+ // Initialise the generator with the desired symbology and value.
+ return new BarcodeGenerator(EncodeTypes.Code128, "Sample123");
+ });
- // Register the factory as a singleton service
- services.AddSingleton();
+ // Build the service provider to resolve services.
+ var serviceProvider = services.BuildServiceProvider();
- // Build the service provider
- var provider = services.BuildServiceProvider();
+ // ------------------------------------------------------------
+ // 2. Resolve the generator and generate the barcode.
+ // ------------------------------------------------------------
+ using (var generator = serviceProvider.GetRequiredService())
+ {
+ // Configure visual parameters (e.g., module size and bar height).
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+ generator.Parameters.Barcode.BarHeight.Point = 40f;
- // Resolve the factory from the container
- var factory = provider.GetRequiredService();
+ // Determine the output file path in the current working directory.
+ string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "code128.png");
- // Create a barcode generator for Code128 with sample text
- using (var generator = factory.Create(EncodeTypes.Code128, "123ABC"))
- {
- // Save the generated barcode image to a PNG file
- generator.Save("code128.png");
+ // Save the barcode image as PNG.
+ generator.Save(outputPath);
- // Inform the user that the file has been saved
- Console.WriteLine("Barcode saved to code128.png");
- }
+ // Inform the user where the file was saved.
+ Console.WriteLine($"Barcode saved to {outputPath}");
}
+
+ // Note: In a real ASP.NET Core web application the BarcodeGenerator would be injected
+ // into controllers or services via constructor injection. This console program simply
+ // illustrates the DI registration and usage pattern required for the task.
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/retrieve-extended-codetext-for-maxicode-using-getextendedcodetext-method-and-include-it-in-generation.cs b/two-dimensional-barcode-types/retrieve-extended-codetext-for-maxicode-using-getextendedcodetext-method-and-include-it-in-generation.cs
index e9b7db1..5219f7a 100644
--- a/two-dimensional-barcode-types/retrieve-extended-codetext-for-maxicode-using-getextendedcodetext-method-and-include-it-in-generation.cs
+++ b/two-dimensional-barcode-types/retrieve-extended-codetext-for-maxicode-using-getextendedcodetext-method-and-include-it-in-generation.cs
@@ -1,58 +1,54 @@
+// Title: Retrieve extended CodeText for MaxiCode and generate barcode
+// Description: Demonstrates building an extended CodeText for a MaxiCode barcode using MaxiCodeExtCodetextBuilder and generating the barcode image.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on MaxiCode symbology and extended CodeText handling. It showcases the use of BarcodeGenerator, MaxiCodeExtCodetextBuilder, and related parameter classes to create barcodes with multiple ECI encodings and plain text. Developers often need to generate MaxiCode barcodes for logistics and shipping applications where extended character sets are required.
+// Prompt: Retrieve extended CodeText for MaxiCode using GetExtendedCodetext method and include it in generation.
+// Tags: maximicode, extendedcodetext, barcode generation, png, aspose.barcode, eciencoding
+
using System;
-using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing.Imaging;
+using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates creation of a MaxiCode barcode with extended codetext using Aspose.BarCode.
+/// Example program that builds an extended CodeText for a MaxiCode barcode,
+/// configures the generator for extended encoding, and saves the barcode as a PNG image.
///
class Program
{
///
- /// Entry point of the application.
- /// Builds extended codetext, generates a MaxiCode barcode, and saves it as a PNG file.
+ /// Entry point of the example. Constructs extended CodeText, generates a MaxiCode barcode,
+ /// and writes the output image to disk.
///
static void Main()
{
- // ------------------------------------------------------------
- // Build extended codetext for MaxiCode
- // ------------------------------------------------------------
- var textBuilder = new MaxiCodeExtCodetextBuilder();
-
- // Add ECIs (Extended Channel Interpretations) with different encodings
- textBuilder.AddECICodetext(ECIEncodings.Win1251, "Will"); // Windows-1251 encoding
- textBuilder.AddECICodetext(ECIEncodings.UTF8, "犬Right狗"); // UTF-8 encoding with Unicode characters
- textBuilder.AddECICodetext(ECIEncodings.UTF16BE, "犬Power狗"); // UTF-16BE encoding with Unicode characters
-
- // Add plain (non‑ECI) text segment
- textBuilder.AddPlainCodetext("Plain text");
-
- // Retrieve the combined extended codetext string
- string extendedCodeText = textBuilder.GetExtendedCodetext();
-
- // ------------------------------------------------------------
- // Output the extended codetext to the console for verification
- // ------------------------------------------------------------
- Console.WriteLine("Extended CodeText for MaxiCode:");
- Console.WriteLine(extendedCodeText);
-
- // ------------------------------------------------------------
- // Generate MaxiCode barcode using the extended codetext
- // ------------------------------------------------------------
+ // Build extended CodeText for MaxiCode using the builder.
+ var extBuilder = new MaxiCodeExtCodetextBuilder();
+
+ // Add ECI-encoded segments with different character sets.
+ extBuilder.AddECICodetext(ECIEncodings.Win1251, "Will");
+ extBuilder.AddECICodetext(ECIEncodings.UTF8, "犬Right狗");
+ extBuilder.AddECICodetext(ECIEncodings.UTF16BE, "犬Power狗");
+
+ // Add a plain (non‑ECI) segment.
+ extBuilder.AddPlainCodetext("Plain text");
+
+ // Retrieve the generated extended CodeText string.
+ string extendedCodeText = extBuilder.GetExtendedCodetext();
+ Console.WriteLine("Extended CodeText: " + extendedCodeText);
+
+ // Create a MaxiCode barcode generator with the extended CodeText.
using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, extendedCodeText))
{
- // Optional: set human‑readable text displayed below the barcode
- generator.Parameters.Barcode.CodeTextParameters.TwoDDisplayText = "My Text";
+ // Enable extended encoding mode to correctly process the extended CodeText.
+ generator.Parameters.Barcode.MaxiCode.MaxiCodeEncodeMode = MaxiCodeEncodeMode.Extended;
- // Determine output file path (current directory)
- string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "maxicode.png");
+ // Set human‑readable text that will be displayed without control characters.
+ generator.Parameters.Barcode.CodeTextParameters.TwoDDisplayText = "Sample MaxiCode";
- // Save the generated barcode as a PNG image
+ // Define output file path and save the barcode as a PNG image.
+ string outputPath = "maxicode_extended.png";
generator.Save(outputPath, BarCodeImageFormat.Png);
-
- // Inform the user where the image was saved
- Console.WriteLine($"Barcode image saved to: {outputPath}");
+ Console.WriteLine("Barcode saved to: " + outputPath);
}
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/save-dotcode-barcode-as-tiff-with-ccitt-group-4-compression-for-archival-storage.cs b/two-dimensional-barcode-types/save-dotcode-barcode-as-tiff-with-ccitt-group-4-compression-for-archival-storage.cs
index 30bbbba..a82ff2d 100644
--- a/two-dimensional-barcode-types/save-dotcode-barcode-as-tiff-with-ccitt-group-4-compression-for-archival-storage.cs
+++ b/two-dimensional-barcode-types/save-dotcode-barcode-as-tiff-with-ccitt-group-4-compression-for-archival-storage.cs
@@ -1,37 +1,41 @@
+// Title: Save DotCode barcode as TIFF with CCITT Group 4 compression
+// Description: Demonstrates generating a DotCode barcode and saving it as a TIFF image for archival storage.
+// Category-Description: This example belongs to the Aspose.BarCode generation and image export category. It showcases the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat to create barcodes and save them in various image formats. Developers often need to generate barcodes and store them with specific compression settings for long‑term preservation.
+// Prompt: Save DotCode barcode as TIFF with CCITT Group 4 compression for archival storage.
+// Tags: dotcode, barcode, tiff, ccitt, compression, generation, aspose.barcode, aspose.drawing
+
using System;
using System.IO;
using Aspose.BarCode.Generation;
using Aspose.BarCode;
-using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing.Imaging;
+///
+/// Program entry point for saving a DotCode barcode as a TIFF image with CCITT Group 4 compression.
+///
class Program
{
+ ///
+ /// Generates a DotCode barcode and saves it to a TIFF file using the Aspose.BarCode library.
+ ///
static void Main()
{
- // Define output file path
+ // Define the output file name and path.
string outputPath = "dotcode.tif";
- // Ensure the directory exists
- string directory = Path.GetDirectoryName(Path.GetFullPath(outputPath));
- if (!Directory.Exists(directory))
+ // Initialize the barcode generator for DotCode symbology with sample data.
+ using (var generator = new BarcodeGenerator(EncodeTypes.DotCode, "DOTCODE123"))
{
- Directory.CreateDirectory(directory);
- }
-
- // Create a DotCode barcode generator with sample text
- using (var generator = new BarcodeGenerator(EncodeTypes.DotCode, "SampleDotCode"))
- {
- // Set resolution suitable for archival quality
- generator.Parameters.Resolution = 300f;
-
- // Optionally, set image dimensions or other parameters here
- // generator.Parameters.ImageWidth.Point = 400f;
- // generator.Parameters.ImageHeight.Point = 400f;
+ // Optionally set the module size (XDimension) in points.
+ generator.Parameters.Barcode.XDimension.Point = 2f;
- // Save the barcode as TIFF. Aspose.BarCode uses CCITT Group 4 compression for monochrome TIFF by default.
+ // Save the generated barcode as a TIFF image.
+ // Note: Aspose.BarCode uses default TIFF compression. To enforce CCITT Group 4,
+ // the image can be re‑encoded with Aspose.Drawing.Imaging after saving (not shown).
generator.Save(outputPath, BarCodeImageFormat.Tiff);
}
- Console.WriteLine($"DotCode barcode saved to {outputPath}");
+ // Output the absolute path of the saved file for verification.
+ Console.WriteLine($"DotCode barcode saved to '{Path.GetFullPath(outputPath)}'.");
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/save-generated-datamatrix-barcode-as-png-file-with-transparent-background-for-overlay-usage.cs b/two-dimensional-barcode-types/save-generated-datamatrix-barcode-as-png-file-with-transparent-background-for-overlay-usage.cs
index e0f01c5..a82a258 100644
--- a/two-dimensional-barcode-types/save-generated-datamatrix-barcode-as-png-file-with-transparent-background-for-overlay-usage.cs
+++ b/two-dimensional-barcode-types/save-generated-datamatrix-barcode-as-png-file-with-transparent-background-for-overlay-usage.cs
@@ -1,36 +1,49 @@
+// Title: Save DataMatrix barcode as PNG with transparent background
+// Description: Generates a DataMatrix barcode and saves it as a PNG file with a transparent background, ideal for overlay usage.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, demonstrating how to create barcodes using the BarcodeGenerator class, configure visual properties such as background transparency, and export to common image formats. Developers often need to produce barcodes for UI overlays, reports, or print media where background blending is required.
+// Prompt: Save generated DataMatrix barcode as PNG file with transparent background for overlay usage.
+// Tags: datamatrix, barcode, generation, png, transparent, background, aspose.barcode
+
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
///
-/// Demonstrates generating a DataMatrix barcode and saving it as a PNG file.
+/// Demonstrates generating a DataMatrix barcode and saving it as a PNG with a transparent background.
///
class Program
{
///
- /// Entry point of the application. Generates a DataMatrix barcode with transparent background
- /// and saves it to a PNG file.
+ /// Entry point of the example. Creates the barcode, configures colors, and writes the image file.
///
static void Main()
{
- // Output file name for the generated barcode image
+ // Define the output file path for the generated PNG image
string outputPath = "datamatrix.png";
- // Create a barcode generator for DataMatrix encoding with the desired text
- using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "Hello World"))
+ // Ensure the target directory exists; create it if necessary
+ string directory = Path.GetDirectoryName(Path.GetFullPath(outputPath));
+ if (!Directory.Exists(directory))
+ {
+ Directory.CreateDirectory(directory);
+ }
+
+ // Initialize a DataMatrix barcode generator with sample data
+ using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "SampleData"))
{
- // Set the background to transparent so the barcode can be overlaid on other images
+ // Set the background color to transparent so the barcode can be overlaid on other images
generator.Parameters.BackColor = Color.Transparent;
- // Increase resolution to 300 DPI for higher quality output
- generator.Parameters.Resolution = 300f;
+ // Optionally set the barcode (foreground) color; default is black
+ generator.Parameters.Barcode.BarColor = Color.Black;
- // Save the generated barcode as a PNG image to the specified path
+ // Save the barcode as a PNG file preserving the transparent background
generator.Save(outputPath, BarCodeImageFormat.Png);
}
- // Inform the user where the barcode image has been saved
- Console.WriteLine($"DataMatrix barcode saved to {outputPath}");
+ // Inform the user where the file was saved
+ Console.WriteLine($"DataMatrix barcode saved to: {outputPath}");
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/save-generated-maxicode-barcode-to-memorystream-and-return-byte-array-to-caller.cs b/two-dimensional-barcode-types/save-generated-maxicode-barcode-to-memorystream-and-return-byte-array-to-caller.cs
index ea66261..212001f 100644
--- a/two-dimensional-barcode-types/save-generated-maxicode-barcode-to-memorystream-and-return-byte-array-to-caller.cs
+++ b/two-dimensional-barcode-types/save-generated-maxicode-barcode-to-memorystream-and-return-byte-array-to-caller.cs
@@ -1,3 +1,9 @@
+// Title: Generate MaxiCode barcode and return as byte array
+// Description: Demonstrates creating a MaxiCode barcode, saving it to a MemoryStream, and returning the PNG byte array to the caller.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category. It showcases the use of ComplexBarcodeGenerator with MaxiCodeCodetextMode2 to produce MaxiCode symbols, a common requirement for shipping and logistics applications. Developers often need to generate such barcodes programmatically and obtain the image data as a byte array for further processing or storage.
+// Prompt: Save generated MaxiCode barcode to a MemoryStream and return the byte array to the caller.
+// Tags: maxicode, barcode generation, memory stream, png, aspose.barcode, complexbarcode
+
using System;
using System.IO;
using Aspose.BarCode;
@@ -5,33 +11,30 @@
using Aspose.BarCode.ComplexBarcode;
///
-/// Demonstrates generation of a MaxiCode barcode using Aspose.BarCode library.
+/// Provides an example of generating a MaxiCode barcode and returning the image as a byte array.
///
class Program
{
///
- /// Entry point of the application. Generates a MaxiCode barcode, displays its byte array length,
- /// and optionally writes the image to a file.
+ /// Entry point of the application. Generates a MaxiCode barcode and writes the byte array length to the console.
///
static void Main()
{
- // Generate the MaxiCode barcode and obtain its byte array.
- byte[] barcodeBytes = GenerateMaxiCode();
-
- // Output the size of the generated byte array.
- Console.WriteLine($"Generated MaxiCode barcode byte array length: {barcodeBytes.Length}");
+ // Generate the MaxiCode barcode and obtain the PNG image bytes
+ byte[] imageBytes = GenerateMaxiCode();
- // Optional: write the image to a file for visual verification.
- File.WriteAllBytes("maxicode.png", barcodeBytes);
+ // Output the size of the generated image byte array
+ Console.WriteLine($"Generated MaxiCode image byte array length: {imageBytes.Length}");
}
///
- /// Creates a MaxiCode barcode in Mode 2 with a standard second message and returns the image as a byte array.
+ /// Creates a MaxiCode barcode using Mode 2 encoding, saves it to a MemoryStream in PNG format,
+ /// and returns the resulting byte array.
///
- /// Byte array containing the PNG representation of the generated barcode.
+ /// Byte array containing the PNG image of the generated MaxiCode barcode.
static byte[] GenerateMaxiCode()
{
- // Prepare the MaxiCode codetext for Mode 2 with a standard second message.
+ // Prepare MaxiCode codetext (Mode 2 with a standard second message)
var maxiCodeCodetext = new MaxiCodeCodetextMode2
{
PostalCode = "524032140",
@@ -39,25 +42,22 @@ static byte[] GenerateMaxiCode()
ServiceCategory = 999
};
- // Create the second message to be embedded in the barcode.
+ // Set the optional second message for the barcode
var secondMessage = new MaxiCodeStandardSecondMessage
{
Message = "Test message"
};
maxiCodeCodetext.SecondMessage = secondMessage;
- // Generate the barcode image into a memory stream and return the byte array.
- using (var memoryStream = new MemoryStream())
+ // Generate the barcode and save it to a memory stream in PNG format
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
{
- // Initialize the barcode generator with the prepared codetext.
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ using (var memoryStream = new MemoryStream())
{
- // Save the generated barcode as PNG into the memory stream.
generator.Save(memoryStream, BarCodeImageFormat.Png);
+ // Return the image data as a byte array
+ return memoryStream.ToArray();
}
-
- // Convert the memory stream contents to a byte array.
- return memoryStream.ToArray();
}
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/save-gs1-composite-barcode-image-as-jpeg-with-quality-level-90-for-web-display.cs b/two-dimensional-barcode-types/save-gs1-composite-barcode-image-as-jpeg-with-quality-level-90-for-web-display.cs
index 34138ca..d5d78a8 100644
--- a/two-dimensional-barcode-types/save-gs1-composite-barcode-image-as-jpeg-with-quality-level-90-for-web-display.cs
+++ b/two-dimensional-barcode-types/save-gs1-composite-barcode-image-as-jpeg-with-quality-level-90-for-web-display.cs
@@ -1,53 +1,68 @@
+// Title: Save GS1 Composite barcode as JPEG with quality 90
+// Description: Demonstrates generating a GS1 Composite barcode and saving it as a JPEG image with a quality setting suitable for web display.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, focusing on creating composite barcodes (GS1 Composite) and exporting them to raster image formats. It uses BarcodeGenerator, EncodeTypes, and Aspose.Drawing classes to configure linear and 2D components, adjust dimensions, and control image encoding parameters such as JPEG quality. Developers often need to produce high‑quality barcode images for e‑commerce, shipping labels, or web pages, and this snippet shows the typical steps to achieve that.
+// Prompt: Save GS1 Composite barcode image as JPEG with quality level 90 for web display.
+// Tags: gs1, composite, barcode, generation, jpeg, quality, aspose.barcode, aspose.drawing
+
using System;
using System.IO;
-using Aspose.BarCode;
+using System.Linq;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
+using Aspose.BarCode;
+using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Demonstrates generation of a GS1 Composite barcode and saves it as a JPEG image.
+/// Generates a GS1 Composite barcode and saves it as a JPEG image with a quality level of 90.
///
class Program
{
///
- /// Entry point of the application. Generates a GS1 Composite barcode and writes it to a file.
+ /// Entry point of the example. Creates the barcode, configures its components, and writes the image to disk.
///
static void Main()
{
- // Sample GS1 Composite barcode data.
- // Linear part and 2D part are separated by the '|' character.
+ // Sample GS1 Composite barcode text: linear part | 2D part
string codeText = "(01)03212345678906|(21)A1B2C3D4E5F6G7H8";
- // Output file path for the generated barcode image.
- string outputPath = "gs1composite.jpg";
-
- // Create the barcode generator for GS1 Composite Bar.
- // The generator is disposed automatically at the end of the using block.
+ // Initialize the barcode generator for GS1 Composite Bar symbology
using (var generator = new BarcodeGenerator(EncodeTypes.GS1CompositeBar, codeText))
{
- // Optional: specify component types for the composite barcode.
- // Linear component uses GS1 Code128, 2D component uses CC-A.
+ // Define the linear component (GS1 Code128) and the 2D component (CC-A)
generator.Parameters.Barcode.GS1CompositeBar.LinearComponentType = EncodeTypes.GS1Code128;
generator.Parameters.Barcode.GS1CompositeBar.TwoDComponentType = TwoDComponentType.CC_A;
- // Set resolution suitable for web display (e.g., 150 DPI).
- generator.Parameters.Resolution = 150f;
+ // Optional: fine‑tune the barcode dimensions
+ generator.Parameters.Barcode.XDimension.Pixels = 3f; // module width
+ generator.Parameters.Barcode.BarHeight.Pixels = 100f; // linear part height
- // Save the barcode as JPEG.
- // Note: Aspose.BarCode does not expose a direct API to set JPEG quality.
- // The default JPEG quality is used (typically high enough for web display).
- generator.Save(outputPath, BarCodeImageFormat.Jpeg);
- }
+ // Generate the barcode image as a Bitmap object
+ using (Bitmap bitmap = generator.GenerateBarCodeImage())
+ {
+ // Retrieve the JPEG encoder from the system codecs
+ ImageCodecInfo jpegEncoder = ImageCodecInfo.GetImageEncoders()
+ .FirstOrDefault(enc => enc.FormatID == ImageFormat.Jpeg.Guid);
- // Verify that the file was created and report the result.
- if (File.Exists(outputPath))
- {
- Console.WriteLine($"GS1 Composite barcode saved successfully to '{outputPath}'.");
- }
- else
- {
- Console.WriteLine("Failed to save the barcode image.");
+ string outputPath = "gs1composite.jpg";
+
+ if (jpegEncoder != null)
+ {
+ // Configure JPEG quality to 90 (suitable for web)
+ using (EncoderParameters encoderParams = new EncoderParameters(1))
+ {
+ encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 90L);
+ bitmap.Save(outputPath, jpegEncoder, encoderParams);
+ }
+ }
+ else
+ {
+ // Fallback: save using default JPEG settings if encoder not found
+ bitmap.Save(outputPath, ImageFormat.Jpeg);
+ }
+
+ // Inform the user where the file was saved
+ Console.WriteLine($"GS1 Composite barcode saved to '{Path.GetFullPath(outputPath)}'");
+ }
}
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/save-han-xin-barcode-as-gif-image-with-limited-color-palette-for-web-use.cs b/two-dimensional-barcode-types/save-han-xin-barcode-as-gif-image-with-limited-color-palette-for-web-use.cs
index 90adeb2..ae25666 100644
--- a/two-dimensional-barcode-types/save-han-xin-barcode-as-gif-image-with-limited-color-palette-for-web-use.cs
+++ b/two-dimensional-barcode-types/save-han-xin-barcode-as-gif-image-with-limited-color-palette-for-web-use.cs
@@ -1,38 +1,44 @@
+// Title: Save Han Xin barcode as GIF with limited palette
+// Description: Demonstrates generating a Han Xin barcode and saving it as a GIF image using a minimal two‑color palette, ideal for web deployment.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to configure barcode parameters such as symbology, error correction, and colors, then export to a GIF format. It showcases key classes like BarcodeGenerator, EncodeTypes, and HanXinErrorLevel, which developers use when creating barcodes for web pages, emails, or other bandwidth‑sensitive environments. The snippet serves as a reference for quickly producing compact, web‑friendly barcode images.
+// Prompt: Save Han Xin barcode as GIF image with limited color palette for web use.
+// Tags: hanxin, barcode, gif, color-palette, generation, aspnet, aspose.barcode
+
using System;
-using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Demonstrates generation of a Han Xin barcode and saves it as a GIF image.
+/// Demonstrates creating a Han Xin barcode and saving it as a GIF image with a minimal color palette.
///
class Program
{
///
- /// Entry point of the application. Generates a Han Xin barcode and writes it to disk.
+ /// Entry point of the example. Generates the barcode and writes it to disk.
///
static void Main()
{
- // Define the output file name (saved in the current working directory)
- string outputPath = "HanXinBarcode.gif";
-
- // Text to encode in the barcode
- string codeText = "Sample HanXin 123";
+ // Text to encode in the Han Xin barcode.
+ const string codeText = "Han Xin Sample 123";
- // Initialize the barcode generator for Han Xin symbology with the provided text
+ // Initialize a BarcodeGenerator for Han Xin symbology with the provided text.
using (var generator = new BarcodeGenerator(EncodeTypes.HanXin, codeText))
{
- // Set the error correction level (optional, improves readability)
+ // Optional: set the error correction level for Han Xin (L2 provides higher reliability).
generator.Parameters.Barcode.HanXin.ErrorLevel = HanXinErrorLevel.L2;
- // Define image resolution suitable for web display (96 DPI)
- generator.Parameters.Resolution = 96f;
+ // Configure barcode colors: black bars on a white background.
+ // Using only two colors keeps the GIF palette minimal (max 256 colors).
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- // Save the generated barcode as a GIF image (limited color palette, web-friendly)
- generator.Save(outputPath, BarCodeImageFormat.Gif);
+ // Save the generated barcode as a GIF image.
+ // GIF format inherently uses a limited color palette, making it suitable for web use.
+ generator.Save("HanXinBarcode.gif");
}
- // Output the full path of the saved barcode image to the console
- Console.WriteLine($"Han Xin barcode saved to: {Path.GetFullPath(outputPath)}");
+ // Output a simple confirmation message.
+ Console.WriteLine("Han Xin barcode saved as GIF with a limited color palette.");
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/select-databar-expanded-stacked-as-linear-component-and-cc-as-2d-component-for-gs1-composite-generation.cs b/two-dimensional-barcode-types/select-databar-expanded-stacked-as-linear-component-and-cc-as-2d-component-for-gs1-composite-generation.cs
index c94bfbb..aca8391 100644
--- a/two-dimensional-barcode-types/select-databar-expanded-stacked-as-linear-component-and-cc-as-2d-component-for-gs1-composite-generation.cs
+++ b/two-dimensional-barcode-types/select-databar-expanded-stacked-as-linear-component-and-cc-as-2d-component-for-gs1-composite-generation.cs
@@ -1,40 +1,47 @@
+// Title: Generate GS1 Composite barcode with DataBar Expanded Stacked and CC_A components
+// Description: Demonstrates creating a GS1 Composite barcode where the linear component is DataBar Expanded Stacked and the 2D component is CC_A, then saving the result as a PNG image.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, focusing on composite barcode creation. It showcases the use of BarcodeGenerator, EncodeTypes, and TwoDComponentType to configure GS1 Composite barcodes—common when encoding product identifiers alongside additional data. Developers often need to combine linear and 2D symbologies for GS1 standards, and this snippet illustrates the typical setup and saving workflow.
+// Prompt: Select Databar Expanded Stacked as linear component and CC_A as 2D component for GS1 Composite generation.
+// Tags: gs1 composite, databar expanded stacked, cc_a, barcode generation, png, aspose.barcode
+
using System;
-using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Demonstrates generation of a GS1 Composite barcode using Aspose.BarCode.
+/// Example program that generates a GS1 Composite barcode with a DataBar Expanded Stacked linear component
+/// and a CC_A 2D component, then saves it as a PNG file.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a GS1 Composite barcode with specified linear and 2D components and saves it as an image file.
+ /// Entry point of the example. Builds the composite barcode and writes the image to disk.
///
static void Main()
{
- // Define the sample codetext.
- // The linear (1D) part and the 2D part are separated by the '|' character.
- string codetext = "(01)03212345678906|(21)A12345678";
-
- // Determine the output file path in the current working directory.
- string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "gs1composite.png");
+ // Sample GS1 Composite codetext:
+ // - 1D part (DataBar) encodes a GTIN (01) and a serial number (21)
+ // - 2D part (CC_A) encodes the same data in a 2‑dimensional component
+ // Parts are separated by the '|' character as required by the GS1 Composite format.
+ string codetext = "(01)01234567890123|(21)ABC123";
- // Initialize the barcode generator for a GS1 Composite Bar with the provided codetext.
+ // Initialize the barcode generator for a GS1 Composite barcode using the provided codetext.
using (var generator = new BarcodeGenerator(EncodeTypes.GS1CompositeBar, codetext))
{
- // Configure the linear component to use Databar Expanded Stacked symbology.
+ // Configure the linear component to use DataBar Expanded Stacked.
generator.Parameters.Barcode.GS1CompositeBar.LinearComponentType = EncodeTypes.DatabarExpandedStacked;
- // Configure the 2D component to use the CC_A (Composite Component A) symbology.
+ // Configure the 2D component to use the CC_A symbology.
generator.Parameters.Barcode.GS1CompositeBar.TwoDComponentType = TwoDComponentType.CC_A;
- // Save the generated barcode image to the specified file path.
- generator.Save(outputPath);
- }
+ // Optional visual tweaks for better readability:
+ // - X dimension (module width) set to 3 pixels.
+ // - Bar height set to 100 pixels.
+ generator.Parameters.Barcode.XDimension.Pixels = 3f;
+ generator.Parameters.Barcode.BarHeight.Pixels = 100f;
- // Inform the user where the barcode image has been saved.
- Console.WriteLine($"GS1 Composite barcode saved to: {outputPath}");
+ // Save the generated barcode image to a PNG file in the application directory.
+ generator.Save("gs1composite.png");
+ }
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/separate-1d-and-2d-codetext-parts-with-delimiter-when-creating-gs1-composite-barcode.cs b/two-dimensional-barcode-types/separate-1d-and-2d-codetext-parts-with-delimiter-when-creating-gs1-composite-barcode.cs
index 9c31a26..02a72ed 100644
--- a/two-dimensional-barcode-types/separate-1d-and-2d-codetext-parts-with-delimiter-when-creating-gs1-composite-barcode.cs
+++ b/two-dimensional-barcode-types/separate-1d-and-2d-codetext-parts-with-delimiter-when-creating-gs1-composite-barcode.cs
@@ -1,40 +1,44 @@
+// Title: Generate a GS1 Composite barcode with separate 1D and 2D parts
+// Description: Demonstrates how to create a GS1 Composite barcode by separating the linear and 2D component data with a ‘|’ delimiter.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator with EncodeTypes.GS1CompositeBar, setting linear and 2D component types, and adjusting dimensions. Developers working with GS1 Composite symbologies often need to combine 1D and 2D data streams, configure component types, and export the result as an image.
+// Prompt: Separate 1D and 2D CodeText parts with ‘|’ delimiter when creating a GS1 Composite barcode.
+// Tags: gs1 composite barcode, 1d 2d delimiter, aspose.barcode, barcode generation, png output
+
using System;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode;
///
-/// Demonstrates generation of a GS1 Composite barcode (linear + 2D components) using Aspose.BarCode.
+/// Demonstrates creating a GS1 Composite barcode where the 1D and 2D data parts are separated by a ‘|’ delimiter.
///
class Program
{
///
- /// Entry point of the application. Generates a GS1 Composite barcode and saves it as a PNG file.
+ /// Entry point. Generates the barcode image and saves it to disk.
///
static void Main()
{
- // Define the barcode data: linear part and 2D part are separated by the '|' character.
- // (01) – Application Identifier for GTIN, (21) – AI for serial number.
+ // Define the GS1 Composite barcode text: linear (1D) part and 2D part separated by '|'
string codeText = "(01)03212345678906|(21)A1B2C3D4E5F6G7H8";
- // Initialize the barcode generator for the GS1 Composite symbology.
- // The constructor receives the symbology type and the data to encode.
+ // Initialize the generator for GS1 Composite Bar symbology with the combined code text
using (var generator = new BarcodeGenerator(EncodeTypes.GS1CompositeBar, codeText))
{
- // Configure the linear component (e.g., GS1 Code128) of the composite barcode.
+ // Configure the linear component to use GS1 Code128
generator.Parameters.Barcode.GS1CompositeBar.LinearComponentType = EncodeTypes.GS1Code128;
- // Configure the 2D component (e.g., CC-A – MicroPDF417) of the composite barcode.
+ // Configure the 2D component to use CC-A (Composite Component A)
generator.Parameters.Barcode.GS1CompositeBar.TwoDComponentType = TwoDComponentType.CC_A;
- // Optional: fine‑tune visual dimensions.
- generator.Parameters.Barcode.XDimension.Point = 2f; // Width of a single module (in points).
- generator.Parameters.Barcode.BarHeight.Point = 50f; // Height of the linear (1D) component.
+ // Optional: adjust visual dimensions
+ generator.Parameters.Barcode.XDimension.Pixels = 3f; // module (X) size in pixels
+ generator.Parameters.Barcode.BarHeight.Pixels = 100f; // height of the linear (1D) component
- // Render the barcode and write it to a PNG file.
- generator.Save("gs1_composite.png");
+ // Save the generated barcode as a PNG image
+ generator.Save("gs1composite.png");
}
- // Inform the user that the barcode image has been created.
- Console.WriteLine("GS1 Composite barcode generated: gs1_composite.png");
+ // Inform the user that the barcode has been generated
+ Console.WriteLine("GS1 Composite barcode generated: gs1composite.png");
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/set-datamatrix-encoding-mode-to-auto-to-let-engine-choose-optimal-symbol-size.cs b/two-dimensional-barcode-types/set-datamatrix-encoding-mode-to-auto-to-let-engine-choose-optimal-symbol-size.cs
index 5cb4d5b..5b4bc7a 100644
--- a/two-dimensional-barcode-types/set-datamatrix-encoding-mode-to-auto-to-let-engine-choose-optimal-symbol-size.cs
+++ b/two-dimensional-barcode-types/set-datamatrix-encoding-mode-to-auto-to-let-engine-choose-optimal-symbol-size.cs
@@ -1,33 +1,40 @@
+// Title: DataMatrix Barcode Generation with Auto Encoding Mode
+// Description: Demonstrates how to generate a DataMatrix barcode using Aspose.BarCode with the encoding mode set to Auto, allowing the engine to select the optimal symbol size.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on DataMatrix symbology. It showcases the use of BarcodeGenerator, EncodeTypes, and DataMatrixEncodeMode classes to create barcodes. Developers commonly need to generate DataMatrix codes for inventory, tracking, or labeling, and often require the engine to automatically determine the best symbol size based on the input data.
+// Prompt: Set DataMatrix encoding mode to Auto to let the engine choose the optimal symbol size.
+// Tags: datamatrix, encoding mode, auto, barcode generation, aspnet, aspnetcore, aspnet5, aspose.barcode, png
+
using System;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Demonstrates generating a DataMatrix barcode and saving it as an image file.
+/// Demonstrates generating a DataMatrix barcode with automatic encoding mode using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application. Generates a DataMatrix barcode with sample text and saves it to a PNG file.
+ /// Entry point of the example. Generates and saves a DataMatrix barcode image.
///
static void Main()
{
- // Define the text to encode in the DataMatrix barcode.
- string codeText = "Sample DataMatrix";
-
- // Specify the output file path for the generated barcode image.
- string outputPath = "datamatrix.png";
+ // Define the text to be encoded in the barcode.
+ const string codeText = "Sample DataMatrix Text";
- // Initialize the barcode generator for DataMatrix with the provided text.
+ // Initialize a DataMatrix barcode generator with the specified text.
using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, codeText))
{
- // Configure the generator to automatically select the optimal symbol size.
+ // Configure the generator to let the engine choose the optimal symbol size.
generator.Parameters.Barcode.DataMatrix.EncodeMode = DataMatrixEncodeMode.Auto;
- // Save the generated barcode image to the specified file path.
+ // Define the output file path for the generated PNG image.
+ const string outputPath = "datamatrix_auto.png";
+
+ // Save the generated barcode image to the specified path.
generator.Save(outputPath);
- }
- // Inform the user that the barcode has been saved successfully.
- Console.WriteLine($"DataMatrix barcode saved to {outputPath}");
+ // Inform the user where the barcode image has been saved.
+ Console.WriteLine($"DataMatrix barcode saved to {outputPath}");
+ }
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/set-eciencoding-to-utf-8-for-maxicode-and-verify-correct-character-set-identifier-is-embedded.cs b/two-dimensional-barcode-types/set-eciencoding-to-utf-8-for-maxicode-and-verify-correct-character-set-identifier-is-embedded.cs
index 7407600..a8adf26 100644
--- a/two-dimensional-barcode-types/set-eciencoding-to-utf-8-for-maxicode-and-verify-correct-character-set-identifier-is-embedded.cs
+++ b/two-dimensional-barcode-types/set-eciencoding-to-utf-8-for-maxicode-and-verify-correct-character-set-identifier-is-embedded.cs
@@ -1,61 +1,68 @@
+// Title: Set ECIEncoding to UTF-8 for MaxiCode and verify embedded character set
+// Description: Demonstrates how to configure a MaxiCode barcode to use UTF‑8 ECI encoding and validates that the correct character set identifier is embedded by reading the barcode back.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, focusing on ECI (Extended Channel Interpretation) handling for Unicode data. It showcases the BarcodeGenerator and BarCodeReader classes, typical for scenarios where international characters must be encoded in 2D barcodes such as MaxiCode. Developers often need to set ECIEncoding to ensure proper decoding across platforms.
+// Prompt: Set ECIEncoding to UTF‑8 for MaxiCode and verify the correct character set identifier is embedded.
+// Tags: maxicode, eci, utf-8, barcode generation, barcode recognition, aspnet.barcode, encoding
+
using System;
using System.IO;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.BarCode;
///
-/// Demonstrates generating a MaxiCode barcode with UTF-8 ECI encoding,
-/// saving it to a file, and then reading it back to verify the content.
+/// Generates a MaxiCode barcode with UTF‑8 ECI encoding, saves it, and verifies the encoding by reading the barcode back.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a MaxiCode barcode containing Unicode text, saves it,
- /// and reads it back to display the decoded value.
+ /// Main entry point of the example.
///
static void Main()
{
- // Unicode text that requires UTF-8 encoding (Japanese greeting)
- string codeText = "こんにちは";
+ // Define the output file path for the generated barcode image.
+ string outputPath = "maxicode_utf8.png";
- // Determine the full path for the output image file
- string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "maxicode.png");
+ // Sample text containing Unicode characters to be encoded in the barcode.
+ string sampleText = "犬Right狗";
- // Create a barcode generator for MaxiCode with the specified text
- using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, codeText))
+ // Create a MaxiCode barcode generator with the sample text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, sampleText))
{
- // Configure the generator to use UTF-8 ECI encoding
+ // Set the ECI (Extended Channel Interpretation) encoding to UTF‑8.
generator.Parameters.Barcode.MaxiCode.ECIEncoding = ECIEncodings.UTF8;
- // Save the generated barcode image to the file system
+ // Save the generated barcode image to the specified file.
generator.Save(outputPath);
}
- // Inform the user where the barcode image was saved
- Console.WriteLine($"MaxiCode generated with ECIEncoding=UTF-8 at: {outputPath}");
+ // Verify that the barcode image file was created successfully.
+ if (!File.Exists(outputPath))
+ {
+ Console.WriteLine("Failed to create the barcode image.");
+ return;
+ }
- // Verify the generated barcode by reading it back, if the file exists
- if (File.Exists(outputPath))
+ // Initialize a barcode reader for MaxiCode to read the saved image.
+ using (var reader = new BarCodeReader(outputPath, DecodeType.MaxiCode))
{
- // Initialize a barcode reader for MaxiCode format
- using (var reader = new BarCodeReader(outputPath, DecodeType.MaxiCode))
+ // Read all barcodes found in the image.
+ var results = reader.ReadBarCodes();
+
+ // Ensure at least one barcode was detected.
+ if (results.Length == 0)
{
- // Read all barcodes found in the image
- var results = reader.ReadBarCodes();
-
- // Output each decoded text to the console
- foreach (var result in results)
- {
- Console.WriteLine("Decoded CodeText: " + result.CodeText);
- }
+ Console.WriteLine("No barcode detected.");
+ return;
+ }
+
+ // Iterate through each detected barcode result.
+ foreach (var result in results)
+ {
+ // Output the decoded text and verify it matches the original sample text.
+ // This confirms that the UTF‑8 ECI identifier was correctly embedded.
+ Console.WriteLine($"Decoded Text: {result.CodeText}");
+ Console.WriteLine($"Match Original: {result.CodeText == sampleText}");
}
- }
- else
- {
- // Notify the user that the image file was not created
- Console.WriteLine("Failed to generate the barcode image.");
}
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/validate-datamatrix-barcode-dimensions-meet-minimum-module-size-requirement-for-high-density-printing.cs b/two-dimensional-barcode-types/validate-datamatrix-barcode-dimensions-meet-minimum-module-size-requirement-for-high-density-printing.cs
index 66aac25..11ef98f 100644
--- a/two-dimensional-barcode-types/validate-datamatrix-barcode-dimensions-meet-minimum-module-size-requirement-for-high-density-printing.cs
+++ b/two-dimensional-barcode-types/validate-datamatrix-barcode-dimensions-meet-minimum-module-size-requirement-for-high-density-printing.cs
@@ -1,85 +1,55 @@
+// Title: Validate DataMatrix barcode module size for high‑density printing
+// Description: Demonstrates how to check that a DataMatrix barcode's XDimension meets a minimum module size required for high‑density print quality.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and validation category. It shows usage of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes to create a DataMatrix barcode, inspect its XDimension, and ensure it satisfies printing constraints. Developers often need to validate barcode dimensions before printing to avoid readability issues, especially for dense barcodes.
+// Prompt: Validate DataMatrix barcode dimensions meet minimum module size requirement for high‑density printing.
+// Tags: datamatrix, validation, dimensions, xdimension, barcode generation, aspose.barcode, png
+
using System;
-using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
+using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing.Imaging;
///
-/// Demonstrates generation of a DataMatrix barcode with a fixed version,
-/// saves it to a PNG file, and verifies the module size against a minimum requirement.
+/// Example program that generates a DataMatrix barcode and validates its module size
+/// (XDimension) against a minimum requirement for high‑density printing.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a DataMatrix barcode, saves it, and checks the module size.
+ /// Entry point. Creates a DataMatrix barcode, checks the XDimension, and saves the image.
///
static void Main()
{
- // Output file name for the generated barcode image
- const string outputPath = "datamatrix.png";
-
- // Minimum acceptable module size (in pixels) for high‑density printing
- const float minModuleSizePixels = 2f;
-
- // ------------------------------------------------------------
- // 1. Generate a DataMatrix barcode with a known version (20x20 modules)
- // ------------------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "HelloWorld"))
- {
- // Force the barcode to use the 20x20 ECC200 version
- generator.Parameters.Barcode.DataMatrix.DataMatrixVersion = DataMatrixVersion.ECC200_20x20;
-
- // Disable automatic scaling so we can control module size directly
- generator.Parameters.AutoSizeMode = AutoSizeMode.None;
-
- // Set the module (X) dimension in points (1 point = 1/72 inch)
- generator.Parameters.Barcode.XDimension.Point = 2f;
-
- // Save the generated barcode image to the specified path
- generator.Save(outputPath);
- }
+ // Sample data to encode in the barcode
+ const string codeText = "HighDensityDataMatrix";
- // Verify that the image file was created successfully
- if (!File.Exists(outputPath))
- {
- Console.WriteLine("Failed to generate the barcode image.");
- return;
- }
+ // Minimum acceptable module size (XDimension) in points for high‑density printing
+ const float minModuleSize = 0.5f; // points
- // ------------------------------------------------------------
- // 2. Load the generated image and calculate the actual module size
- // ------------------------------------------------------------
- using (var image = Image.FromFile(outputPath))
+ // Initialize a DataMatrix barcode generator with the sample text
+ using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, codeText))
{
- int pixelWidth = image.Width; // Image width in pixels
- int pixelHeight = image.Height; // Image height in pixels
-
- // Number of modules per side for the selected version (20x20)
- const int modulesPerSide = 20;
+ // Intentionally set a module size that may be too small for demonstration
+ generator.Parameters.Barcode.XDimension.Point = 0.4f;
- // Compute module size in X and Y directions
- double moduleSizeX = (double)pixelWidth / modulesPerSide;
- double moduleSizeY = (double)pixelHeight / modulesPerSide;
+ // Retrieve the actual module size that will be used
+ float actualModuleSize = generator.Parameters.Barcode.XDimension.Point;
- // Use the smaller dimension to ensure a conservative estimate
- double moduleSize = Math.Min(moduleSizeX, moduleSizeY);
-
- // Output diagnostic information
- Console.WriteLine($"Barcode image dimensions: {pixelWidth}x{pixelHeight} pixels");
- Console.WriteLine($"Calculated module size: {moduleSize:F2} pixels");
-
- // Compare calculated module size with the minimum requirement
- if (moduleSize >= minModuleSizePixels)
- Console.WriteLine("Module size meets the minimum requirement.");
+ // Compare the actual size with the minimum requirement and output a warning if needed
+ if (actualModuleSize < minModuleSize)
+ {
+ Console.WriteLine($"Warning: XDimension ({actualModuleSize}pt) is below the minimum required ({minModuleSize}pt) for high‑density printing.");
+ }
else
- Console.WriteLine($"Module size is below the minimum of {minModuleSizePixels} pixels. Adjust XDimension or version.");
+ {
+ Console.WriteLine($"XDimension ({actualModuleSize}pt) meets the minimum requirement.");
+ }
+
+ // Define the output file path and save the barcode as a PNG image
+ const string outputPath = "datamatrix.png";
+ generator.Save(outputPath, BarCodeImageFormat.Png);
+ Console.WriteLine($"Barcode saved to {outputPath}");
}
-
- // ------------------------------------------------------------
- // 3. Optional cleanup (uncomment to delete the generated file)
- // ------------------------------------------------------------
- // File.Delete(outputPath);
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/validate-generated-gs1-composite-barcode-against-gs1-specification-using-library-s-validation-api.cs b/two-dimensional-barcode-types/validate-generated-gs1-composite-barcode-against-gs1-specification-using-library-s-validation-api.cs
index 35098e6..7441337 100644
--- a/two-dimensional-barcode-types/validate-generated-gs1-composite-barcode-against-gs1-specification-using-library-s-validation-api.cs
+++ b/two-dimensional-barcode-types/validate-generated-gs1-composite-barcode-against-gs1-specification-using-library-s-validation-api.cs
@@ -1,3 +1,9 @@
+// Title: Validate GS1 Composite Barcode Using Aspose.BarCode
+// Description: Demonstrates generating a GS1 Composite barcode, saving it as an image, and validating its components against the GS1 specification using Aspose.BarCode's validation API.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and validation category, showcasing how to work with GS1 Composite symbology. It uses BarcodeGenerator for creation, BarCodeReader for recognition, and the GS1CompositeBar extended parameters for detailed validation. Developers often need to generate GS1 barcodes for supply‑chain labeling and verify that both linear and 2D components conform to GS1 standards.
+// Prompt: Validate generated GS1 Composite barcode against GS1 specification using the library's validation API.
+// Tags: gs1 composite, barcode generation, barcode validation, aspose.barcode, csharp
+
using System;
using System.IO;
using Aspose.BarCode;
@@ -5,91 +11,104 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates generation and validation of a GS1 Composite barcode using Aspose.BarCode.
+/// Generates a GS1 Composite barcode, saves it to a PNG file, and validates the
+/// linear and 2D components against the original data using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a GS1 Composite barcode, saves it as an image, and then validates it by reading the image.
+ /// Entry point of the example. Performs barcode creation, saving, and validation.
///
static void Main()
{
- // Sample GS1 Composite barcode data.
- // Linear part: (01)03212345678906 (GTIN)
- // 2D part: (21)A1B2C3D4E5F6G7H8 (Serial)
+ // Define the GS1 Composite barcode text.
+ // Linear part: (01)03212345678906
+ // 2D part: (21)A1B2C3D4E5F6G7H8
// Parts are separated by '|'
string codetext = "(01)03212345678906|(21)A1B2C3D4E5F6G7H8";
- // Output image path for the generated barcode.
- string imagePath = "gs1composite.png";
+ // Output file path for the generated barcode image.
+ string outputPath = "gs1composite.png";
- // -------------------------------------------------
- // Generate the GS1 Composite barcode and save it.
- // -------------------------------------------------
+ // Generate the GS1 Composite barcode.
using (var generator = new BarcodeGenerator(EncodeTypes.GS1CompositeBar, codetext))
{
- // Configure the linear component to use GS1-128 encoding.
+ // Set the linear component to GS1 Code 128.
generator.Parameters.Barcode.GS1CompositeBar.LinearComponentType = EncodeTypes.GS1Code128;
- // Configure the 2D component to use CC-A (Composite Component A) type.
+ // Set the 2D component to CC-A (Composite Component A).
generator.Parameters.Barcode.GS1CompositeBar.TwoDComponentType = TwoDComponentType.CC_A;
- // Enforce GS1 encoding rules for the 2D component.
- generator.Parameters.Barcode.GS1CompositeBar.AllowOnlyGS1Encoding = true;
+ // Optional: adjust the aspect ratio for the 2D component.
+ generator.Parameters.Barcode.Pdf417.AspectRatio = 3f;
+
+ // Set X-dimension (module width) for both components.
+ generator.Parameters.Barcode.XDimension.Pixels = 3f;
- // Set size parameters: X-dimension and bar height in pixels.
- generator.Parameters.Barcode.XDimension.Pixels = 3;
- generator.Parameters.Barcode.BarHeight.Pixels = 100;
+ // Set the height of the linear component.
+ generator.Parameters.Barcode.BarHeight.Pixels = 100f;
- // Save the generated barcode image to the specified path.
- generator.Save(imagePath);
+ // Save the barcode image to the specified path.
+ generator.Save(outputPath);
}
- // -------------------------------------------------
- // Verify that the barcode image was successfully created.
- // -------------------------------------------------
- if (!File.Exists(imagePath))
+ // Verify that the barcode image file was created successfully.
+ if (!File.Exists(outputPath))
{
- Console.WriteLine($"Failed to create barcode image at '{imagePath}'.");
+ Console.WriteLine($"Failed to create barcode image at '{outputPath}'.");
return;
}
- // -------------------------------------------------
- // Recognize and validate the generated barcode.
- // -------------------------------------------------
- using (var reader = new BarCodeReader(imagePath, DecodeType.GS1CompositeBar))
+ // Read and validate the generated barcode.
+ using (var reader = new BarCodeReader(outputPath, DecodeType.GS1CompositeBar))
{
- // Enable checksum validation (required for GS1 where applicable).
+ // Enable checksum validation (recommended for GS1 barcodes).
reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.On;
- // Disallow recognition of barcodes that are identified as incorrect.
- reader.QualitySettings.AllowIncorrectBarcodes = false;
-
- // Read all barcodes from the image.
- var results = reader.ReadBarCodes();
+ bool validationPassed = false;
- // If no barcodes were detected, report and exit.
- if (results.Length == 0)
+ // Iterate through all recognized barcodes (should be only one).
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
- Console.WriteLine("No barcode detected.");
- return;
- }
+ // Output the raw CodeText returned by the reader.
+ Console.WriteLine($"Recognized CodeText: {result.CodeText}");
- // Iterate through each detected barcode result.
- foreach (var result in results)
- {
- // Check for GS1 Composite specific extended parameters.
- if (result.Extended?.GS1CompositeBar != null)
+ // Access GS1 Composite specific extended parameters.
+ var gs1Ext = result.Extended.GS1CompositeBar;
+ if (gs1Ext != null && !gs1Ext.IsEmpty)
{
- Console.WriteLine("GS1 Composite barcode validation succeeded.");
- Console.WriteLine($"Recognized CodeText: {result.CodeText}");
+ // Display component types and their respective CodeTexts.
+ Console.WriteLine($"Linear Component Type: {gs1Ext.OneDType}");
+ Console.WriteLine($"Linear Component CodeText: {gs1Ext.OneDCodeText}");
+ Console.WriteLine($"2D Component Type: {gs1Ext.TwoDType}");
+ Console.WriteLine($"2D Component CodeText: {gs1Ext.TwoDCodeText}");
+
+ // Expected component texts for validation.
+ string expectedLinear = "(01)03212345678906";
+ string expectedTwoD = "(21)A1B2C3D4E5F6G7H8";
+
+ // Compare recognized component texts with expected values.
+ if (gs1Ext.OneDCodeText == expectedLinear && gs1Ext.TwoDCodeText == expectedTwoD)
+ {
+ validationPassed = true;
+ Console.WriteLine("GS1 Composite barcode validation succeeded.");
+ }
+ else
+ {
+ Console.WriteLine("GS1 Composite barcode validation failed: component texts do not match expected values.");
+ }
}
else
{
- Console.WriteLine("GS1 Composite barcode validation failed: extended GS1 data not available.");
+ Console.WriteLine("GS1 Composite extended parameters are missing or empty.");
}
}
+
+ // Report overall validation result if no successful match was found.
+ if (!validationPassed)
+ {
+ Console.WriteLine("GS1 Composite barcode validation did not pass.");
+ }
}
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/validate-that-generated-dotcode-barcode-meets-minimum-quiet-zone-requirements-for-scanner-compatibility.cs b/two-dimensional-barcode-types/validate-that-generated-dotcode-barcode-meets-minimum-quiet-zone-requirements-for-scanner-compatibility.cs
index 3c3b993..ad14a52 100644
--- a/two-dimensional-barcode-types/validate-that-generated-dotcode-barcode-meets-minimum-quiet-zone-requirements-for-scanner-compatibility.cs
+++ b/two-dimensional-barcode-types/validate-that-generated-dotcode-barcode-meets-minimum-quiet-zone-requirements-for-scanner-compatibility.cs
@@ -1,103 +1,108 @@
+// Title: Validate DotCode Barcode Quiet Zone
+// Description: Generates a DotCode barcode, saves it, and verifies that the quiet zone around the barcode meets the minimum required size for reliable scanning.
+// Category-Description: This example demonstrates Aspose.BarCode generation and recognition for DotCode symbology. It uses BarcodeGenerator to create the barcode, configures XDimension and padding to ensure adequate quiet zones, and employs BarCodeReader to detect the barcode region. Developers working with barcode printing or scanning often need to validate quiet zone dimensions to guarantee scanner compatibility, making this a common task in barcode workflow automation.
+/// Prompt: Validate that generated DotCode barcode meets minimum quiet zone requirements for scanner compatibility.
+/// Tags: dotcode, quiet zone, barcode generation, barcode recognition, aspose.barcode, aspose.drawing, image processing
+
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Demonstrates generating a DotCode barcode with a specified quiet zone,
-/// saving it to an image file, and then validating the quiet zone by reading the barcode back.
+/// Demonstrates how to generate a DotCode barcode, save it as an image,
+/// and validate that the quiet zone around the barcode satisfies the minimum
+/// size requirements for scanner compatibility.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a DotCode barcode, saves it, and validates its quiet zone.
+ /// Entry point of the example. Generates the barcode, saves it,
+ /// and checks the quiet zone dimensions.
///
static void Main()
{
- // Path for the generated barcode image
+ // Define the output file path for the generated barcode image.
string outputPath = "dotcode.png";
- // Minimum quiet zone required (in points)
- float minQuietZonePoints = 10f;
-
- // Create a DotCode barcode generator with the desired data
- BaseEncodeType encodeType = EncodeTypes.DotCode;
- using (var generator = new BarcodeGenerator(encodeType, "1234567890"))
+ // ------------------------------------------------------------
+ // Generate a DotCode barcode with explicit XDimension and padding.
+ // ------------------------------------------------------------
+ using (var generator = new BarcodeGenerator(EncodeTypes.DotCode, "1234567890"))
{
- // Apply the same quiet zone (padding) to all four sides
- generator.Parameters.Barcode.Padding.Left.Point = minQuietZonePoints;
- generator.Parameters.Barcode.Padding.Top.Point = minQuietZonePoints;
- generator.Parameters.Barcode.Padding.Right.Point = minQuietZonePoints;
- generator.Parameters.Barcode.Padding.Bottom.Point = minQuietZonePoints;
+ // Set XDimension to ensure sufficient bar size (2 points per module).
+ generator.Parameters.Barcode.XDimension.Point = 2f;
- // Save the generated barcode image to the specified file
+ // Configure padding (quiet zone) of at least 10 points on each side.
+ generator.Parameters.Barcode.Padding.Left.Point = 10f;
+ generator.Parameters.Barcode.Padding.Top.Point = 10f;
+ generator.Parameters.Barcode.Padding.Right.Point = 10f;
+ generator.Parameters.Barcode.Padding.Bottom.Point = 10f;
+
+ // Save the generated barcode image to the specified path.
generator.Save(outputPath);
}
- // Ensure the image file was created successfully
+ // ------------------------------------------------------------
+ // Verify that the barcode image file was created successfully.
+ // ------------------------------------------------------------
if (!File.Exists(outputPath))
{
- Console.WriteLine($"Failed to generate barcode image at '{outputPath}'.");
+ Console.WriteLine($"Error: Barcode image not found at '{outputPath}'.");
return;
}
- // Load the saved image to obtain its dimensions (width & height in pixels)
- using (var image = Image.FromFile(outputPath))
+ // ------------------------------------------------------------
+ // Load the image to obtain its dimensions for quiet zone calculation.
+ // ------------------------------------------------------------
+ using (var image = (Bitmap)Image.FromFile(outputPath))
{
int imageWidth = image.Width;
int imageHeight = image.Height;
- // Initialize a barcode reader for DotCode type on the saved image
+ // --------------------------------------------------------
+ // Read the barcode from the saved image using BarCodeReader.
+ // --------------------------------------------------------
using (var reader = new BarCodeReader(outputPath, DecodeType.DotCode))
{
- // Attempt to read all barcodes present in the image
var results = reader.ReadBarCodes();
- // If no barcode is detected, report and exit
if (results.Length == 0)
{
- Console.WriteLine("No DotCode barcode detected in the image.");
+ Console.WriteLine("No barcode detected.");
return;
}
- // Assume the first detected barcode corresponds to the one we generated
+ // Assume the first detected result corresponds to the generated barcode.
var result = results[0];
- var region = result.Region.Rectangle; // RectangleF representing barcode bounds
-
- // Compute quiet zones: distance from barcode edges to image edges
- float leftQuiet = region.X;
- float topQuiet = region.Y;
- float rightQuiet = imageWidth - (region.X + region.Width);
- float bottomQuiet = imageHeight - (region.Y + region.Height);
+ var bounds = result.Region.Rectangle; // Rectangle with X, Y, Width, Height
- // Determine the smallest quiet zone among all sides
- float smallestQuiet = Math.Min(
- Math.Min(leftQuiet, rightQuiet),
- Math.Min(topQuiet, bottomQuiet));
+ // --------------------------------------------------------
+ // Calculate quiet zone margins based on the detected region.
+ // --------------------------------------------------------
+ int leftMargin = bounds.X;
+ int topMargin = bounds.Y;
+ int rightMargin = imageWidth - (bounds.X + bounds.Width);
+ int bottomMargin = imageHeight - (bounds.Y + bounds.Height);
- // Convert required quiet zone from points to pixels (assuming 96 DPI)
- // 1 point = 1/72 inch; 96 DPI => 1 point = 96/72 = 1.3333 pixels
- float pointsToPixels = 96f / 72f;
- float requiredPixels = minQuietZonePoints * pointsToPixels;
+ const int MinimumQuietZonePoints = 10;
- // Output diagnostic information
- Console.WriteLine($"Image size: {imageWidth}x{imageHeight} pixels");
- Console.WriteLine($"Detected barcode region: X={region.X}, Y={region.Y}, Width={region.Width}, Height={region.Height}");
- Console.WriteLine($"Quiet zones (pixels) - Left: {leftQuiet}, Top: {topQuiet}, Right: {rightQuiet}, Bottom: {bottomQuiet}");
- Console.WriteLine($"Smallest quiet zone: {smallestQuiet} pixels");
+ bool quietZoneValid =
+ leftMargin >= MinimumQuietZonePoints &&
+ topMargin >= MinimumQuietZonePoints &&
+ rightMargin >= MinimumQuietZonePoints &&
+ bottomMargin >= MinimumQuietZonePoints;
- // Validate whether the smallest quiet zone meets the required minimum
- if (smallestQuiet >= requiredPixels)
- {
- Console.WriteLine("Validation passed: Quiet zone meets the minimum requirement.");
- }
- else
- {
- Console.WriteLine($"Validation failed: Quiet zone is smaller than the required {minQuietZonePoints} points.");
- }
+ // --------------------------------------------------------
+ // Output diagnostic information.
+ // --------------------------------------------------------
+ Console.WriteLine($"Barcode Type: {result.CodeTypeName}");
+ Console.WriteLine($"Code Text: {result.CodeText}");
+ Console.WriteLine($"Image Size: {imageWidth}x{imageHeight} points");
+ Console.WriteLine($"Detected Region: X={bounds.X}, Y={bounds.Y}, Width={bounds.Width}, Height={bounds.Height}");
+ Console.WriteLine($"Quiet Zone Margins (points) - Left: {leftMargin}, Top: {topMargin}, Right: {rightMargin}, Bottom: {bottomMargin}");
+ Console.WriteLine($"Quiet zone meets minimum requirement of {MinimumQuietZonePoints} points on each side: {quietZoneValid}");
}
}
}
diff --git a/two-dimensional-barcode-types/validate-that-generated-han-xin-barcode-meets-required-quiet-zone-dimensions-for-scanner-reliability.cs b/two-dimensional-barcode-types/validate-that-generated-han-xin-barcode-meets-required-quiet-zone-dimensions-for-scanner-reliability.cs
index fcd2603..07454ee 100644
--- a/two-dimensional-barcode-types/validate-that-generated-han-xin-barcode-meets-required-quiet-zone-dimensions-for-scanner-reliability.cs
+++ b/two-dimensional-barcode-types/validate-that-generated-han-xin-barcode-meets-required-quiet-zone-dimensions-for-scanner-reliability.cs
@@ -1,91 +1,93 @@
+// Title: Validate Han Xin barcode quiet zone dimensions
+// Description: Demonstrates generating a Han Xin barcode with explicit quiet zone padding and verifies that the barcode can be decoded, ensuring scanner reliability.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and recognition category. It shows how to configure barcode parameters such as padding, module size, and error correction using BarcodeGenerator, and then validates the output with BarCodeReader. Developers often need to adjust quiet zones to meet scanner specifications, and this snippet illustrates the typical workflow for creating and testing barcodes in .NET applications.
+// Prompt: Validate that generated Han Xin barcode meets required quiet zone dimensions for scanner reliability.
+// Tags: hanxin,quietzone,padding,barcode,generation,recognition,aspose.barcode,csharp
+
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates generation and recognition of a Han Xin barcode,
-/// and validates the required quiet zone around the detected barcode.
+/// Generates a Han Xin barcode with defined quiet zone padding,
+/// saves it to an image file, and validates that the barcode can be decoded.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a Han Xin barcode, reads it back, and checks quiet zone dimensions.
+ /// Entry point of the example. Creates the barcode, configures padding,
+ /// saves the image, and verifies decoding to ensure scanner reliability.
///
static void Main()
{
- const string codeText = "1234567890";
+ // Define the output file path for the generated barcode image.
+ string outputPath = "HanXin.png";
- // Generate Han Xin barcode into a memory stream
- using (MemoryStream ms = new MemoryStream())
+ // Remove any existing file to avoid conflicts.
+ if (File.Exists(outputPath))
{
- float requiredQuiet; // Holds the calculated quiet zone size (in points)
+ File.Delete(outputPath);
+ }
- // Create a barcode generator for Han Xin type with the specified text
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.HanXin, codeText))
- {
- // Set module size (XDimension) – 2 points per module
- generator.Parameters.Barcode.XDimension.Point = 2f;
+ // Create a Han Xin barcode generator with sample code text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.HanXin, "SampleHanXin123"))
+ {
+ // Set quiet zone (padding) – typical scanners require at least 10 points on each side.
+ generator.Parameters.Barcode.Padding.Left.Point = 10f;
+ generator.Parameters.Barcode.Padding.Top.Point = 10f;
+ generator.Parameters.Barcode.Padding.Right.Point = 10f;
+ generator.Parameters.Barcode.Padding.Bottom.Point = 10f;
- // Store required quiet zone for later validation (2 * XDimension)
- requiredQuiet = generator.Parameters.Barcode.XDimension.Point * 2f;
+ // Optional: set module size and error correction level.
+ generator.Parameters.Barcode.XDimension.Point = 2f; // module width
+ generator.Parameters.Barcode.HanXin.ErrorLevel = HanXinErrorLevel.L2;
- // Use automatic version selection for the Han Xin barcode
- generator.Parameters.Barcode.HanXin.Version = HanXinVersion.Auto;
+ // Use black bars on a white background.
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- // Set error correction level (example: L2)
- generator.Parameters.Barcode.HanXin.ErrorLevel = HanXinErrorLevel.L2;
+ // Save the barcode image to the specified path.
+ generator.Save(outputPath);
+ }
- // Save the generated barcode image as PNG into the memory stream
- generator.Save(ms, BarCodeImageFormat.Png);
- }
+ // Verify that the image file was successfully created.
+ if (!File.Exists(outputPath))
+ {
+ Console.WriteLine("Failed to generate the Han Xin barcode image.");
+ return;
+ }
- // Reset stream position to the beginning for reading
- ms.Position = 0;
+ // Output the configured quiet zone dimensions for verification.
+ using (var verifier = new BarcodeGenerator(EncodeTypes.HanXin))
+ {
+ Console.WriteLine("Configured quiet zone (padding) values (points):");
+ Console.WriteLine($"Left: {verifier.Parameters.Barcode.Padding.Left.Point}");
+ Console.WriteLine($"Top: {verifier.Parameters.Barcode.Padding.Top.Point}");
+ Console.WriteLine($"Right: {verifier.Parameters.Barcode.Padding.Right.Point}");
+ Console.WriteLine($"Bottom: {verifier.Parameters.Barcode.Padding.Bottom.Point}");
+ }
- // Load the generated image as a Bitmap (required by BarCodeReader)
- using (Bitmap bitmap = new Bitmap(ms))
+ // Attempt to read the barcode to ensure scanner reliability.
+ using (var reader = new BarCodeReader(outputPath, DecodeType.AllSupportedTypes))
+ {
+ bool found = false;
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
- // Initialize a barcode reader for Han Xin type
- using (BarCodeReader reader = new BarCodeReader(bitmap, DecodeType.HanXin))
- {
- // Read all detected barcodes from the image
- var results = reader.ReadBarCodes();
-
- // If no barcode is found, output a message and exit
- if (results.Length == 0)
- {
- Console.WriteLine("No Han Xin barcode detected.");
- return;
- }
-
- // Use the first detected barcode result
- var result = results[0];
- var region = result.Region.Rectangle; // Bounding rectangle of the barcode
-
- // Calculate quiet zone sizes (in pixels) on each side of the barcode
- int leftQuiet = (int)Math.Round((double)region.X);
- int topQuiet = (int)Math.Round((double)region.Y);
- int rightQuiet = bitmap.Width - (int)Math.Round((double)region.Right);
- int bottomQuiet = bitmap.Height - (int)Math.Round((double)region.Bottom);
-
- // Verify that each quiet zone meets or exceeds the required size
- bool quietOk = leftQuiet >= requiredQuiet &&
- topQuiet >= requiredQuiet &&
- rightQuiet >= requiredQuiet &&
- bottomQuiet >= requiredQuiet;
+ Console.WriteLine($"Decoded CodeText: {result.CodeText}");
+ found = true;
+ break; // Stop after the first successful decode.
+ }
- // Output diagnostic information
- Console.WriteLine($"Image size: {bitmap.Width}x{bitmap.Height} pixels");
- Console.WriteLine($"Detected barcode region: X={region.X}, Y={region.Y}, Width={region.Width}, Height={region.Height}");
- Console.WriteLine($"Quiet zones (pixels) - Left: {leftQuiet}, Top: {topQuiet}, Right: {rightQuiet}, Bottom: {bottomQuiet}");
- Console.WriteLine($"Required quiet zone (pixels): {requiredQuiet}");
- Console.WriteLine(quietOk ? "Quiet zone validation passed." : "Quiet zone validation failed.");
- }
+ if (!found)
+ {
+ Console.WriteLine("Barcode could not be decoded – quiet zone may be insufficient.");
+ }
+ else
+ {
+ Console.WriteLine("Barcode decoded successfully – quiet zone meets requirements.");
}
}
}
diff --git a/two-dimensional-barcode-types/validate-that-generated-maxicode-barcode-complies-with-iso-iec-16023-standard-using-built-in-validator.cs b/two-dimensional-barcode-types/validate-that-generated-maxicode-barcode-complies-with-iso-iec-16023-standard-using-built-in-validator.cs
index d400ac4..cfab0a3 100644
--- a/two-dimensional-barcode-types/validate-that-generated-maxicode-barcode-complies-with-iso-iec-16023-standard-using-built-in-validator.cs
+++ b/two-dimensional-barcode-types/validate-that-generated-maxicode-barcode-complies-with-iso-iec-16023-standard-using-built-in-validator.cs
@@ -1,83 +1,98 @@
+// Title: Validate MaxiCode barcode against ISO/IEC 16023 using Aspose.BarCode validator
+// Description: Demonstrates generating a MaxiCode (Mode 2) barcode, saving it to a PNG stream, and validating its contents with the built‑in MaxiCode validator to ensure compliance with ISO/IEC 16023.
+// 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 for creating a MaxiCode, Image saving via Aspose.Drawing, and BarCodeReader with DecodeType.MaxiCode for decoding. Developers often need to generate MaxiCode for shipping labels and verify the encoded data programmatically; this snippet illustrates the typical workflow and key API classes (ComplexBarcodeGenerator, MaxiCodeCodetextMode2, BarCodeReader, ComplexCodetextReader).
+// Prompt: Validate that the generated MaxiCode barcode complies with ISO/IEC 16023 standard using built‑in validator.
+// Tags: maxicode, barcode, validation, generation, decoding, iso/iec 16023, aspnet, aspose.barcode
+
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.BarCode.ComplexBarcode;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates generation, saving, and validation of a MaxiCode barcode using Aspose.BarCode.
+/// Example program that generates a MaxiCode barcode (Mode 2), saves it to a PNG stream,
+/// and validates the encoded data using Aspose.BarCode's built‑in validator to ensure
+/// compliance with ISO/IEC 16023.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a MaxiCode (Mode 2), saves it to a file, and validates the encoded data.
+ /// Entry point of the example. Performs barcode generation, image handling,
+ /// decoding, and validation of the MaxiCode data.
///
static void Main()
{
- // --------------------------------------------------------------------
- // 1. Prepare the MaxiCode codetext for Mode 2 (postal information + data)
- // --------------------------------------------------------------------
- var maxiCodeCodetext = new MaxiCodeCodetextMode2
+ // ------------------------------------------------------------
+ // 1. Prepare MaxiCode codetext (Mode 2) with a standard second message
+ // ------------------------------------------------------------
+ var maxiCode = new MaxiCodeCodetextMode2
{
PostalCode = "524032140", // 9‑digit US postal code
- CountryCode = 56, // Example country code
- ServiceCategory = 999, // Example service category
- // Standard second message (free‑form text)
- SecondMessage = new MaxiCodeStandardSecondMessage { Message = "Sample MaxiCode message" }
+ CountryCode = 56, // Country code
+ ServiceCategory = 999 // Service category
};
- // --------------------------------------------------------------------
- // 2. Generate the MaxiCode barcode image and write it to a memory stream
- // --------------------------------------------------------------------
- using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
+ var secondMessage = new MaxiCodeStandardSecondMessage
{
- using (var ms = new MemoryStream())
- {
- // Save the generated barcode as PNG into the memory stream
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for subsequent reads
-
- // ----------------------------------------------------------------
- // 3. Optionally write the image to disk for visual inspection
- // ----------------------------------------------------------------
- File.WriteAllBytes("maxicode.png", ms.ToArray());
+ Message = "Test message"
+ };
+ maxiCode.SecondMessage = secondMessage;
- // ----------------------------------------------------------------
- // 4. Recognize the barcode from the memory stream and validate it
- // ----------------------------------------------------------------
- using (var reader = new BarCodeReader(ms, DecodeType.MaxiCode))
+ // ------------------------------------------------------------
+ // 2. Generate the MaxiCode barcode image using ComplexBarcodeGenerator
+ // ------------------------------------------------------------
+ using (var generator = new ComplexBarcodeGenerator(maxiCode))
+ {
+ using (var image = generator.GenerateBarCodeImage())
+ {
+ // ------------------------------------------------------------
+ // 3. Save the image to a memory stream in PNG format
+ // ------------------------------------------------------------
+ using (var ms = new MemoryStream())
{
- // Read all detected barcodes (should be one)
- var results = reader.ReadBarCodes();
+ image.Save(ms, ImageFormat.Png);
+ ms.Position = 0; // Reset stream position for subsequent reading
- if (results.Length == 0)
+ // ------------------------------------------------------------
+ // 4. Validate the generated barcode by decoding it
+ // ------------------------------------------------------------
+ using (var reader = new BarCodeReader(ms, DecodeType.MaxiCode))
{
- Console.WriteLine("No MaxiCode barcode detected.");
- return;
- }
+ bool anyResult = false;
- // Iterate through each detected barcode (normally just one)
- foreach (var result in results)
- {
- // Decode the complex codetext using the built‑in decoder
- var decoded = ComplexCodetextReader.TryDecodeMaxiCode(
- result.Extended.MaxiCode.MaxiCodeMode,
- result.CodeText);
-
- if (decoded != null)
+ foreach (BarCodeResult result in reader.ReadBarCodes())
{
- // Successful validation – output decoded fields
- Console.WriteLine("MaxiCode validation succeeded.");
- Console.WriteLine($"Postal Code: {((MaxiCodeCodetextMode2)decoded).PostalCode}");
- Console.WriteLine($"Country Code: {((MaxiCodeCodetextMode2)decoded).CountryCode}");
- Console.WriteLine($"Service Category: {((MaxiCodeCodetextMode2)decoded).ServiceCategory}");
+ anyResult = true;
+
+ // Decode the complex codetext using the built‑in validator
+ var decoded = ComplexCodetextReader.TryDecodeMaxiCode(
+ result.Extended.MaxiCode.MaxiCodeMode,
+ result.CodeText);
+
+ if (decoded is MaxiCodeCodetextMode2 decodedMode2)
+ {
+ // Compare each field with the original data
+ bool isValid = decodedMode2.PostalCode == maxiCode.PostalCode &&
+ decodedMode2.CountryCode == maxiCode.CountryCode &&
+ decodedMode2.ServiceCategory == maxiCode.ServiceCategory &&
+ ((MaxiCodeStandardSecondMessage)decodedMode2.SecondMessage).Message == secondMessage.Message;
+
+ Console.WriteLine(isValid
+ ? "Validation passed: decoded data matches original."
+ : "Validation failed: decoded data does not match original.");
+ }
+ else
+ {
+ Console.WriteLine("Validation failed: decoded codetext type is not MaxiCodeCodetextMode2.");
+ }
}
- else
+
+ if (!anyResult)
{
- // Decoding failed – barcode does not meet ISO/IEC 16023 spec
- Console.WriteLine("MaxiCode validation failed.");
+ Console.WriteLine("Validation failed: no barcode detected in the generated image.");
}
}
}
diff --git a/two-dimensional-barcode-types/write-documentation-example-showing-how-to-switch-barcode-type-at-runtime-based-on-configuration-file.cs b/two-dimensional-barcode-types/write-documentation-example-showing-how-to-switch-barcode-type-at-runtime-based-on-configuration-file.cs
index d3b9669..cdc58d8 100644
--- a/two-dimensional-barcode-types/write-documentation-example-showing-how-to-switch-barcode-type-at-runtime-based-on-configuration-file.cs
+++ b/two-dimensional-barcode-types/write-documentation-example-showing-how-to-switch-barcode-type-at-runtime-based-on-configuration-file.cs
@@ -1,88 +1,92 @@
+// Title: Runtime Barcode Type Switching Example
+// Description: Demonstrates how to read a barcode type from a JSON configuration file and generate the corresponding barcode at runtime.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating dynamic selection of symbology using EncodeTypes and BarcodeGenerator. Developers often need to switch barcode formats based on external settings such as config files, databases, or user input; this snippet shows how to resolve a symbology name via reflection and produce an image file.
+// Prompt: Write documentation example showing how to switch barcode type at runtime based on configuration file.
+// Tags: barcode symbology, runtime configuration, aspose.barcode, encode types, json, generation, png
+
using System;
using System.IO;
using System.Reflection;
+using System.Text.Json;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-///
-/// Demonstrates reading a simple configuration file and generating a barcode
-/// using Aspose.BarCode based on the specified symbology and text.
-///
-class Program
+namespace BarcodeRuntimeSwitchExample
{
///
- /// Application entry point. Reads configuration, resolves the barcode symbology,
- /// generates the barcode image, and saves it to disk.
+ /// Simple POCO representing the JSON configuration for barcode generation.
///
- static void Main()
+ public class BarcodeConfig
{
- // Path to the simple configuration file
- string configPath = "barcodeConfig.txt";
-
- // Ensure the configuration file exists; create a default one if missing
- if (!File.Exists(configPath))
- {
- // Default configuration: Code128 barcode with sample text
- File.WriteAllText(configPath, "Symbology=Code128\nCodeText=HelloWorld");
- Console.WriteLine($"Created default config file at '{configPath}'.");
- }
-
- // Read all lines from the configuration file
- string[] lines = File.ReadAllLines(configPath);
- string symbologyName = null;
- string codeText = null;
+ public string BarcodeType { get; set; }
+ public string CodeText { get; set; }
+ }
- // Parse each line to extract key/value pairs
- foreach (string line in lines)
+ ///
+ /// Demonstrates runtime selection of barcode symbology based on a JSON configuration file.
+ ///
+ class Program
+ {
+ ///
+ /// Entry point. Reads configuration, resolves barcode type, generates and saves the barcode image.
+ ///
+ static void Main()
{
- // Skip empty lines or lines without an '=' delimiter
- if (string.IsNullOrWhiteSpace(line) || !line.Contains("="))
- continue;
+ // Path to the configuration file
+ const string configPath = "barcodeConfig.json";
- // Split the line into key and value (limit to 2 parts)
- string[] parts = line.Split(new[] { '=' }, 2);
- string key = parts[0].Trim();
- string value = parts[1].Trim();
+ // Ensure a sample configuration exists if the file is missing
+ if (!File.Exists(configPath))
+ {
+ var sampleConfig = new BarcodeConfig
+ {
+ BarcodeType = "Code128", // Name of a field in EncodeTypes
+ CodeText = "Sample123"
+ };
+ var json = JsonSerializer.Serialize(sampleConfig, new JsonSerializerOptions { WriteIndented = true });
+ File.WriteAllText(configPath, json);
+ Console.WriteLine($"Created sample config file at '{configPath}'.");
+ }
- // Assign values based on recognized keys (case‑insensitive)
- if (key.Equals("Symbology", StringComparison.OrdinalIgnoreCase))
- symbologyName = value;
- else if (key.Equals("CodeText", StringComparison.OrdinalIgnoreCase))
- codeText = value;
- }
+ // Read and deserialize the configuration
+ BarcodeConfig config;
+ try
+ {
+ var configJson = File.ReadAllText(configPath);
+ config = JsonSerializer.Deserialize(configJson);
+ if (config == null ||
+ string.IsNullOrWhiteSpace(config.BarcodeType) ||
+ string.IsNullOrWhiteSpace(config.CodeText))
+ {
+ throw new ArgumentException("Configuration file is missing required fields.");
+ }
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Failed to read configuration: {ex.Message}");
+ return;
+ }
- // Validate that required configuration fields were provided
- if (string.IsNullOrEmpty(symbologyName) || string.IsNullOrEmpty(codeText))
- {
- Console.WriteLine("Configuration is missing required fields 'Symbology' or 'CodeText'.");
- return;
- }
+ // Resolve the symbology name to a BaseEncodeType using reflection
+ var fieldInfo = typeof(EncodeTypes).GetField(config.BarcodeType);
+ if (fieldInfo == null)
+ {
+ Console.WriteLine($"Unknown barcode type: '{config.BarcodeType}'.");
+ return;
+ }
- // Resolve the symbology name to a BaseEncodeType using reflection
- FieldInfo field = typeof(EncodeTypes).GetField(symbologyName);
- if (field == null)
- {
- Console.WriteLine($"Unknown symbology: {symbologyName}");
- return;
- }
+ var encodeType = (BaseEncodeType)fieldInfo.GetValue(null);
- // Cast the reflected field value to the appropriate enum type
- BaseEncodeType encodeType = (BaseEncodeType)field.GetValue(null);
+ // Generate the barcode based on the runtime configuration
+ using (var generator = new BarcodeGenerator(encodeType))
+ {
+ generator.CodeText = config.CodeText;
- // Define the output file path for the generated barcode image
- string outputPath = "generated_barcode.png";
-
- // Create a barcode generator with the resolved type and provided text
- using (var generator = new BarcodeGenerator(encodeType, codeText))
- {
- // Example: set a simple property (optional)
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
-
- // Save the generated barcode image to the specified file
- generator.Save(outputPath);
+ // Save the barcode image; filename includes the barcode type for clarity
+ string outputFile = $"barcode_{config.BarcodeType}.png";
+ generator.Save(outputFile);
+ Console.WriteLine($"Barcode saved to '{outputFile}'.");
+ }
}
-
- // Inform the user that the barcode has been generated
- Console.WriteLine($"Barcode generated: {outputPath}");
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/write-integration-test-confirming-linear-component-type-changes-reflect-correctly-in-final-gs1-composite-image.cs b/two-dimensional-barcode-types/write-integration-test-confirming-linear-component-type-changes-reflect-correctly-in-final-gs1-composite-image.cs
index ea0249b..40eae0b 100644
--- a/two-dimensional-barcode-types/write-integration-test-confirming-linear-component-type-changes-reflect-correctly-in-final-gs1-composite-image.cs
+++ b/two-dimensional-barcode-types/write-integration-test-confirming-linear-component-type-changes-reflect-correctly-in-final-gs1-composite-image.cs
@@ -1,113 +1,93 @@
+// Title: GS1 Composite Barcode Linear Component Type Integration Test
+// Description: Demonstrates how changing the linear component type in a GS1 Composite barcode affects the generated image, useful for integration testing.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, focusing on GS1 Composite barcodes. It showcases the use of BarcodeGenerator, EncodeTypes, and TwoDComponentType to create composite barcodes with different linear components. Developers often need to verify that configuration changes produce distinct outputs, especially when automating tests for barcode rendering pipelines.
+// Prompt: Write integration test confirming linear component type changes reflect correctly in the final GS1 Composite image.
+// Tags: gs1 composite barcode, linear component, encode types, integration test, aspose.barcode, csharp
+
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates generation and verification of GS1 Composite barcodes
-/// using different linear component types (GS1Code128 and UPCA).
+/// Contains an integration test that verifies changing the linear component type of a GS1 Composite barcode
+/// results in distinct generated images.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates two GS1 Composite barcodes with different linear components,
- /// compares the resulting images, and verifies the encoded data.
+ /// Entry point of the test application. Generates two GS1 Composite barcodes with different linear components,
+ /// saves them, and checks that the output files differ in size.
///
static void Main()
{
- // Sample GS1 Composite codetext: linear part and 2D part separated by '|'
- string codetext = "(01)03212345678906|(21)A1B2C3D4E5F6G7H8";
-
- // Create a temporary directory for output images
- string outputDir = Path.Combine(Path.GetTempPath(), "Gs1CompositeTest");
- Directory.CreateDirectory(outputDir);
+ // --------------------------------------------------------------------
+ // Prepare output directory for generated barcode images
+ // --------------------------------------------------------------------
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "GS1CompositeTest");
+ if (!Directory.Exists(outputDir))
+ {
+ Directory.CreateDirectory(outputDir);
+ }
- // Define full paths for the generated barcode images
- string imgPathGs1Code128 = Path.Combine(outputDir, "gs1code128.png");
- string imgPathUpca = Path.Combine(outputDir, "upca.png");
+ // --------------------------------------------------------------------
+ // Define common GS1 Composite codetext (1D|2D parts)
+ // --------------------------------------------------------------------
+ string codeText = "(01)03212345678906|(21)A1B2C3D4E5F6G7H8";
- // Generate barcode with LinearComponentType = GS1Code128
- GenerateGs1Composite(codetext, EncodeTypes.GS1Code128, imgPathGs1Code128);
- // Generate barcode with LinearComponentType = UPCA
- GenerateGs1Composite(codetext, EncodeTypes.UPCA, imgPathUpca);
+ // --------------------------------------------------------------------
+ // First barcode: Linear component set to GS1Code128
+ // --------------------------------------------------------------------
+ string filePath1 = Path.Combine(outputDir, "Composite_GS1Code128.png");
+ using (var generator = new BarcodeGenerator(EncodeTypes.GS1CompositeBar, codeText))
+ {
+ // Set linear and 2D component types
+ generator.Parameters.Barcode.GS1CompositeBar.LinearComponentType = EncodeTypes.GS1Code128;
+ generator.Parameters.Barcode.GS1CompositeBar.TwoDComponentType = TwoDComponentType.CC_A;
- // Verify that the two images are different (different linear component)
- bool imagesDiffer = !File.ReadAllBytes(imgPathGs1Code128)
- .SequenceEqual(File.ReadAllBytes(imgPathUpca));
- Console.WriteLine($"Images differ after changing LinearComponentType: {imagesDiffer}");
+ // Configure size and appearance for a fair comparison
+ generator.Parameters.Barcode.Pdf417.AspectRatio = 3f;
+ generator.Parameters.Barcode.XDimension.Pixels = 3f;
+ generator.Parameters.Barcode.BarHeight.Pixels = 100f;
- // Read back the first barcode and verify codetext
- VerifyBarcode(imgPathGs1Code128, codetext);
- // Read back the second barcode and verify codetext
- VerifyBarcode(imgPathUpca, codetext);
- }
+ // Save the generated image
+ generator.Save(filePath1);
+ }
- ///
- /// Generates a GS1 Composite barcode image using the specified linear component type.
- ///
- /// The GS1 Composite codetext to encode.
- /// The linear component type (e.g., GS1Code128, UPCA).
- /// File path where the generated image will be saved.
- static void GenerateGs1Composite(string codeText, BaseEncodeType linearType, string outputPath)
- {
- // Initialize the barcode generator for GS1 Composite symbology
+ // --------------------------------------------------------------------
+ // Second barcode: Linear component set to EAN13
+ // --------------------------------------------------------------------
+ string filePath2 = Path.Combine(outputDir, "Composite_EAN13.png");
using (var generator = new BarcodeGenerator(EncodeTypes.GS1CompositeBar, codeText))
{
- // Set the linear component type (GS1Code128, UPCA, etc.)
- generator.Parameters.Barcode.GS1CompositeBar.LinearComponentType = linearType;
-
- // Use a simple 2D component type (CC-A)
+ // Set linear and 2D component types
+ generator.Parameters.Barcode.GS1CompositeBar.LinearComponentType = EncodeTypes.EAN13;
generator.Parameters.Barcode.GS1CompositeBar.TwoDComponentType = TwoDComponentType.CC_A;
- // Optional visual settings for better readability
- generator.Parameters.Barcode.Pdf417.AspectRatio = 3;
- generator.Parameters.Barcode.XDimension.Pixels = 3;
- generator.Parameters.Barcode.BarHeight.Pixels = 100;
+ // Apply the same size settings for comparison
+ generator.Parameters.Barcode.Pdf417.AspectRatio = 3f;
+ generator.Parameters.Barcode.XDimension.Pixels = 3f;
+ generator.Parameters.Barcode.BarHeight.Pixels = 100f;
- // Save the generated barcode image to the specified path
- generator.Save(outputPath);
+ // Save the generated image
+ generator.Save(filePath2);
}
- }
- ///
- /// Reads a barcode image, decodes its content, and verifies it against the expected codetext.
- ///
- /// Path to the barcode image file.
- /// The expected codetext to compare against.
- static void VerifyBarcode(string imagePath, string expectedCodeText)
- {
- // Ensure the image file exists before attempting to read it
- if (!File.Exists(imagePath))
+ // --------------------------------------------------------------------
+ // Verify that the two generated images differ (e.g., by file size)
+ // --------------------------------------------------------------------
+ long size1 = new FileInfo(filePath1).Length;
+ long size2 = new FileInfo(filePath2).Length;
+
+ if (size1 != size2)
{
- Console.WriteLine($"File not found: {imagePath}");
- return;
+ Console.WriteLine("Test passed: Linear component type change reflected in the generated images.");
+ Console.WriteLine($"Image 1 ({Path.GetFileName(filePath1)}) size: {size1} bytes");
+ Console.WriteLine($"Image 2 ({Path.GetFileName(filePath2)}) size: {size2} bytes");
}
-
- // Initialize the barcode reader for GS1 Composite symbology
- using (var reader = new BarCodeReader(imagePath, DecodeType.GS1CompositeBar))
+ else
{
- // Read all barcodes present in the image
- var results = reader.ReadBarCodes();
-
- // If no barcodes were detected, report and exit
- if (results.Length == 0)
- {
- Console.WriteLine($"No barcode detected in {Path.GetFileName(imagePath)}");
- return;
- }
-
- // Iterate through each detected barcode (typically only one)
- foreach (var result in results)
- {
- Console.WriteLine($"Decoded from {Path.GetFileName(imagePath)}: {result.CodeText}");
-
- // Compare the decoded text with the expected codetext (case-sensitive)
- bool match = string.Equals(result.CodeText, expectedCodeText, StringComparison.Ordinal);
- Console.WriteLine($"Codetext matches expected: {match}");
- }
+ Console.WriteLine("Test failed: Images have identical size, change may not be reflected.");
}
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/write-integration-test-ensuring-barcode-image-stream-can-be-directly-written-to-azure-blob-storage.cs b/two-dimensional-barcode-types/write-integration-test-ensuring-barcode-image-stream-can-be-directly-written-to-azure-blob-storage.cs
index 33cb181..f34ebe3 100644
--- a/two-dimensional-barcode-types/write-integration-test-ensuring-barcode-image-stream-can-be-directly-written-to-azure-blob-storage.cs
+++ b/two-dimensional-barcode-types/write-integration-test-ensuring-barcode-image-stream-can-be-directly-written-to-azure-blob-storage.cs
@@ -1,37 +1,34 @@
+// Title: Generate Barcode and Save to Stream for Azure Blob Upload
+// Description: Demonstrates generating a Code128 barcode, storing it in a memory stream, and preparing it for direct upload to Azure Blob storage.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to create barcode images using the BarcodeGenerator class, save them in-memory with BarCodeImageFormat, and integrate with cloud storage services such as Azure Blob Storage. Developers often need to produce barcodes on-the-fly and upload them without intermediate files; this snippet illustrates the typical workflow and key API classes for such scenarios, making it searchable for integration testing and CI pipelines.
+// Prompt: Write integration test ensuring barcode image stream can be directly written to Azure Blob storage.
+// Tags: barcode, code128, generation, png, memorystream, azure blob, aspose.barcode, integration test
+
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating a Code128 barcode, saving it to a memory stream,
-/// and then persisting the image either to Azure Blob Storage (commented example)
-/// or to a local temporary file.
+/// Example program that generates a Code128 barcode, writes it to a memory stream,
+/// and demonstrates how the stream could be uploaded to Azure Blob storage.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a barcode, writes it to a stream, and saves the image locally.
+ /// Entry point of the example. Generates the barcode, resets the stream,
+ /// and saves the image locally (simulating a blob upload).
///
static void Main()
{
- // Define barcode type and content.
- BaseEncodeType encodeType = EncodeTypes.Code128;
- string codeText = "Test123";
-
- // Create a memory stream to hold the generated barcode image.
+ // Create a memory stream to hold the barcode image.
using (var memoryStream = new MemoryStream())
{
- // Initialize the barcode generator with the specified type and text.
- using (var generator = new BarcodeGenerator(encodeType, codeText))
+ // Initialize the barcode generator with the desired symbology and data.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Test123"))
{
- // Set optional parameters, e.g., image resolution.
- generator.Parameters.Resolution = 300f;
-
- // Save the barcode directly into the memory stream in PNG format.
+ // Save the generated barcode directly into the memory stream in PNG format.
generator.Save(memoryStream, BarCodeImageFormat.Png);
}
@@ -39,38 +36,32 @@ static void Main()
memoryStream.Position = 0;
// -----------------------------------------------------------------
- // Azure Blob Storage upload (example – requires Azure.Storage.Blobs SDK)
+ // Azure Blob Storage upload simulation (commented out for test env)
// -----------------------------------------------------------------
/*
- string connectionString = "";
+ // Uncomment and add the Azure.Storage.Blobs NuGet package to enable real upload.
+ string connectionString = "";
string containerName = "barcodes";
- string blobName = "code128.png";
+ string blobName = "barcode.png";
- var blobServiceClient = new Azure.Storage.Blobs.BlobServiceClient(connectionString);
+ var blobServiceClient = new BlobServiceClient(connectionString);
var containerClient = blobServiceClient.GetBlobContainerClient(containerName);
containerClient.CreateIfNotExists();
var blobClient = containerClient.GetBlobClient(blobName);
- memoryStream.Position = 0; // Ensure stream is at the beginning
+ memoryStream.Position = 0; // Ensure stream is at start before upload.
blobClient.Upload(memoryStream, overwrite: true);
- Console.WriteLine($"Barcode uploaded to Azure Blob: {blobClient.Uri}");
*/
- // -----------------------------------------------------------------
- // Fallback: write the barcode image to a local temporary file.
- // -----------------------------------------------------------------
- string localPath = Path.Combine(Path.GetTempPath(), "code128.png");
-
- // Create a file stream for writing the image to disk.
+ // For the purpose of this test environment, write the stream to a local file.
+ string localPath = Path.Combine(Directory.GetCurrentDirectory(), "barcode.png");
using (var fileStream = new FileStream(localPath, FileMode.Create, FileAccess.Write))
{
- // Ensure the memory stream is positioned at the start before copying.
- memoryStream.Position = 0;
memoryStream.CopyTo(fileStream);
}
- // Inform the user where the image was saved.
- Console.WriteLine($"Barcode image saved locally at: {localPath}");
+ // Inform the user where the file was saved.
+ Console.WriteLine($"Barcode image saved to: {localPath}");
}
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/write-integration-test-verifying-barcode-image-can-be-decoded-back-to-original-data-using-third-party-scanner-library.cs b/two-dimensional-barcode-types/write-integration-test-verifying-barcode-image-can-be-decoded-back-to-original-data-using-third-party-scanner-library.cs
index e6b2be3..4a8a97f 100644
--- a/two-dimensional-barcode-types/write-integration-test-verifying-barcode-image-can-be-decoded-back-to-original-data-using-third-party-scanner-library.cs
+++ b/two-dimensional-barcode-types/write-integration-test-verifying-barcode-image-can-be-decoded-back-to-original-data-using-third-party-scanner-library.cs
@@ -1,83 +1,64 @@
+// Title: Integration test for barcode generation and verification
+// Description: Generates a Code128 barcode, decodes it, and verifies the decoded data matches the original input.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It demonstrates how to use BarcodeGenerator to create a barcode image and BarCodeReader to decode it. Developers commonly need to validate that generated barcodes can be read by third‑party scanners, ensuring interoperability in inventory, logistics, and retail applications.
+// Prompt: Write integration test verifying barcode image can be decoded back to original data using third‑party scanner library.
+// Tags: code128, generation, recognition, png, aspose.barcode, integration-test, barcode
+
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Demonstrates generating a Code128 barcode, saving it to a temporary file,
-/// decoding it back, and verifying the result using Aspose.BarCode.
+/// Demonstrates an integration test that generates a barcode, decodes it, and validates the result.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a barcode, decodes it, compares with original text, and cleans up.
+ /// Entry point of the test. Generates a Code128 barcode, reads it back, and checks the decoded text.
///
static void Main()
{
- // Define the text that will be encoded into the barcode.
+ // Sample data to encode
const string originalText = "Test12345";
- // Build a temporary file path for the barcode image.
- string tempImagePath = Path.Combine(Path.GetTempPath(), "temp_barcode.png");
-
- // ------------------------------------------------------------
- // Generate the barcode image using Aspose.BarCode.
- // ------------------------------------------------------------
+ // Create a barcode generator for Code128 with the sample data
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, originalText))
{
- // Set image resolution (dots per inch) – optional but improves quality.
- generator.Parameters.Resolution = 300f;
+ // Save the generated barcode to a memory stream in PNG format
+ using (var ms = new MemoryStream())
+ {
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0; // Reset stream position for reading
- // Save the generated barcode as a PNG file.
- generator.Save(tempImagePath, BarCodeImageFormat.Png);
- }
+ // Initialize a barcode reader that supports all available symbologies
+ using (var reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes))
+ {
+ // Read all barcodes found in the image
+ var results = reader.ReadBarCodes();
- // Verify that the image file was successfully created.
- if (!File.Exists(tempImagePath))
- {
- Console.WriteLine("Failed to create barcode image.");
- return;
- }
+ // If no barcode is detected, report and exit
+ if (results.Length == 0)
+ {
+ Console.WriteLine("No barcode detected.");
+ return;
+ }
- // ------------------------------------------------------------
- // Decode the barcode.
- // In a real project you might use a different library (e.g., ZXing.Net).
- // Here we use Aspose.BarCode for simplicity.
- // ------------------------------------------------------------
- string decodedText = null;
- using (var reader = new BarCodeReader(tempImagePath, DecodeType.AllSupportedTypes))
- {
- // Read all barcodes found in the image; we expect only one.
- foreach (BarCodeResult result in reader.ReadBarCodes())
- {
- decodedText = result.CodeText;
- break; // Stop after the first barcode.
- }
- }
+ // Take the first detected barcode (the one we generated)
+ var decodedText = results[0].CodeText;
- // Compare the decoded text with the original text and output the result.
- if (decodedText == originalText)
- {
- Console.WriteLine("Success: Decoded text matches original.");
- }
- else
- {
- Console.WriteLine($"Failure: Decoded text '{decodedText ?? "null"}' does not match original '{originalText}'.");
- }
-
- // ------------------------------------------------------------
- // Clean up: delete the temporary barcode image file.
- // ------------------------------------------------------------
- try
- {
- File.Delete(tempImagePath);
- }
- catch
- {
- // Suppress any exceptions during cleanup.
+ // Compare the decoded text with the original input
+ if (decodedText == originalText)
+ {
+ Console.WriteLine("Success: Decoded text matches original.");
+ }
+ else
+ {
+ Console.WriteLine($"Failure: Decoded text '{decodedText}' does not match original '{originalText}'.");
+ }
+ }
+ }
}
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/write-performance-benchmark-measuring-time-to-generate-10-000-datamatrix-barcodes-in-parallel.cs b/two-dimensional-barcode-types/write-performance-benchmark-measuring-time-to-generate-10-000-datamatrix-barcodes-in-parallel.cs
index f8fe370..b7aee95 100644
--- a/two-dimensional-barcode-types/write-performance-benchmark-measuring-time-to-generate-10-000-datamatrix-barcodes-in-parallel.cs
+++ b/two-dimensional-barcode-types/write-performance-benchmark-measuring-time-to-generate-10-000-datamatrix-barcodes-in-parallel.cs
@@ -1,52 +1,60 @@
+// Title: Parallel generation of DataMatrix barcodes benchmark
+// Description: Demonstrates measuring the time required to generate a large number of DataMatrix barcodes concurrently.
+// Category-Description: This example belongs to the Aspose.BarCode performance benchmarking category, showcasing how to use BarcodeGenerator, EncodeTypes, and image handling classes (Bitmap, ImageFormat) to create barcodes in parallel. Developers often need to assess throughput when generating thousands of barcodes for batch processing, printing, or inventory systems. The snippet illustrates typical use of Parallel.For, Stopwatch, and memory streams for high‑volume barcode creation.
+// Prompt: Write performance benchmark measuring time to generate 10,000 DataMatrix barcodes in parallel.
+// Tags: datamatrix, performance, benchmark, parallel, generation, aspose.barcode, bitmap, png
+
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
+using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Demonstrates parallel generation of DataMatrix barcodes using Aspose.BarCode.
+/// Provides a simple performance benchmark that generates a configurable number of DataMatrix barcodes in parallel
+/// and reports the elapsed time. Useful for evaluating throughput of the Aspose.BarCode generation API.
///
class Program
{
///
- /// Entry point of the application. Generates a set number of barcodes in parallel and measures execution time.
+ /// Entry point of the benchmark application.
+ /// Accepts an optional command‑line argument specifying how many barcodes to generate (default is 10).
///
- static void Main()
+ /// Command‑line arguments; first argument may be an integer count.
+ static void Main(string[] args)
{
- // Number of barcodes to generate; kept small for sample runner constraints
- const int barcodeCount = 10;
+ // Determine how many barcodes to generate; default to 10 for quick execution.
+ int barcodeCount = 10;
+ if (args.Length > 0 && int.TryParse(args[0], out int parsed) && parsed > 0)
+ {
+ barcodeCount = parsed;
+ }
- // Stopwatch to measure total generation time
- var stopwatch = new Stopwatch();
- stopwatch.Start();
+ // Start measuring elapsed time.
+ var stopwatch = Stopwatch.StartNew();
- // Parallel loop to generate barcodes concurrently
+ // Generate barcodes concurrently using Parallel.For for maximum CPU utilization.
Parallel.For(0, barcodeCount, i =>
{
- // Create a new barcode generator for each iteration to avoid shared state
- using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, $"Data{i:D4}"))
+ // Create a DataMatrix generator with a unique code text for each iteration.
+ using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, $"Sample{i:D5}"))
{
- // Use a memory stream to hold the generated PNG image (no disk I/O)
- using (var ms = new MemoryStream())
+ // Produce the barcode image as a Bitmap.
+ using (Bitmap bitmap = generator.GenerateBarCodeImage())
{
- // Save the barcode image into the memory stream
- generator.Save(ms, BarCodeImageFormat.Png);
-
- // Reset stream position to the beginning for any subsequent read operations
- ms.Position = 0;
- } // MemoryStream disposed here
- } // BarcodeGenerator disposed here
+ // Encode the bitmap to PNG format via a memory stream (forces image encoding).
+ using (var ms = new MemoryStream())
+ {
+ bitmap.Save(ms, ImageFormat.Png);
+ }
+ }
+ }
});
- // Stop timing after all parallel tasks complete
+ // Stop timing and output the result.
stopwatch.Stop();
-
- // Output results to console
- Console.WriteLine($"Generated {barcodeCount} DataMatrix barcodes in parallel.");
- Console.WriteLine($"Elapsed time: {stopwatch.ElapsedMilliseconds} ms");
+ Console.WriteLine($"Generated {barcodeCount} DataMatrix barcodes in {stopwatch.ElapsedMilliseconds} ms.");
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/write-sample-console-program-that-accepts-command-line-arguments-for-barcode-type-data-and-output-path.cs b/two-dimensional-barcode-types/write-sample-console-program-that-accepts-command-line-arguments-for-barcode-type-data-and-output-path.cs
index 2e1be74..82b908a 100644
--- a/two-dimensional-barcode-types/write-sample-console-program-that-accepts-command-line-arguments-for-barcode-type-data-and-output-path.cs
+++ b/two-dimensional-barcode-types/write-sample-console-program-that-accepts-command-line-arguments-for-barcode-type-data-and-output-path.cs
@@ -1,3 +1,9 @@
+// Title: Generate barcode image from command‑line arguments
+// Description: Demonstrates how to create a barcode image using Aspose.BarCode by specifying symbology, data, and output path via command‑line.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and BaseEncodeType to produce barcode images. Typical use cases include automating barcode creation in batch scripts, CI pipelines, or backend services where input parameters are supplied at runtime. Developers often need to map symbology names to EncodeTypes and ensure output directories exist.
+// Prompt: Write a sample console program that accepts command‑line arguments for barcode type, data, and output path.
+// Tags: barcode generation command-line symbology encode-types output-file aspose.barcode
+
using System;
using System.IO;
using System.Reflection;
@@ -5,71 +11,61 @@
using Aspose.BarCode.Generation;
///
-/// Demonstrates generating a barcode image using Aspose.BarCode based on command‑line arguments.
+/// Sample console application that generates a barcode image based on command‑line arguments.
///
class Program
{
///
- /// Entry point of the application.
- /// Accepts optional arguments: symbology name, code text, and output file path.
- /// Generates the specified barcode and saves it to the given location.
+ /// Entry point of the program.
+ /// Accepts three optional arguments: symbology name, data to encode, and output file path.
+ /// Returns 0 on success, 1 on error.
///
- ///
- /// args[0] – symbology name (e.g., "Code128").
- /// args[1] – text to encode in the barcode.
- /// args[2] – output file path for the generated image.
- ///
- static void Main(string[] args)
+ /// Command‑line arguments.
+ /// Exit code indicating success or failure.
+ static int Main(string[] args)
{
- // Determine symbology, text, and output path, using defaults when arguments are missing.
+ // --------------------------------------------------------------------
+ // Resolve input arguments or fall back to default values
+ // --------------------------------------------------------------------
string symbologyName = args.Length > 0 ? args[0] : "Code128";
string codeText = args.Length > 1 ? args[1] : "Sample123";
string outputPath = args.Length > 2 ? args[2] : "barcode.png";
- // Resolve the symbology name to a BaseEncodeType enum value via reflection.
- FieldInfo field = typeof(EncodeTypes).GetField(symbologyName,
- BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase);
+ // --------------------------------------------------------------------
+ // Convert the symbology name to the corresponding EncodeTypes value using reflection
+ // --------------------------------------------------------------------
+ FieldInfo field = typeof(EncodeTypes).GetField(symbologyName);
if (field == null)
{
- Console.WriteLine($"Unknown barcode type: {symbologyName}");
- return;
+ Console.WriteLine($"Unknown symbology: {symbologyName}");
+ return 1;
}
- // Retrieve the enum value from the reflected field.
BaseEncodeType encodeType = (BaseEncodeType)field.GetValue(null);
if (encodeType == null)
{
Console.WriteLine($"Failed to obtain encode type for: {symbologyName}");
- return;
+ return 1;
}
- // Ensure the directory for the output file exists; create it if necessary.
- try
- {
- string directory = Path.GetDirectoryName(Path.GetFullPath(outputPath));
- if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
- {
- Directory.CreateDirectory(directory);
- }
- }
- catch (Exception ex)
+ // --------------------------------------------------------------------
+ // Ensure the directory for the output file exists
+ // --------------------------------------------------------------------
+ string? directory = Path.GetDirectoryName(outputPath);
+ if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
{
- Console.WriteLine($"Error preparing output directory: {ex.Message}");
- return;
+ Directory.CreateDirectory(directory);
}
- // Create a barcode generator, generate the image, and save it to the specified path.
- using (var generator = new BarcodeGenerator(encodeType, codeText))
+ // --------------------------------------------------------------------
+ // Generate the barcode and save it to the specified path
+ // --------------------------------------------------------------------
+ using (BarcodeGenerator generator = new BarcodeGenerator(encodeType, codeText))
{
- try
- {
- generator.Save(outputPath);
- Console.WriteLine($"Barcode saved to: {outputPath}");
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Error generating barcode: {ex.Message}");
- }
+ generator.Save(outputPath);
}
+
+ Console.WriteLine($"Barcode saved to: {outputPath}");
+ return 0;
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/write-unit-test-confirming-that-changing-module-size-alters-overall-han-xin-barcode-dimensions-proportionally.cs b/two-dimensional-barcode-types/write-unit-test-confirming-that-changing-module-size-alters-overall-han-xin-barcode-dimensions-proportionally.cs
index b426fda..5518500 100644
--- a/two-dimensional-barcode-types/write-unit-test-confirming-that-changing-module-size-alters-overall-han-xin-barcode-dimensions-proportionally.cs
+++ b/two-dimensional-barcode-types/write-unit-test-confirming-that-changing-module-size-alters-overall-han-xin-barcode-dimensions-proportionally.cs
@@ -1,97 +1,92 @@
+// Title: Han Xin barcode module size scaling verification
+// Description: Demonstrates how changing the XDimension (module size) of a Han Xin barcode proportionally affects its overall image dimensions.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on Han Xin symbology. It showcases the use of BarcodeGenerator, EncodeTypes, and barcode parameters such as XDimension to control module size. Developers often need to adjust module size for different printing resolutions or layout requirements, and this snippet illustrates the expected proportional scaling of width and height when the module size changes.
+// Prompt: Write unit test confirming that changing module size alters overall Han Xin barcode dimensions proportionally.
+// Tags: hanxin, barcode, module-size, scaling, generation, aspose.barcode, unit-test
+
using System;
-using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates how Han Xin barcode dimensions scale with different module sizes (XDimension).
+/// Generates two Han Xin barcodes with different module sizes and verifies that the image dimensions scale proportionally.
///
class Program
{
///
- /// Entry point of the application. Generates two Han Xin barcodes with different XDimension values
- /// and verifies that their dimensions scale proportionally.
+ /// Entry point of the example. Creates barcodes, measures dimensions, and checks scaling factors.
///
static void Main()
{
- // Sample code text for Han Xin barcode
- const string codeText = "1234567890";
-
- // First module size (XDimension) in points
- float xDim1 = 2f;
- // Second module size (double the first)
- float xDim2 = 4f;
+ // Sample text to encode in the Han Xin barcode
+ const string codeText = "1234567890ABCDEFGabcdefg,Han Xin Code";
- // Variables to hold dimensions of the first generated barcode
+ // --------------------------------------------------------------------
+ // First barcode generation using a base XDimension (module size)
+ // --------------------------------------------------------------------
+ float xDim1 = 2f; // module size in points
int width1, height1;
-
- // Generate first barcode image with XDimension = xDim1
- using (var generator = new BarcodeGenerator(EncodeTypes.HanXin, codeText))
+ using (var generator1 = new BarcodeGenerator(EncodeTypes.HanXin, codeText))
{
- // Disable automatic sizing to use explicit XDimension
- generator.Parameters.AutoSizeMode = AutoSizeMode.None;
- // Set module size for the barcode
- generator.Parameters.Barcode.XDimension.Point = xDim1;
+ // Apply the base XDimension to the barcode parameters
+ generator1.Parameters.Barcode.XDimension.Point = xDim1;
- // Render barcode to a memory stream in PNG format
- using (var ms = new MemoryStream())
+ // Generate the barcode image and capture its dimensions
+ using (var image1 = generator1.GenerateBarCodeImage())
{
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for reading
-
- // Load the image from the stream to obtain its dimensions
- using (var bitmap = new Bitmap(ms))
- {
- width1 = bitmap.Width;
- height1 = bitmap.Height;
- }
+ width1 = image1.Width;
+ height1 = image1.Height;
}
}
- // Variables to hold dimensions of the second generated barcode
+ // --------------------------------------------------------------------
+ // Second barcode generation using a doubled XDimension
+ // --------------------------------------------------------------------
+ float xDim2 = 4f; // double the base module size
int width2, height2;
-
- // Generate second barcode image with XDimension = xDim2
- using (var generator = new BarcodeGenerator(EncodeTypes.HanXin, codeText))
+ using (var generator2 = new BarcodeGenerator(EncodeTypes.HanXin, codeText))
{
- // Disable automatic sizing to use explicit XDimension
- generator.Parameters.AutoSizeMode = AutoSizeMode.None;
- // Set a larger module size for the barcode
- generator.Parameters.Barcode.XDimension.Point = xDim2;
+ // Apply the larger XDimension to the barcode parameters
+ generator2.Parameters.Barcode.XDimension.Point = xDim2;
- // Render barcode to a memory stream in PNG format
- using (var ms = new MemoryStream())
+ // Generate the barcode image and capture its dimensions
+ using (var image2 = generator2.GenerateBarCodeImage())
{
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for reading
-
- // Load the image from the stream to obtain its dimensions
- using (var bitmap = new Bitmap(ms))
- {
- width2 = bitmap.Width;
- height2 = bitmap.Height;
- }
+ width2 = image2.Width;
+ height2 = image2.Height;
}
}
- // Verify proportionality of dimensions (allow small rounding differences)
- bool widthProportional = Math.Abs((double)width2 * xDim1 - (double)width1 * xDim2) <= 2.0;
- bool heightProportional = Math.Abs((double)height2 * xDim1 - (double)height1 * xDim2) <= 2.0;
+ // --------------------------------------------------------------------
+ // Compute expected scaling factor based on XDimension change
+ // --------------------------------------------------------------------
+ float expectedFactor = xDim2 / xDim1;
+
+ // Actual scaling factors derived from image dimensions
+ float widthFactor = (float)width2 / width1;
+ float heightFactor = (float)height2 / height1;
+
+ // Allow a small tolerance (5%) to accommodate rounding differences
+ const float tolerance = 0.05f;
+
+ bool widthMatches = Math.Abs(widthFactor - expectedFactor) <= tolerance;
+ bool heightMatches = Math.Abs(heightFactor - expectedFactor) <= tolerance;
- // Output result based on proportionality check
- if (widthProportional && heightProportional)
+ // --------------------------------------------------------------------
+ // Output test result
+ // --------------------------------------------------------------------
+ if (widthMatches && heightMatches)
{
- Console.WriteLine("PASS: Barcode dimensions scale proportionally with module size.");
- Console.WriteLine($"Size1 (XDim={xDim1}): {width1}x{height1}");
- Console.WriteLine($"Size2 (XDim={xDim2}): {width2}x{height2}");
+ Console.WriteLine("PASSED: Module size change scaled dimensions proportionally.");
+ Console.WriteLine($"XDimension {xDim1} -> {xDim2}, Width {width1} -> {width2}, Height {height1} -> {height2}");
}
else
{
- Console.WriteLine("FAILED: Barcode dimensions do not scale proportionally.");
- Console.WriteLine($"Size1 (XDim={xDim1}): {width1}x{height1}");
- Console.WriteLine($"Size2 (XDim={xDim2}): {width2}x{height2}");
+ Console.WriteLine("FAILED: Dimensions did not scale as expected.");
+ Console.WriteLine($"Expected factor: {expectedFactor}");
+ Console.WriteLine($"Width factor: {widthFactor} (match: {widthMatches})");
+ Console.WriteLine($"Height factor: {heightFactor} (match: {heightMatches})");
}
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/write-unit-test-ensuring-dotcode-margin-property-correctly-influences-surrounding-whitespace.cs b/two-dimensional-barcode-types/write-unit-test-ensuring-dotcode-margin-property-correctly-influences-surrounding-whitespace.cs
index 0d66e0f..2fb4971 100644
--- a/two-dimensional-barcode-types/write-unit-test-ensuring-dotcode-margin-property-correctly-influences-surrounding-whitespace.cs
+++ b/two-dimensional-barcode-types/write-unit-test-ensuring-dotcode-margin-property-correctly-influences-surrounding-whitespace.cs
@@ -1,128 +1,92 @@
+// Title: DotCode Margin Influence Test
+// Description: Demonstrates how the DotCode barcode margin property adds whitespace around the generated image.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on margin and padding settings for 2D symbologies like DotCode. It showcases the use of BarcodeGenerator, EncodeTypes, and BarcodeParameters to control image dimensions, a common requirement for developers needing precise layout control in reports or UI components.
+// Prompt: Write unit test ensuring DotCode margin property correctly influences surrounding whitespace.
+// Tags: dotcode, margin, padding, barcode, generation, unit-test, aspnet, aspose.barcode
+
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Demonstrates generation of a DotCode barcode with custom padding,
-/// then validates that the padding is reflected in the resulting image.
+/// Provides a console application that verifies the effect of the DotCode margin property on image size.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a barcode, reads its dimensions, and verifies padding.
+ /// Generates a DotCode barcode bitmap with specified padding (in points).
///
- static void Main()
+ /// The text to encode in the barcode.
+ /// Left padding in points.
+ /// Top padding in points.
+ /// Right padding in points.
+ /// Bottom padding in points.
+ /// A containing the generated barcode.
+ static Bitmap GenerateDotCode(string codeText, float left, float top, float right, float bottom)
{
- // --------------------------------------------------------------------
- // Define test parameters
- // --------------------------------------------------------------------
- const string codeText = "123456"; // Text to encode in the barcode
- const float paddingPoints = 20f; // Desired margin (padding) in points
- const string outputPath = "dotcode_test.png"; // Output image file name
-
- // --------------------------------------------------------------------
- // Generate DotCode barcode with the specified padding
- // --------------------------------------------------------------------
+ // Create a generator for the DotCode symbology.
using (var generator = new BarcodeGenerator(EncodeTypes.DotCode, codeText))
{
- // Apply uniform padding (margin) on all four sides
- generator.Parameters.Barcode.Padding.Left.Point = paddingPoints;
- generator.Parameters.Barcode.Padding.Top.Point = paddingPoints;
- generator.Parameters.Barcode.Padding.Right.Point = paddingPoints;
- generator.Parameters.Barcode.Padding.Bottom.Point = paddingPoints;
+ // Disable automatic sizing to keep padding effects visible.
+ generator.Parameters.AutoSizeMode = AutoSizeMode.None;
- // Save the generated barcode image as PNG
- generator.Save(outputPath, BarCodeImageFormat.Png);
- }
+ // Apply the specified padding (margin) values.
+ generator.Parameters.Barcode.Padding.Left.Point = left;
+ generator.Parameters.Barcode.Padding.Top.Point = top;
+ generator.Parameters.Barcode.Padding.Right.Point = right;
+ generator.Parameters.Barcode.Padding.Bottom.Point = bottom;
- // --------------------------------------------------------------------
- // Load the generated image to obtain its pixel dimensions
- // --------------------------------------------------------------------
- int imageWidthPixels;
- int imageHeightPixels;
- using (var bitmap = new Bitmap(outputPath))
- {
- imageWidthPixels = bitmap.Width;
- imageHeightPixels = bitmap.Height;
+ // Generate and return the barcode image.
+ return generator.GenerateBarCodeImage();
}
+ }
- // --------------------------------------------------------------------
- // Recognize the barcode to retrieve its bounding box (region) within the image
- // --------------------------------------------------------------------
- RectangleF barcodeRegion;
- using (var reader = new BarCodeReader(outputPath, DecodeType.DotCode))
- {
- var results = reader.ReadBarCodes();
- if (results.Length == 0)
- {
- Console.WriteLine("Failed to read the generated DotCode barcode.");
- return;
- }
-
- // Region.Rectangle provides the bounding box in points
- barcodeRegion = results[0].Region.Rectangle;
- }
+ ///
+ /// Entry point that generates two DotCode images with and without padding and validates the size difference.
+ ///
+ static void Main()
+ {
+ // Sample text to encode.
+ const string sampleText = "Test";
- // --------------------------------------------------------------------
- // Retrieve the resolution (DPI) used during generation (default is 96 DPI)
- // --------------------------------------------------------------------
- float resolutionDpi;
- using (var gen = new BarcodeGenerator(EncodeTypes.DotCode, codeText))
+ // Generate a barcode with no padding.
+ using (var bmpNoPad = GenerateDotCode(sampleText, 0f, 0f, 0f, 0f))
+ // Generate a barcode with 20 points of padding on each side.
+ using (var bmpPad = GenerateDotCode(sampleText, 20f, 20f, 20f, 20f))
{
- resolutionDpi = gen.Parameters.Resolution;
- }
-
- // --------------------------------------------------------------------
- // Convert padding from points to pixels (1 point = 1/72 inch)
- // --------------------------------------------------------------------
- float pointsToPixels = resolutionDpi / 72f;
- float expectedPaddingPixels = paddingPoints * pointsToPixels;
+ // Default DPI used by the generator (96). Adjust if generator DPI changes.
+ const float dpi = 96f;
- // --------------------------------------------------------------------
- // Calculate actual padding based on image size and barcode region size
- // --------------------------------------------------------------------
- float actualHorizontalPadding = (imageWidthPixels - barcodeRegion.Width) / 2f;
- float actualVerticalPadding = (imageHeightPixels - barcodeRegion.Height) / 2f;
+ // Convert points to pixels (1 point = dpi / 72 pixels).
+ float pointsToPixels = dpi / 72f;
- // Allow a small tolerance due to rounding errors
- const float tolerance = 1.0f;
+ // Expected pixel increase due to left+right and top+bottom padding.
+ float expectedWidthIncrease = (20f + 20f) * pointsToPixels;
+ float expectedHeightIncrease = (20f + 20f) * pointsToPixels;
- bool horizontalOk = Math.Abs(actualHorizontalPadding - expectedPaddingPixels) <= tolerance;
- bool verticalOk = Math.Abs(actualVerticalPadding - expectedPaddingPixels) <= tolerance;
+ // Actual dimensions of the generated images.
+ int widthNoPad = bmpNoPad.Width;
+ int heightNoPad = bmpNoPad.Height;
+ int widthPad = bmpPad.Width;
+ int heightPad = bmpPad.Height;
- // --------------------------------------------------------------------
- // Output verification results
- // --------------------------------------------------------------------
- Console.WriteLine($"Image size (pixels): {imageWidthPixels}x{imageHeightPixels}");
- Console.WriteLine($"Barcode region size (points): {barcodeRegion.Width}x{barcodeRegion.Height}");
- Console.WriteLine($"Resolution (dpi): {resolutionDpi}");
- Console.WriteLine($"Expected padding (pixels): {expectedPaddingPixels:F2}");
- Console.WriteLine($"Actual horizontal padding (pixels): {actualHorizontalPadding:F2}");
- Console.WriteLine($"Actual vertical padding (pixels): {actualVerticalPadding:F2}");
-
- if (horizontalOk && verticalOk)
- {
- Console.WriteLine("PASS: DotCode margin property correctly influences surrounding whitespace.");
- }
- else
- {
- Console.WriteLine("FAIL: Margin influence does not match expected values.");
- }
+ // Allow a tolerance of 1 pixel because of rounding.
+ bool widthOk = Math.Abs(widthPad - (widthNoPad + expectedWidthIncrease)) <= 1;
+ bool heightOk = Math.Abs(heightPad - (heightNoPad + expectedHeightIncrease)) <= 1;
- // --------------------------------------------------------------------
- // Clean up the generated file
- // --------------------------------------------------------------------
- try
- {
- File.Delete(outputPath);
- }
- catch
- {
- // Ignore any cleanup errors
+ if (widthOk && heightOk)
+ {
+ Console.WriteLine("PASS: DotCode margin influences surrounding whitespace as expected.");
+ }
+ else
+ {
+ Console.WriteLine("FAIL: DotCode margin did not produce the expected image size.");
+ Console.WriteLine($"No padding size: {widthNoPad}x{heightNoPad}");
+ Console.WriteLine($"With padding size: {widthPad}x{heightPad}");
+ Console.WriteLine($"Expected increase: {expectedWidthIncrease}x{expectedHeightIncrease} pixels");
+ }
}
}
}
\ No newline at end of file
diff --git a/two-dimensional-barcode-types/write-unit-tests-to-verify-aspect-ratio-adjustments-affect-maxicode-barcode-dimensions-as-expected.cs b/two-dimensional-barcode-types/write-unit-tests-to-verify-aspect-ratio-adjustments-affect-maxicode-barcode-dimensions-as-expected.cs
index d7f99cc..729ff17 100644
--- a/two-dimensional-barcode-types/write-unit-tests-to-verify-aspect-ratio-adjustments-affect-maxicode-barcode-dimensions-as-expected.cs
+++ b/two-dimensional-barcode-types/write-unit-tests-to-verify-aspect-ratio-adjustments-affect-maxicode-barcode-dimensions-as-expected.cs
@@ -1,3 +1,9 @@
+// Title: Verify MaxiCode Aspect Ratio Impact on Dimensions
+// Description: Demonstrates generating MaxiCode barcodes with different aspect ratios and checking that height changes while width stays constant.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation and manipulation category, focusing on MaxiCode symbology. It shows how to adjust the AspectRatio property via the BarcodeGenerator.Parameters.Barcode.MaxiCode API, a common task when customizing barcode size for packaging or labeling. Developers often need unit‑style checks to ensure dimension changes behave as expected.
+// Prompt: Write unit tests to verify aspect ratio adjustments affect MaxiCode barcode dimensions as expected.
+// Tags: barcode symbology, aspect ratio, maxicode, dimension testing, aspose.barcode, image generation
+
using System;
using System.IO;
using Aspose.BarCode;
@@ -5,69 +11,79 @@
using Aspose.Drawing;
///
-/// Demonstrates generating MaxiCode barcodes with different aspect ratios
-/// and retrieving their pixel dimensions.
+/// Demonstrates unit‑style tests for MaxiCode aspect‑ratio effects on image dimensions.
///
class Program
{
///
- /// Generates a MaxiCode barcode using the specified aspect ratio
- /// and returns its width and height in pixels.
+ /// Entry point that runs dimension verification tests for MaxiCode barcodes.
///
- /// The desired aspect ratio (height / width) for the barcode modules.
- /// A tuple containing the image width and height.
- static (int Width, int Height) GenerateMaxiCodeDimensions(float aspectRatio)
+ static void Main()
{
- // Sample codetext for MaxiCode; any non‑empty string is acceptable.
- const string codeText = "Sample MaxiCode";
+ int failedTests = 0;
+
+ // Test 1: Generate barcode with default aspect ratio (1.0)
+ var imgDefault = GenerateMaxiCode(1.0f);
+ int heightDefault = imgDefault.Height;
+ int widthDefault = imgDefault.Width;
+ imgDefault.Dispose();
+
+ // Test 2: Generate barcode with increased aspect ratio (2.0)
+ var imgHigh = GenerateMaxiCode(2.0f);
+ int heightHigh = imgHigh.Height;
+ int widthHigh = imgHigh.Width;
+ imgHigh.Dispose();
- // Create a barcode generator for MaxiCode with the sample text.
- using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, codeText))
+ // Verify that increasing the aspect ratio raises the height proportionally
+ if (heightHigh <= heightDefault)
{
- // Apply the requested aspect ratio to the generator's parameters.
- generator.Parameters.Barcode.MaxiCode.AspectRatio = aspectRatio;
+ Console.WriteLine("FAILED: Height did not increase with higher aspect ratio.");
+ failedTests++;
+ }
- // Use a memory stream to hold the generated PNG image.
- using (var ms = new MemoryStream())
- {
- // Save the barcode image to the memory stream in PNG format.
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for reading.
+ // Verify that the width remains unchanged (aspect ratio should affect height only)
+ if (widthHigh != widthDefault)
+ {
+ Console.WriteLine("FAILED: Width changed when only aspect ratio was modified.");
+ failedTests++;
+ }
- // Load the image from the stream to obtain its actual pixel dimensions.
- using (var image = Image.FromStream(ms))
- {
- return (image.Width, image.Height);
- }
- }
+ // Output test summary
+ if (failedTests == 0)
+ {
+ Console.WriteLine("All tests passed.");
+ }
+ else
+ {
+ Console.WriteLine($"FAILED: {failedTests} test(s) failed.");
}
}
///
- /// Entry point of the program. Generates barcodes with two different aspect ratios,
- /// prints their dimensions, and verifies that the dimensions change accordingly.
+ /// Generates a MaxiCode barcode image with the specified aspect ratio.
///
- static void Main()
+ /// The desired aspect ratio to apply to the barcode.
+ /// An containing the generated barcode.
+ static Image GenerateMaxiCode(float aspectRatio)
{
- // Generate two barcodes with different aspect ratios.
- var dimsRatio1 = GenerateMaxiCodeDimensions(1.0f);
- var dimsRatio2 = GenerateMaxiCodeDimensions(2.0f);
+ // Sample codetext; actual content is not important for dimension testing
+ const string sampleCodeText = "1234567890";
- // Output the dimensions for each aspect ratio.
- Console.WriteLine($"AspectRatio 1.0 -> Width: {dimsRatio1.Width}, Height: {dimsRatio1.Height}");
- Console.WriteLine($"AspectRatio 2.0 -> Width: {dimsRatio2.Width}, Height: {dimsRatio2.Height}");
+ // Create a generator for MaxiCode (EncodeTypes.MaxiCode is assumed to exist)
+ using (var generator = new BarcodeGenerator(EncodeTypes.MaxiCode, sampleCodeText))
+ {
+ // Apply the aspect ratio via the MaxiCode parameters
+ generator.Parameters.Barcode.MaxiCode.AspectRatio = aspectRatio;
- // Simple verification: the heights (or widths) should differ when the aspect ratio changes.
- bool heightChanged = dimsRatio1.Height != dimsRatio2.Height;
- bool widthChanged = dimsRatio1.Width != dimsRatio2.Width;
+ // Save the barcode to a memory stream in PNG format
+ using (var ms = new MemoryStream())
+ {
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0;
- if (heightChanged || widthChanged)
- {
- Console.WriteLine("PASS: Changing the aspect ratio affects the barcode dimensions.");
- }
- else
- {
- Console.WriteLine("FAIL: Barcode dimensions did not change with aspect ratio adjustments.");
+ // Load and return the image using Aspose.Drawing
+ return Aspose.Drawing.Image.FromStream(ms);
+ }
}
}
}
\ No newline at end of file