diff --git a/barcode-appearance-customization/adjust-xdimension-to-increase-bar-width-for-code39-barcode-reducing-visual-density-for-print-media.cs b/barcode-appearance-customization/adjust-xdimension-to-increase-bar-width-for-code39-barcode-reducing-visual-density-for-print-media.cs
index 5685d7c..0d581fb 100644
--- a/barcode-appearance-customization/adjust-xdimension-to-increase-bar-width-for-code39-barcode-reducing-visual-density-for-print-media.cs
+++ b/barcode-appearance-customization/adjust-xdimension-to-increase-bar-width-for-code39-barcode-reducing-visual-density-for-print-media.cs
@@ -1,41 +1,44 @@
-// Title: Code39 Barcode with Increased XDimension
-// Description: Demonstrates how to adjust the XDimension property to widen bars in a Code39 barcode, making it less dense for print media.
+// Title: Increase XDimension for Code39 barcode to reduce visual density
+// Description: Demonstrates how to adjust the XDimension property of a Code39 barcode using Aspose.BarCode to make bars wider, which is useful for print media where lower density is desired.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating barcode parameter customization. It showcases the BarcodeGenerator class, EncodeTypes enumeration, and barcode parameter settings such as XDimension, BarHeight, BarColor, and BackColor. Developers often need to tweak these settings to meet printing, scanning, and branding requirements.
// Prompt: Adjust XDimension to increase bar width for a Code39 barcode, reducing visual density for print media.
-// Tags: code39, barcode, xdimension, print, aspose.barcode, generation
+// Tags: code39, xdimension, barcode, generation, png, aspose.barcode, aspose.drawing
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Generates a Code39 barcode with a larger XDimension to reduce visual density,
-/// suitable for printing on media where wider bars are preferred.
+/// Generates a Code39 barcode with an increased XDimension to produce wider bars,
+/// reducing visual density for better print media readability.
///
class Program
{
///
- /// Entry point of the example. Creates a Code39 barcode, adjusts its XDimension,
- /// and saves the result as a PNG image.
+ /// Entry point of the example. Creates a barcode, adjusts its dimensions,
+ /// and saves it as a PNG image.
///
static void Main()
{
- // Initialize a Code39 barcode generator with sample text.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code39, "CODE39-EXAMPLE"))
+ // Initialize a Code39 barcode generator with the sample text "CODE39"
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code39, "CODE39"))
{
- // Disable auto-size mode so that manual XDimension settings take effect.
- generator.Parameters.AutoSizeMode = AutoSizeMode.None;
-
- // Increase the XDimension to make each bar wider (e.g., 2 points).
+ // Increase XDimension (bar width) to 2 points for lower density
generator.Parameters.Barcode.XDimension.Point = 2f;
- // Optionally set a reasonable bar height for printing (e.g., 40 points).
+ // Set a reasonable bar height (40 points) suitable for printing
generator.Parameters.Barcode.BarHeight.Point = 40f;
- // Save the generated barcode image to a PNG file.
+ // Define foreground (bars) and background colors
+ generator.Parameters.Barcode.BarColor = Color.Black;
+ generator.Parameters.BackColor = Color.White;
+
+ // Save the generated barcode as a PNG file
generator.Save("code39.png");
}
- // Inform the user that the barcode has been generated.
+ // Output a simple confirmation message
Console.WriteLine("Code39 barcode generated with increased XDimension.");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/apply-45-degree-rotationangle-to-qr-code-and-save-result-as-jpeg-image.cs b/barcode-appearance-customization/apply-45-degree-rotationangle-to-qr-code-and-save-result-as-jpeg-image.cs
index 9842752..d0e094e 100644
--- a/barcode-appearance-customization/apply-45-degree-rotationangle-to-qr-code-and-save-result-as-jpeg-image.cs
+++ b/barcode-appearance-customization/apply-45-degree-rotationangle-to-qr-code-and-save-result-as-jpeg-image.cs
@@ -1,30 +1,38 @@
-// Title: QR Code Rotation Example
-// Description: Demonstrates applying a 45-degree rotation to a QR code and saving it as a JPEG image.
+// Title: QR Code Generation with 45‑Degree Rotation
+// Description: Demonstrates applying a 45‑degree rotation to a QR code and saving it as a JPEG image.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to configure barcode parameters such as rotation using the BarcodeGenerator class. Typical use cases include customizing barcode appearance for branding or layout requirements. Developers often need to adjust rotation, size, and format when integrating barcodes into graphics or documents.
// Prompt: Apply a 45‑degree RotationAngle to a QR code and save the result as a JPEG image.
-// Tags: qr, rotation, jpeg, aspose.barcode, barcodegeneration
+// Tags: qr code, rotation, jpeg, generation, aspose.barcode
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.BarCode.BarCodeRecognition;
///
-/// Entry point for the QR code rotation demonstration.
+/// Generates a QR code, applies a 45‑degree rotation, and saves it as a JPEG image.
///
class Program
{
///
- /// Generates a QR code, rotates it 45 degrees, and saves it as a JPEG file.
+ /// Entry point of the example. Creates a QR code, rotates it, and writes the output file.
///
static void Main()
{
- // Initialize the QR code generator with the desired text.
- using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Hello Aspose"))
+ // Initialize a QR code generator within a using block to ensure proper disposal
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR))
{
- // Set the rotation angle to 45 degrees.
+ // Set the text that the QR code will encode
+ generator.CodeText = "Hello World";
+
+ // Apply a 45‑degree rotation to the generated barcode image
generator.Parameters.RotationAngle = 45f;
- // Persist the rotated QR code image as a JPEG file.
- generator.Save("qr_rotated.jpg");
+ // Save the rotated QR code as a JPEG file
+ generator.Save("qr45.jpg");
}
+
+ // Inform the user that the operation completed successfully
+ Console.WriteLine("QR code generated with 45° rotation and saved as qr45.jpg");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/combine-custom-padding-and-rotation-settings-to-fit-maxicode-barcode-within-predefined-canvas-size.cs b/barcode-appearance-customization/combine-custom-padding-and-rotation-settings-to-fit-maxicode-barcode-within-predefined-canvas-size.cs
index 995f095..90ed42f 100644
--- a/barcode-appearance-customization/combine-custom-padding-and-rotation-settings-to-fit-maxicode-barcode-within-predefined-canvas-size.cs
+++ b/barcode-appearance-customization/combine-custom-padding-and-rotation-settings-to-fit-maxicode-barcode-within-predefined-canvas-size.cs
@@ -1,26 +1,32 @@
-// Title: MaxiCode barcode with custom padding and rotation
-// Description: Demonstrates generating a MaxiCode barcode, applying uniform padding and rotating it to fit within a 300x300 point canvas.
+// Title: MaxiCode Barcode with Custom Padding and Rotation on Fixed Canvas
+// Description: Demonstrates how to generate a MaxiCode barcode, apply custom padding and rotate it to fit within a predefined canvas size.
+// Category-Description: This example belongs to the Aspose.BarCode complex barcode generation category, illustrating the use of ComplexBarcodeGenerator, MaxiCodeCodetextMode2, and image parameter settings. It shows typical tasks such as setting canvas dimensions, padding, rotation, and colors for MaxiCode symbols. Developers creating shipping labels or logistics solutions often need to fit MaxiCode barcodes into fixed-size graphics.
// Prompt: Combine custom padding and rotation settings to fit a MaxiCode barcode within a predefined canvas size.
-// Tags: maxicode, padding, rotation, canvas, aspose.barcode, csharp
+// Tags: maxicode, padding, rotation, png, complexbarcode, generator, image-parameters
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.ComplexBarcode;
-using Aspose.Drawing.Imaging;
///
-/// Example program that generates a MaxiCode barcode with custom padding and rotation.
+/// Generates a MaxiCode barcode, applies custom padding and rotation, and saves it to a PNG file.
///
class Program
{
///
- /// Entry point. Creates a MaxiCode barcode, sets canvas size, padding, rotation, and saves the image.
+ /// Entry point of the example. Configures barcode parameters, generates the image, and writes the output path.
///
static void Main()
{
- // Define sample MaxiCode data (Mode 2) with postal code, country code, service category, and a secondary message.
- var maxiCode = new MaxiCodeCodetextMode2
+ // Define output file name and desired canvas size (points)
+ string outputPath = "maxicode.png";
+ float canvasWidth = 300f;
+ float canvasHeight = 300f;
+
+ // Prepare MaxiCode codetext using Mode 2 (includes postal code, country, service category, and a second message)
+ var maxiCodeCodetext = new MaxiCodeCodetextMode2
{
PostalCode = "524032140",
CountryCode = 56,
@@ -28,30 +34,34 @@ static void Main()
SecondMessage = new MaxiCodeStandardSecondMessage { Message = "Sample MaxiCode" }
};
- // Initialize a ComplexBarcodeGenerator using the MaxiCode codetext.
- using (var generator = new ComplexBarcodeGenerator(maxiCode))
+ // Initialize the complex barcode generator with the prepared codetext
+ using (var generator = new ComplexBarcodeGenerator(maxiCodeCodetext))
{
- // Set AutoSizeMode to Interpolation so ImageWidth/ImageHeight control the final size.
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ // Set the target canvas dimensions
+ generator.Parameters.ImageWidth.Point = canvasWidth;
+ generator.Parameters.ImageHeight.Point = canvasHeight;
- // Define the target canvas size (300x300 points).
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 300f;
+ // Use interpolation auto‑size mode so the specified width/height control the final image size
+ generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- // Apply uniform padding of 10 points on all sides.
+ // Apply uniform padding of 10 points on all sides
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;
- // Rotate the barcode 90 degrees clockwise.
+ // Rotate the barcode 90 degrees clockwise
generator.Parameters.RotationAngle = 90f;
- // Save the generated barcode image to a PNG file.
- generator.Save("MaxiCode.png");
+ // Optional visual settings: white background and black bars
+ generator.Parameters.BackColor = Aspose.Drawing.Color.White;
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+
+ // Save the generated barcode image as PNG
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
- // Inform the user that the barcode has been generated.
- Console.WriteLine("MaxiCode barcode generated successfully.");
+ // Inform the user where the file was saved
+ Console.WriteLine($"MaxiCode barcode saved to '{Path.GetFullPath(outputPath)}'.");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/configure-autosizemode-to-interpolation-set-imagewidth-and-imageheight-and-generate-high-resolution-png-barcode.cs b/barcode-appearance-customization/configure-autosizemode-to-interpolation-set-imagewidth-and-imageheight-and-generate-high-resolution-png-barcode.cs
index 088f887..1fb8c06 100644
--- a/barcode-appearance-customization/configure-autosizemode-to-interpolation-set-imagewidth-and-imageheight-and-generate-high-resolution-png-barcode.cs
+++ b/barcode-appearance-customization/configure-autosizemode-to-interpolation-set-imagewidth-and-imageheight-and-generate-high-resolution-png-barcode.cs
@@ -1,45 +1,48 @@
-// Title: High‑Resolution QR Code Barcode Generation with Interpolation Auto‑Size
+// Title: Generate High‑Resolution PNG Barcode with Interpolation AutoSizeMode
// Description: Demonstrates configuring AutoSizeMode to Interpolation, setting image dimensions, and saving a high‑resolution PNG barcode using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, showcasing how to use the BarcodeGenerator class with EncodeTypes, AutoSizeMode, and resolution settings. Typical use cases include creating printable barcodes for inventory, shipping, or product labeling where high‑resolution output is required. Developers often need to control image size, DPI, and rendering mode to meet quality standards.
// Prompt: Configure AutoSizeMode to Interpolation, set ImageWidth and ImageHeight, and generate a high‑resolution PNG barcode.
-// Tags: qr, barcode, autosizemode, interpolation, highresolution, png, aspose.barcode, csharp
+// Tags: code128, generation, png, autosizemode, resolution, aspose.barcode, barcodegenerator
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
///
-/// Example program that generates a high‑resolution QR code barcode.
+/// Example program that generates a high‑resolution PNG barcode using Aspose.BarCode.
///
class Program
{
///
- /// Entry point. Configures the barcode generator and saves a PNG image.
+ /// Entry point. Configures barcode parameters, generates the image, and saves it to disk.
///
static void Main()
{
- // Initialize a barcode generator for a QR code with the desired text
- using (var generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"))
+ // Define the output file path in the current working directory.
+ string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "high_res_barcode.png");
+
+ // Create a BarcodeGenerator for Code128 symbology with sample text.
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Set the output resolution to 300 DPI for high‑quality rendering
+ // Set the desired resolution (e.g., 300 DPI) for high‑quality output.
generator.Parameters.Resolution = 300f;
- // Enable Interpolation auto‑size mode to improve scaling quality
+ // Enable interpolation auto‑size mode and specify canvas dimensions in points.
generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ generator.Parameters.ImageWidth.Point = 600f; // Width in points.
+ generator.Parameters.ImageHeight.Point = 300f; // Height in points.
- // Define the canvas size in points (1 point = 1/72 inch)
- generator.Parameters.ImageWidth.Point = 600f; // Width: 600 points
- generator.Parameters.ImageHeight.Point = 600f; // Height: 600 points
-
- // Optional: specify foreground (barcode) and background colors
+ // Optional: define barcode and background colors.
generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- // Save the generated barcode as a high‑resolution PNG file
- generator.Save("high_res_barcode.png");
+ // Save the generated barcode as a PNG image to the specified path.
+ generator.Save(outputPath);
}
- // Inform the user that the barcode has been created
- Console.WriteLine("Barcode generated successfully.");
+ // Inform the user where the barcode image has been saved.
+ Console.WriteLine($"Barcode image saved to: {outputPath}");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/create-app-that-reads-csv-list-of-barcode-data-and-generates-images-with-padding-and-rotation.cs b/barcode-appearance-customization/create-app-that-reads-csv-list-of-barcode-data-and-generates-images-with-padding-and-rotation.cs
index e75dedf..04044ce 100644
--- a/barcode-appearance-customization/create-app-that-reads-csv-list-of-barcode-data-and-generates-images-with-padding-and-rotation.cs
+++ b/barcode-appearance-customization/create-app-that-reads-csv-list-of-barcode-data-and-generates-images-with-padding-and-rotation.cs
@@ -1,119 +1,92 @@
// Title: Generate barcode images from CSV with padding and rotation
-// Description: Demonstrates reading barcode data from a CSV file (or sample data) and creating PNG images with uniform padding and optional rotation.
+// Description: This example reads a CSV file containing barcode data, padding, and rotation values, then creates PNG images using Aspose.BarCode.
+// Category-Description: Demonstrates Aspose.BarCode generation API for batch processing. Shows how to use BarcodeGenerator, set EncodeTypes, configure padding via Parameters.Barcode.Padding, apply rotation with Parameters.RotationAngle, and save images. Useful for developers automating barcode creation from data sources such as CSV files.
// Prompt: Create an app that reads a CSV list of barcode data and generates images with padding and rotation.
-// Tags: barcode, csv, padding, rotation, png, aspose.barcode, aspose.drawing
+// Tags: barcode symbology, generation, png, padding, rotation, csv, aspose.barcode
using System;
-using System.Collections.Generic;
-using System.Globalization;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
///
-/// Reads barcode data from a CSV file (or uses sample data) and generates PNG images
-/// with uniform padding and optional rotation using Aspose.BarCode.
+/// Reads a CSV list of barcode specifications and generates PNG images with custom padding and rotation.
///
class Program
{
///
- /// Application entry point. Loads data, creates output directory, and generates barcode images.
+ /// Entry point of the application. Processes the CSV file and creates barcode images.
///
static void Main()
{
- // Path to the CSV file (optional). If the file does not exist, sample data will be used.
- const string csvPath = "barcodes.csv";
+ // Define the path to the CSV file that holds barcode specifications.
+ string csvPath = "barcodes.csv";
- // Load barcode data from CSV or fall back to a default list.
- List<(string CodeText, float Rotation)> records = LoadCsv(csvPath);
-
- // Ensure the output directory exists.
- const string outputDir = "Barcodes";
- if (!Directory.Exists(outputDir))
+ // If the CSV file does not exist, create a sample file with example data.
+ if (!File.Exists(csvPath))
{
- Directory.CreateDirectory(outputDir);
+ string[] sampleLines =
+ {
+ // Format: CodeText,OutputFileName,RotationAngle,PaddingPoints
+ "1234567890,code1.png,0,10",
+ "ABCDEF,code2.png,90,15",
+ "HelloWorld,code3.png,180,20"
+ };
+ File.WriteAllLines(csvPath, sampleLines);
+ Console.WriteLine($"Sample CSV created at '{csvPath}'.");
}
- // Process each record and generate a barcode image.
- int index = 1;
- foreach (var record in records)
+ // Read all lines from the CSV file, ignoring empty entries.
+ string[] lines = File.ReadAllLines(csvPath);
+ foreach (string line in lines)
{
- // Create a BarcodeGenerator for Code128 (change EncodeTypes as needed).
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, record.CodeText))
- {
- // Set uniform padding (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;
+ if (string.IsNullOrWhiteSpace(line))
+ continue; // Skip blank lines.
- // Set rotation angle (must be 0, 90, 180, or 270 for best readability).
- generator.Parameters.RotationAngle = record.Rotation;
-
- // Optional: set barcode colors.
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
-
- // Save the barcode image to the output directory.
- string fileName = Path.Combine(outputDir, $"barcode_{index}.png");
- generator.Save(fileName);
- Console.WriteLine($"Saved barcode #{index}: {fileName}");
+ // Expected columns: CodeText, OutputFileName, RotationAngle, PaddingPoints
+ string[] parts = line.Split(',');
+ if (parts.Length < 4)
+ {
+ Console.WriteLine($"Skipping malformed line: {line}");
+ continue; // Not enough columns; move to the next line.
}
- index++;
- }
+ // Extract and trim individual values.
+ string codeText = parts[0].Trim();
+ string outputFile = parts[1].Trim();
- Console.WriteLine("Barcode generation completed.");
- }
-
- // Loads CSV data. Expected format per line: CodeText,RotationAngle
- // RotationAngle is optional; if missing, 0 is used.
- private static List<(string CodeText, float Rotation)> LoadCsv(string path)
- {
- var list = new List<(string, float)>();
-
- if (File.Exists(path))
- {
- // Read each line from the CSV file.
- using (var reader = new StreamReader(path))
+ // Parse rotation angle; if invalid, report and skip.
+ if (!float.TryParse(parts[2].Trim(), out float rotation))
{
- string line;
- while ((line = reader.ReadLine()) != null)
- {
- // Skip empty lines.
- if (string.IsNullOrWhiteSpace(line))
- continue;
-
- // Split line into parts: code text and optional rotation.
- string[] parts = line.Split(',');
- string codeText = parts[0].Trim();
- float rotation = 0f;
+ Console.WriteLine($"Invalid rotation value on line: {line}");
+ continue;
+ }
- // Parse rotation if provided.
- if (parts.Length > 1 && float.TryParse(parts[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out float parsed))
- {
- rotation = parsed;
- }
+ // Parse padding value; if invalid, report and skip.
+ if (!float.TryParse(parts[3].Trim(), out float padding))
+ {
+ Console.WriteLine($"Invalid padding value on line: {line}");
+ continue;
+ }
- // Add valid entries to the list.
- if (!string.IsNullOrEmpty(codeText))
- {
- list.Add((codeText, rotation));
- }
- }
+ // Generate the barcode using the specified symbology (Code128) and text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ {
+ // Apply uniform padding (in points) to all sides of the barcode.
+ generator.Parameters.Barcode.Padding.Left.Point = padding;
+ generator.Parameters.Barcode.Padding.Top.Point = padding;
+ generator.Parameters.Barcode.Padding.Right.Point = padding;
+ generator.Parameters.Barcode.Padding.Bottom.Point = padding;
+
+ // Set the rotation angle (in degrees) for the barcode image.
+ generator.Parameters.RotationAngle = rotation;
+
+ // Save the generated barcode as a PNG file (default format).
+ generator.Save(outputFile);
+ Console.WriteLine($"Generated '{outputFile}' for code '{codeText}'.");
}
}
- else
- {
- // Sample data if CSV is missing.
- list.Add(("Sample001", 0f));
- list.Add(("Sample002", 90f));
- list.Add(("Sample003", 180f));
- list.Add(("Sample004", 270f));
- list.Add(("Sample005", 0f));
- }
- return list;
+ Console.WriteLine("Barcode generation completed.");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/create-barcode-with-autosizemode-set-to-none-and-define-xdimension-to-control-narrow-bar-width.cs b/barcode-appearance-customization/create-barcode-with-autosizemode-set-to-none-and-define-xdimension-to-control-narrow-bar-width.cs
index 0443b06..390c36f 100644
--- a/barcode-appearance-customization/create-barcode-with-autosizemode-set-to-none-and-define-xdimension-to-control-narrow-bar-width.cs
+++ b/barcode-appearance-customization/create-barcode-with-autosizemode-set-to-none-and-define-xdimension-to-control-narrow-bar-width.cs
@@ -1,40 +1,40 @@
-// Title: Generate Code128 Barcode with Fixed XDimension
-// Description: Demonstrates creating a Code128 barcode, disabling auto-size, and setting the narrow bar width via XDimension.
+// Title: Generate Code128 barcode with custom XDimension and disabled AutoSize
+// Description: Demonstrates creating a Code128 barcode, turning off automatic sizing, and setting the narrow bar width via XDimension.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to control barcode dimensions using the BarcodeGenerator, EncodeTypes, and AutoSizeMode classes. Developers often need to produce barcodes with precise module widths for printing or scanning requirements, and this snippet shows the typical steps for customizing size parameters before saving the image.
// Prompt: Create a barcode with AutoSizeMode set to None and define XDimension to control narrow bar width.
-// Tags: code128, barcode, autosizemode, xdimension, png, aspose.barcode, aspnet
+// Tags: code128, autosizemode, xdimension, barcode generation, png output, aspnet.barcode, generation
using System;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
+using Aspose.BarCode;
///
-/// Example program that generates a Code128 barcode image with a custom narrow bar width.
+/// Program demonstrating barcode generation with custom sizing.
///
class Program
{
///
- /// Entry point. Generates the barcode, configures sizing options, and saves it as a PNG file.
+ /// Entry point. Generates a Code128 barcode, disables auto sizing, sets XDimension, and saves as PNG.
///
static void Main()
{
- // Initialize a barcode generator for Code128 with the sample text "1234567890".
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
+ // Initialize a barcode generator for the Code128 symbology (any 1D type could be used)
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128))
{
- // Disable automatic sizing so manual dimensions can be applied.
+ // Set the data to be encoded in the barcode
+ generator.CodeText = "1234567890";
+
+ // Turn off automatic size calculation so we can define dimensions manually
generator.Parameters.AutoSizeMode = AutoSizeMode.None;
- // Define the narrow bar width (XDimension) as 2 points.
+ // Specify the narrow bar width (XDimension) in points; 2 points per module in this case
generator.Parameters.Barcode.XDimension.Point = 2f;
- // Set the bar height for the 1D barcode when AutoSizeMode is None.
- generator.Parameters.Barcode.BarHeight.Point = 50f;
-
- // Save the generated barcode image to a PNG file.
+ // Save the generated barcode as a PNG image file
generator.Save("barcode.png");
}
- // Inform the user that the barcode has been created.
- Console.WriteLine("Barcode generated and saved to barcode.png");
+ // Inform the user that the barcode has been created
+ Console.WriteLine("Barcode generated and saved as 'barcode.png'.");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/create-batch-process-that-rotates-each-generated-barcode-by-90-degrees-before-saving-as-png-files.cs b/barcode-appearance-customization/create-batch-process-that-rotates-each-generated-barcode-by-90-degrees-before-saving-as-png-files.cs
index c9708b5..49fffd6 100644
--- a/barcode-appearance-customization/create-batch-process-that-rotates-each-generated-barcode-by-90-degrees-before-saving-as-png-files.cs
+++ b/barcode-appearance-customization/create-batch-process-that-rotates-each-generated-barcode-by-90-degrees-before-saving-as-png-files.cs
@@ -1,44 +1,65 @@
-// Title: Batch Barcode Generation with Rotation
-// Description: Generates a set of Code128 barcodes, rotates each by 90 degrees, and saves them as PNG files.
+// Title: Batch barcode generation with 90° rotation
+// Description: Demonstrates generating multiple barcode types, rotating each by 90 degrees, and saving them as PNG images.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator, set rotation, and export images. Developers often need to create batches of barcodes with specific orientation for printing or UI display, and this snippet illustrates typical API usage for such scenarios.
// Prompt: Create a batch process that rotates each generated barcode by 90 degrees before saving as PNG files.
-// Tags: barcode, code128, rotation, png, batch, aspose.barcode
+// Tags: barcode symbology, rotation, png, aspose.barcode, generation
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Demonstrates batch creation of Code128 barcodes, applying a 90‑degree rotation,
-/// and saving each image as a PNG file.
+/// Generates a set of barcodes, rotates each by 90 degrees, and saves them as PNG files.
///
class Program
{
///
- /// Entry point of the application. Generates, rotates, and saves barcodes.
+ /// Entry point of the application. Creates output folder, defines sample barcodes,
+ /// rotates each barcode, and saves the result as PNG images.
///
static void Main()
{
- // Define a collection of sample code texts for the batch process
- string[] codeTexts = { "12345", "ABCDE", "987654321", "HelloWorld", "20230607" };
+ // Define the output directory for generated barcode images
+ string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(outputFolder))
+ {
+ // Create the directory if it does not already exist
+ Directory.CreateDirectory(outputFolder);
+ }
+
+ // Collection of barcode specifications: type, data, and target file name
+ var samples = new (BaseEncodeType type, string text, string fileName)[]
+ {
+ (EncodeTypes.Code128, "ABC123456", "code128.png"),
+ (EncodeTypes.QR, "https://example.com", "qr.png"),
+ (EncodeTypes.DataMatrix, "DataMatrixSample", "datamatrix.png"),
+ (EncodeTypes.Pdf417, "PDF417 Sample Text", "pdf417.png"),
+ (EncodeTypes.EAN13, "123456789012", "ean13.png")
+ };
- // Iterate over each code text, generate a barcode, rotate it, and save as PNG
- for (int i = 0; i < codeTexts.Length; i++)
+ // Iterate over each sample, generate, rotate, and save the barcode
+ foreach (var sample in samples)
{
- // Initialise a Code128 barcode generator with the current code text
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeTexts[i]))
+ string outputPath = Path.Combine(outputFolder, sample.fileName);
+
+ // Initialize the barcode generator with the specified type and data
+ using (BarcodeGenerator generator = new BarcodeGenerator(sample.type, sample.text))
{
- // Set rotation angle to 90 degrees (clockwise)
+ // Apply a 90-degree rotation to the generated barcode
generator.Parameters.RotationAngle = 90f;
- // Construct a unique file name for the output image
- string fileName = $"barcode_{i + 1}.png";
+ // Optional: set a consistent image size for all barcodes
+ generator.Parameters.ImageWidth.Point = 300f;
+ generator.Parameters.ImageHeight.Point = 150f;
+
+ // Save the rotated barcode as a PNG file
+ generator.Save(outputPath, BarCodeImageFormat.Png);
- // Save the rotated barcode image in PNG format
- generator.Save(fileName, BarCodeImageFormat.Png);
+ // Inform the user about the saved file location
+ Console.WriteLine($"Saved rotated barcode to: {outputPath}");
}
}
-
- // Output a confirmation message to the console
- Console.WriteLine("Barcodes generated and rotated successfully.");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/create-reusable-library-function-that-accepts-rotation-angle-padding-and-size-parameters-to-produce-customized-barcode-i.cs b/barcode-appearance-customization/create-reusable-library-function-that-accepts-rotation-angle-padding-and-size-parameters-to-produce-customized-barcode-i.cs
index 2f4fef2..b45f20f 100644
--- a/barcode-appearance-customization/create-reusable-library-function-that-accepts-rotation-angle-padding-and-size-parameters-to-produce-customized-barcode-i.cs
+++ b/barcode-appearance-customization/create-reusable-library-function-that-accepts-rotation-angle-padding-and-size-parameters-to-produce-customized-barcode-i.cs
@@ -1,79 +1,81 @@
-// Title: Generate customizable barcode image with rotation, padding, and size
-// Description: Demonstrates creating a barcode image using Aspose.BarCode with user-defined rotation, padding, and dimensions, useful for generating consistent barcode graphics.
+// Title: Generate Custom Rotated Barcode with Padding and Size
+// Description: Demonstrates creating a barcode image with a specified rotation angle, uniform padding, and custom dimensions, then saving it as PNG.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to use the BarcodeGenerator class together with its Parameters property to control rotation, padding, and image size. Developers often need to produce barcodes that fit specific layout constraints, such as rotated labels or fixed-size graphics, and this snippet shows the typical API usage for those scenarios.
// Prompt: Create a reusable library function that accepts rotation angle, padding, and size parameters to produce customized barcode images.
-// Tags: barcode, code128, rotation, padding, size, png, aspose.barcode, csharp
+// Tags: barcode symbology, image generation, rotation, padding, size, aspose.barcode, png, c#
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
-///
-/// Demonstrates barcode generation with customizable parameters.
-///
-class Program
+namespace BarcodeDemo
{
///
- /// Generates a barcode image with custom rotation, padding, and size.
+ /// Demonstrates generating a barcode with custom rotation, padding, and image size.
///
- /// Rotation in degrees (e.g., 0, 90, 180, 270).
- /// Uniform padding in points applied to all sides.
- /// Image width in points.
- /// Image height in points.
- /// Text to encode in the barcode.
- /// File path to save the PNG image.
- static void GenerateBarcode(float rotationAngle, float padding, float width, float height, string codeText, string outputPath)
+ class Program
{
- // Validate required parameters.
- if (string.IsNullOrWhiteSpace(codeText))
- throw new ArgumentException("codeText cannot be null or empty.", nameof(codeText));
- if (string.IsNullOrWhiteSpace(outputPath))
- throw new ArgumentException("outputPath cannot be null or empty.", nameof(outputPath));
-
- // Use Code128 as a common 1D symbology.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ ///
+ /// Entry point of the example. Sets up parameters and creates a barcode image.
+ ///
+ static void Main()
{
- // Apply rotation.
- generator.Parameters.RotationAngle = rotationAngle;
-
- // Set size control via interpolation mode.
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- generator.Parameters.ImageWidth.Point = width;
- generator.Parameters.ImageHeight.Point = height;
+ // Define sample parameters for the barcode generation
+ string outputPath = "custom_barcode.png";
+ BaseEncodeType encodeType = EncodeTypes.Code128;
+ string codeText = "1234567890";
+ float rotationAngle = 45f; // degrees
+ float padding = 10f; // points
+ float imageWidth = 300f; // points
+ float imageHeight = 150f; // points
- // Apply uniform padding on all sides.
- generator.Parameters.Barcode.Padding.Left.Point = padding;
- generator.Parameters.Barcode.Padding.Top.Point = padding;
- generator.Parameters.Barcode.Padding.Right.Point = padding;
- generator.Parameters.Barcode.Padding.Bottom.Point = padding;
+ // Generate the barcode with the specified customizations
+ CreateBarcode(outputPath, encodeType, codeText, rotationAngle, padding, imageWidth, imageHeight);
- // Save the generated barcode as a PNG file.
- generator.Save(outputPath, BarCodeImageFormat.Png);
+ // Inform the user where the barcode image was saved
+ Console.WriteLine($"Barcode saved to: {outputPath}");
}
- }
-
- ///
- /// Entry point that calls with sample parameters and handles errors.
- ///
- static void Main()
- {
- // Sample parameters.
- float rotation = 90f; // Rotate 90 degrees.
- float padding = 5f; // 5 points padding on each side.
- float imgWidth = 300f; // 300 points width.
- float imgHeight = 150f; // 150 points height.
- string text = "Sample123"; // Text to encode.
- string file = "custom_barcode.png"; // Output file name.
- try
+ ///
+ /// Generates a barcode image with custom rotation, uniform padding, and image size.
+ ///
+ /// File path to save the barcode image.
+ /// Symbology type (e.g., EncodeTypes.Code128).
+ /// Text to encode.
+ /// Rotation angle in degrees.
+ /// Uniform padding applied to all sides (points).
+ /// Desired image width (points).
+ /// Desired image height (points).
+ static void CreateBarcode(string outputPath, BaseEncodeType encodeType, string codeText,
+ float rotationAngle, float padding,
+ float imageWidth, float imageHeight)
{
- // Generate the barcode with the specified settings.
- GenerateBarcode(rotation, padding, imgWidth, imgHeight, text, file);
- Console.WriteLine($"Barcode generated and saved to '{file}'.");
- }
- catch (Exception ex)
- {
- // Output any errors that occur during generation.
- Console.WriteLine($"Error: {ex.Message}");
+ // Validate arguments to ensure required values are provided
+ if (string.IsNullOrWhiteSpace(outputPath))
+ throw new ArgumentException("Output path must be provided.", nameof(outputPath));
+ if (codeText == null)
+ throw new ArgumentNullException(nameof(codeText));
+
+ // Initialize the barcode generator with the chosen symbology and text
+ using (var generator = new BarcodeGenerator(encodeType, codeText))
+ {
+ // Apply rotation to the barcode image
+ generator.Parameters.RotationAngle = rotationAngle;
+
+ // Set uniform padding on all sides
+ generator.Parameters.Barcode.Padding.Left.Point = padding;
+ generator.Parameters.Barcode.Padding.Top.Point = padding;
+ generator.Parameters.Barcode.Padding.Right.Point = padding;
+ generator.Parameters.Barcode.Padding.Bottom.Point = padding;
+
+ // Define the output image dimensions
+ generator.Parameters.ImageWidth.Point = imageWidth;
+ generator.Parameters.ImageHeight.Point = imageHeight;
+
+ // Save the generated barcode as a PNG file
+ generator.Save(outputPath, BarCodeImageFormat.Png);
+ }
}
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/create-script-that-automatically-adjusts-padding-after-rotation-to-prevent-barcode-edges-from-being-cut-off.cs b/barcode-appearance-customization/create-script-that-automatically-adjusts-padding-after-rotation-to-prevent-barcode-edges-from-being-cut-off.cs
index 9778cc0..f2524a9 100644
--- a/barcode-appearance-customization/create-script-that-automatically-adjusts-padding-after-rotation-to-prevent-barcode-edges-from-being-cut-off.cs
+++ b/barcode-appearance-customization/create-script-that-automatically-adjusts-padding-after-rotation-to-prevent-barcode-edges-from-being-cut-off.cs
@@ -1,65 +1,63 @@
-// Title: Automatic Padding Adjustment After Barcode Rotation
-// Description: Demonstrates how to rotate a barcode and automatically increase padding to avoid clipping of edges.
+// Title: Adjust barcode padding after rotation to avoid clipping
+// Description: Demonstrates how to calculate and apply extra padding to a rotated barcode so that its edges are not cut off.
+// Category-Description: This example belongs to the Aspose.BarCode image manipulation category, illustrating the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat to rotate barcodes and dynamically adjust padding. Developers often need to rotate barcodes for design layouts while ensuring the full code remains visible; this snippet shows the typical workflow for calculating required padding based on image dimensions.
// Prompt: Create a script that automatically adjusts padding after rotation to prevent barcode edges from being cut off.
-// Tags: barcode, rotation, padding, code128, aspose.barcode, image output
+// Tags: code128, rotation, padding, png, barcodegenerator, parameters, aspnet.barcode
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
///
-/// Example program that generates a Code128 barcode, rotates it,
-/// and automatically adjusts padding to prevent the barcode edges from being cut off.
+/// Demonstrates automatic padding adjustment for a rotated barcode to prevent clipping.
///
class Program
{
///
- /// Entry point of the application.
- /// Generates a rotated barcode with dynamic padding and saves it as an image file.
+ /// Entry point. Generates a Code128 barcode, rotates it, computes required padding, and saves as PNG.
///
static void Main()
{
- // Define the barcode text to encode.
- const string codeText = "Sample123";
+ // Define the output file path
+ string outputPath = "rotated_barcode.png";
- // Initialize the barcode generator with Code128 symbology.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ // Initialize a barcode generator for Code128 with sample text
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- // Rotate the barcode by 90 degrees (clockwise).
- generator.Parameters.RotationAngle = 90f;
+ // Set the desired rotation angle (e.g., 45 degrees)
+ float rotationAngle = 45f;
+ generator.Parameters.RotationAngle = rotationAngle;
- // Set a base uniform padding (in points) around the barcode.
- float basePadding = 5f;
- generator.Parameters.Barcode.Padding.Left.Point = basePadding;
- generator.Parameters.Barcode.Padding.Top.Point = basePadding;
- generator.Parameters.Barcode.Padding.Right.Point = basePadding;
- generator.Parameters.Barcode.Padding.Bottom.Point = basePadding;
+ // Generate a temporary barcode image to obtain its original dimensions
+ using (var bitmap = generator.GenerateBarCodeImage())
+ {
+ // Original width and height in pixels
+ int width = bitmap.Width;
+ int height = bitmap.Height;
- // Determine the effective rotation angle within a 0‑180° range.
- float rotation = generator.Parameters.RotationAngle % 180f;
- if (rotation < 0) rotation += 180f; // Normalize negative angles.
+ // Calculate the diagonal length needed to contain the rotated image
+ double diagonal = Math.Sqrt(width * width + height * height);
- // If the rotation is not a multiple of 180°, add extra padding to avoid clipping.
- if (Math.Abs(rotation) > 0.1f) // Non‑zero rotation threshold.
- {
- // Extra padding (in points) – adjust this value as needed for your use case.
- float extraPadding = 10f;
+ // Determine extra space required on each side after rotation
+ double extraPixels = (diagonal - Math.Max(width, height)) / 2.0;
- generator.Parameters.Barcode.Padding.Left.Point += extraPadding;
- generator.Parameters.Barcode.Padding.Top.Point += extraPadding;
- generator.Parameters.Barcode.Padding.Right.Point += extraPadding;
- generator.Parameters.Barcode.Padding.Bottom.Point += extraPadding;
- }
+ // Convert extra pixels to points (1 point = 1/72 inch, default DPI = 96)
+ float extraPoints = (float)(extraPixels * 72.0 / 96.0);
- // Optional: set background and bar colors for better visibility.
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ // Apply uniform padding on all sides based on the calculated extra space
+ generator.Parameters.Barcode.Padding.Left.Point = extraPoints;
+ generator.Parameters.Barcode.Padding.Top.Point = extraPoints;
+ generator.Parameters.Barcode.Padding.Right.Point = extraPoints;
+ generator.Parameters.Barcode.Padding.Bottom.Point = extraPoints;
+ }
- // Save the rotated barcode image to a file.
- const string outputPath = "rotated_barcode.png";
- generator.Save(outputPath);
- Console.WriteLine($"Barcode saved to {outputPath}");
+ // Save the rotated barcode with the adjusted padding to a PNG file
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
+
+ // Output the full path of the saved barcode image
+ Console.WriteLine($"Barcode saved to '{Path.GetFullPath(outputPath)}'");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/create-utility-that-applies-different-padding-values-per-side-for-various-barcode-symbologies-in-single-workflow.cs b/barcode-appearance-customization/create-utility-that-applies-different-padding-values-per-side-for-various-barcode-symbologies-in-single-workflow.cs
index 5f03524..51a1221 100644
--- a/barcode-appearance-customization/create-utility-that-applies-different-padding-values-per-side-for-various-barcode-symbologies-in-single-workflow.cs
+++ b/barcode-appearance-customization/create-utility-that-applies-different-padding-values-per-side-for-various-barcode-symbologies-in-single-workflow.cs
@@ -1,80 +1,91 @@
-// Title: Barcode padding demonstration per symbology
-// Description: Shows how to apply custom padding values on each side for different barcode types using Aspose.BarCode.
+// Title: Apply per-side padding to multiple barcode symbologies
+// Description: Demonstrates how to set individual padding values for each side of various barcode types using Aspose.BarCode.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing the use of BarcodeGenerator, EncodeTypes, and padding parameters. It helps developers who need fine‑grained control over barcode margins for different symbologies, such as Code128, QR, DataMatrix, PDF417, and GS1 DataBar, and want to output images in common formats.
// Prompt: Create a utility that applies different padding values per side for various barcode symbologies in a single workflow.
-// Tags: barcode symbology, padding, aspose.barcode, image output, csharp
+// Tags: barcode symbology, padding, generation, png, aspose.barcode, encode types
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Demonstrates applying side‑specific padding to various barcode symbologies.
+/// Generates a set of barcodes with custom per‑side padding and saves them as PNG files.
///
class Program
{
///
- /// Entry point. Generates sample barcodes with custom padding and saves them as PNG files.
+ /// Entry point of the utility. Creates an output folder, defines barcode configurations,
+ /// applies side‑specific padding, and saves each barcode image.
///
static void Main()
{
- // Example 1: Code128 with custom padding (left/right 5pt, top/bottom 10pt)
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "CODE128_SAMPLE"))
- {
- // Set individual padding values in points
- generator.Parameters.Barcode.Padding.Left.Point = 5f;
- generator.Parameters.Barcode.Padding.Top.Point = 10f;
- generator.Parameters.Barcode.Padding.Right.Point = 5f;
- generator.Parameters.Barcode.Padding.Bottom.Point = 10f;
-
- // Save the generated barcode image
- generator.Save("code128.png");
- }
-
- // Example 2: QR Code with uniform small padding (2pt on all sides)
- using (var generator = new BarcodeGenerator(EncodeTypes.QR, "QR_SAMPLE"))
- {
- generator.Parameters.Barcode.Padding.Left.Point = 2f;
- generator.Parameters.Barcode.Padding.Top.Point = 2f;
- generator.Parameters.Barcode.Padding.Right.Point = 2f;
- generator.Parameters.Barcode.Padding.Bottom.Point = 2f;
-
- generator.Save("qr.png");
- }
+ // Create (or reuse) the output directory for generated barcode images.
+ string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ Directory.CreateDirectory(outputFolder);
- // Example 3: DataMatrix with no padding (tight fit)
- using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "DATAMATRIX_SAMPLE"))
+ // Define a collection of barcode configurations, each with its own type, text, padding, and file name.
+ var configs = new[]
{
- generator.Parameters.Barcode.Padding.Left.Point = 0f;
- generator.Parameters.Barcode.Padding.Top.Point = 0f;
- generator.Parameters.Barcode.Padding.Right.Point = 0f;
- generator.Parameters.Barcode.Padding.Bottom.Point = 0f;
-
- generator.Save("datamatrix.png");
- }
+ new
+ {
+ Type = (BaseEncodeType)EncodeTypes.Code128,
+ CodeText = "CODE128_SAMPLE",
+ Padding = new { Left = 5f, Top = 10f, Right = 5f, Bottom = 10f },
+ FileName = "Code128.png"
+ },
+ new
+ {
+ Type = (BaseEncodeType)EncodeTypes.QR,
+ CodeText = "QR_SAMPLE",
+ Padding = new { Left = 2f, Top = 2f, Right = 2f, Bottom = 2f },
+ FileName = "QR.png"
+ },
+ new
+ {
+ Type = (BaseEncodeType)EncodeTypes.DataMatrix,
+ CodeText = "DM_SAMPLE",
+ Padding = new { Left = 0f, Top = 0f, Right = 0f, Bottom = 0f },
+ FileName = "DataMatrix.png"
+ },
+ new
+ {
+ Type = (BaseEncodeType)EncodeTypes.Pdf417,
+ CodeText = "PDF417_SAMPLE",
+ Padding = new { Left = 8f, Top = 4f, Right = 8f, Bottom = 4f },
+ FileName = "Pdf417.png"
+ },
+ new
+ {
+ Type = (BaseEncodeType)EncodeTypes.DatabarStacked,
+ CodeText = "(01)01234567890123",
+ Padding = new { Left = 3f, Top = 6f, Right = 3f, Bottom = 6f },
+ FileName = "DataBarStacked.png"
+ }
+ };
- // Example 4: PDF417 with asymmetric padding (left/right 8pt, top/bottom 4pt)
- using (var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "PDF417_SAMPLE"))
+ // Iterate over each configuration, generate the barcode, apply padding, and save the image.
+ foreach (var cfg in configs)
{
- generator.Parameters.Barcode.Padding.Left.Point = 8f;
- generator.Parameters.Barcode.Padding.Top.Point = 4f;
- generator.Parameters.Barcode.Padding.Right.Point = 8f;
- generator.Parameters.Barcode.Padding.Bottom.Point = 4f;
+ string outputPath = Path.Combine(outputFolder, cfg.FileName);
+ using (var generator = new BarcodeGenerator(cfg.Type, cfg.CodeText))
+ {
+ // Apply per‑side padding (values are specified in points).
+ generator.Parameters.Barcode.Padding.Left.Point = cfg.Padding.Left;
+ generator.Parameters.Barcode.Padding.Top.Point = cfg.Padding.Top;
+ generator.Parameters.Barcode.Padding.Right.Point = cfg.Padding.Right;
+ generator.Parameters.Barcode.Padding.Bottom.Point = cfg.Padding.Bottom;
- generator.Save("pdf417.png");
- }
-
- // Example 5: Aztec with distinct side padding (left/right 3pt, top/bottom 6pt)
- using (var generator = new BarcodeGenerator(EncodeTypes.Aztec, "AZTEC_SAMPLE"))
- {
- generator.Parameters.Barcode.Padding.Left.Point = 3f;
- generator.Parameters.Barcode.Padding.Top.Point = 6f;
- generator.Parameters.Barcode.Padding.Right.Point = 3f;
- generator.Parameters.Barcode.Padding.Bottom.Point = 6f;
+ // Set the bar color to black (optional visual customization).
+ generator.Parameters.Barcode.BarColor = Color.Black;
- generator.Save("aztec.png");
+ // Save the generated barcode as a PNG image.
+ generator.Save(outputPath, BarCodeImageFormat.Png);
+ Console.WriteLine($"Saved {cfg.FileName} with custom padding to {outputPath}");
+ }
}
- // Inform the user that generation is complete
- Console.WriteLine("Barcodes generated with custom padding.");
+ Console.WriteLine("Barcode generation completed.");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/design-configuration-file-format-to-store-barcode-appearance-settings-such-as-autosizemode-xdimension-and-padding-values.cs b/barcode-appearance-customization/design-configuration-file-format-to-store-barcode-appearance-settings-such-as-autosizemode-xdimension-and-padding-values.cs
index 983bbb9..9f7a4b2 100644
--- a/barcode-appearance-customization/design-configuration-file-format-to-store-barcode-appearance-settings-such-as-autosizemode-xdimension-and-padding-values.cs
+++ b/barcode-appearance-customization/design-configuration-file-format-to-store-barcode-appearance-settings-such-as-autosizemode-xdimension-and-padding-values.cs
@@ -1,113 +1,72 @@
-// Title: Barcode Generation with Configurable Appearance Settings
-// Description: Demonstrates reading barcode appearance options from a JSON configuration file and applying them to an Aspose.BarCode generator.
+// Title: Barcode appearance configuration export/import example
+// Description: Demonstrates how to configure barcode appearance settings, export them to an XML file, and reuse them for generating barcodes.
+// Category-Description: This example belongs to the Aspose.BarCode configuration management category, showcasing the use of BarcodeGenerator, its Parameters, and XML import/export APIs. Developers often need to persist barcode visual settings such as AutoSizeMode, XDimension, and padding for reuse across applications or environments. The snippet illustrates typical workflows for saving and loading these settings.
// Prompt: Design a configuration file format to store barcode appearance settings such as AutoSizeMode, XDimension, and padding values.
-// Tags: barcode, configuration, json, autosizemode, xdimension, padding, aspose.barcode, c#
+// Tags: barcode, configuration, autosizemode, xdimension, padding, export, import, aspose.barcode, code128, png
using System;
using System.IO;
-using System.Text.Json;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-namespace BarcodeConfigDemo
+///
+/// Demonstrates exporting and importing barcode appearance settings using Aspose.BarCode.
+///
+class Program
{
///
- /// Represents the structure of the configuration file.
- /// The file is a simple JSON document, e.g.:
- /// {
- /// "AutoSizeMode": "Interpolation",
- /// "XDimension": 2.5,
- /// "Padding": { "Left": 5, "Top": 5, "Right": 5, "Bottom": 5 }
- /// }
+ /// Entry point. Creates a barcode, saves its appearance to XML, generates an image, then reloads the settings to create another barcode.
///
- public class BarcodeConfig
+ static void Main()
{
- // AutoSizeMode as a string; will be parsed to the corresponding enum.
- public string AutoSizeMode { get; set; } = "None";
+ // Define file paths for the configuration XML and generated images
+ string xmlPath = "barcodeSettings.xml";
+ string imagePath = "barcode.png";
- // Module size of the barcode (in points).
- public float XDimension { get; set; } = 1.0f;
-
- // Padding values around the barcode.
- public PaddingConfig Padding { get; set; } = new PaddingConfig();
- }
-
- ///
- /// Holds padding values for each side of the barcode.
- ///
- public class PaddingConfig
- {
- public float Left { get; set; } = 0f;
- public float Top { get; set; } = 0f;
- public float Right { get; set; } = 0f;
- public float Bottom { get; set; } = 0f;
- }
-
- class Program
- {
- ///
- /// Entry point of the demo. Reads configuration, creates a barcode, and saves it as an image.
- ///
- static void Main()
+ // -----------------------------------------------------------------
+ // Create a barcode generator, configure appearance settings, and save
+ // the configuration to an XML file.
+ // -----------------------------------------------------------------
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- const string configFile = "barcodeConfig.json";
-
- // Ensure a configuration file exists; create a default one if missing.
- if (!File.Exists(configFile))
- {
- var defaultConfig = new BarcodeConfig
- {
- AutoSizeMode = "Interpolation",
- XDimension = 2.5f,
- Padding = new PaddingConfig { Left = 5f, Top = 5f, Right = 5f, Bottom = 5f }
- };
- var json = JsonSerializer.Serialize(defaultConfig, new JsonSerializerOptions { WriteIndented = true });
- File.WriteAllText(configFile, json);
- Console.WriteLine($"Created default configuration file: {configFile}");
- }
+ // Auto-size the barcode using interpolation mode
+ generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- // Load configuration from the JSON file.
- BarcodeConfig config;
- try
- {
- var json = File.ReadAllText(configFile);
- config = JsonSerializer.Deserialize(json);
- if (config == null)
- throw new InvalidOperationException("Configuration deserialization resulted in null.");
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Failed to read configuration: {ex.Message}");
- return;
- }
+ // Set the module size (XDimension) to 2 points
+ generator.Parameters.Barcode.XDimension.Point = 2f;
- // Convert the AutoSizeMode string to the corresponding enum value.
- if (!Enum.TryParse(config.AutoSizeMode, ignoreCase: true, out var autoSizeMode))
- {
- Console.WriteLine($"Invalid AutoSizeMode value: {config.AutoSizeMode}");
- return;
- }
+ // Apply uniform padding of 5 points on all sides
+ 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;
- // Create a barcode generator and apply settings from the configuration.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
- {
- // Apply AutoSizeMode.
- generator.Parameters.AutoSizeMode = autoSizeMode;
+ // Export the current settings to an XML configuration file
+ generator.ExportToXml(xmlPath);
- // Apply XDimension (module size) using the Point unit.
- generator.Parameters.Barcode.XDimension.Point = config.XDimension;
+ // Save a sample barcode image using the configured settings
+ generator.Save(imagePath, BarCodeImageFormat.Png);
+ }
- // Apply padding for each side.
- generator.Parameters.Barcode.Padding.Left.Point = config.Padding.Left;
- generator.Parameters.Barcode.Padding.Top.Point = config.Padding.Top;
- generator.Parameters.Barcode.Padding.Right.Point = config.Padding.Right;
- generator.Parameters.Barcode.Padding.Bottom.Point = config.Padding.Bottom;
+ // -----------------------------------------------------------------
+ // Load the barcode appearance settings from the XML file and generate
+ // a new barcode to demonstrate that the configuration is applied.
+ // -----------------------------------------------------------------
+ if (File.Exists(xmlPath))
+ {
+ using (var loadedGenerator = BarcodeGenerator.ImportFromXml(xmlPath))
+ {
+ // Change the encoded text to verify that settings are retained
+ loadedGenerator.CodeText = "Loaded123";
- // Save the generated barcode image.
- const string outputFile = "barcode.png";
- generator.Save(outputFile);
- Console.WriteLine($"Barcode generated and saved to {outputFile}");
+ string loadedImagePath = "barcode_loaded.png";
+ loadedGenerator.Save(loadedImagePath, BarCodeImageFormat.Png);
+ Console.WriteLine($"Barcode generated with loaded settings saved to {loadedImagePath}");
}
}
+ else
+ {
+ Console.WriteLine($"Configuration file not found: {xmlPath}");
+ }
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/develop-function-that-switches-autosizemode-between-interpolation-and-nearest-based-on-user-selected-image-dimensions.cs b/barcode-appearance-customization/develop-function-that-switches-autosizemode-between-interpolation-and-nearest-based-on-user-selected-image-dimensions.cs
index 95bfc56..8065e9b 100644
--- a/barcode-appearance-customization/develop-function-that-switches-autosizemode-between-interpolation-and-nearest-based-on-user-selected-image-dimensions.cs
+++ b/barcode-appearance-customization/develop-function-that-switches-autosizemode-between-interpolation-and-nearest-based-on-user-selected-image-dimensions.cs
@@ -1,68 +1,74 @@
-// Title: Barcode AutoSizeMode Selection Based on Image Dimensions
-// Description: Demonstrates how to choose the AutoSizeMode (Interpolation or Nearest) for a barcode image according to its width and height, then generate and save the barcode.
+// Title: AutoSizeMode selection based on image dimensions
+// Description: Demonstrates switching Aspose.BarCode AutoSizeMode between Interpolation and Nearest depending on requested barcode image size.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to control image scaling using the AutoSizeMode property of BarcodeGenerator. It shows typical use cases such as adjusting rendering quality for large versus small barcodes, using classes like BarcodeGenerator, EncodeTypes, and BarCodeImageFormat. Developers often need to balance performance and visual fidelity when generating barcodes at various dimensions.
// Prompt: Develop a function that switches AutoSizeMode between Interpolation and Nearest based on user‑selected image dimensions.
-// Tags: barcode, autosizemode, interpolation, nearest, image dimensions, aspose.barcode, c#
+// Tags: code128, autosizemode, png, barcodegenerator, aspose.barcode, image-scaling
+
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
///
-/// Example program that selects an appropriate for a barcode
-/// based on the provided image dimensions and generates the barcode image.
+/// Demonstrates dynamic selection of AutoSizeMode for barcode generation based on image dimensions.
///
class Program
{
- ///
- /// Determines based on image dimensions.
- /// If width is greater than or equal to height, returns ;
- /// otherwise, returns .
- ///
- /// Image width in pixels.
- /// Image height in pixels.
- /// Chosen .
- static AutoSizeMode DetermineAutoSizeMode(int width, int height)
+ // Determines which AutoSizeMode to use based on the requested image dimensions.
+ // For this example, larger images use Interpolation, smaller ones use Nearest.
+ static AutoSizeMode DetermineAutoSizeMode(float width, float height)
{
- // Use Interpolation when the image is landscape or square; otherwise use Nearest.
- return width >= height ? AutoSizeMode.Interpolation : AutoSizeMode.Nearest;
+ // Thresholds can be adjusted as needed.
+ if (width > 300f || height > 150f)
+ {
+ return AutoSizeMode.Interpolation;
+ }
+ else
+ {
+ return AutoSizeMode.Nearest;
+ }
}
- ///
- /// Entry point. Generates a barcode using the selected
- /// and saves it to a PNG file.
- ///
- static void Main()
+ // Generates a barcode image with the specified dimensions and saves it to the given path.
+ static void GenerateBarcode(string outputPath, float width, float height)
{
- // Sample image dimensions (replace with actual user input as needed).
- int imageWidth = 300; // pixels
- int imageHeight = 150; // pixels
-
- // Choose the appropriate AutoSizeMode based on dimensions.
- AutoSizeMode mode = DetermineAutoSizeMode(imageWidth, imageHeight);
+ // Ensure the output directory exists.
+ string directory = Path.GetDirectoryName(outputPath);
+ if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
+ {
+ Directory.CreateDirectory(directory);
+ }
- // Create a barcode generator for Code128 with sample codetext.
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- // Apply the selected AutoSizeMode.
- generator.Parameters.AutoSizeMode = mode;
+ // Choose AutoSizeMode based on dimensions.
+ generator.Parameters.AutoSizeMode = DetermineAutoSizeMode(width, height);
- // Set the target image size using point units.
- generator.Parameters.ImageWidth.Point = (float)imageWidth;
- generator.Parameters.ImageHeight.Point = (float)imageHeight;
+ // Set the target image size. These unit members must be used.
+ generator.Parameters.ImageWidth.Point = width;
+ generator.Parameters.ImageHeight.Point = height;
- // Optional visual settings.
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ // Optional: set a background and bar color for visibility.
generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- generator.Parameters.Resolution = 96; // DPI
-
- // Determine output file name based on the chosen mode.
- string fileName = mode == AutoSizeMode.Interpolation
- ? "barcode_interpolation.png"
- : "barcode_nearest.png";
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
- // Save the barcode image to disk.
- generator.Save(fileName);
- Console.WriteLine($"Barcode saved as {fileName} with AutoSizeMode {mode}");
+ // Save the barcode as PNG.
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
}
+
+ ///
+ /// Entry point that generates sample barcodes with different sizes to showcase AutoSizeMode switching.
+ ///
+ static void Main()
+ {
+ // Example 1: Larger dimensions -> Interpolation mode.
+ GenerateBarcode("barcode_large.png", 400f, 200f);
+
+ // Example 2: Smaller dimensions -> Nearest mode.
+ GenerateBarcode("barcode_small.png", 200f, 100f);
+
+ Console.WriteLine("Barcodes generated successfully.");
+ }
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/develop-method-to-calculate-optimal-xdimension-based-on-desired-image-width-and-barcode-symbology-specifications.cs b/barcode-appearance-customization/develop-method-to-calculate-optimal-xdimension-based-on-desired-image-width-and-barcode-symbology-specifications.cs
index fe92191..7c9337e 100644
--- a/barcode-appearance-customization/develop-method-to-calculate-optimal-xdimension-based-on-desired-image-width-and-barcode-symbology-specifications.cs
+++ b/barcode-appearance-customization/develop-method-to-calculate-optimal-xdimension-based-on-desired-image-width-and-barcode-symbology-specifications.cs
@@ -1,123 +1,108 @@
-// Title: Calculate optimal XDimension for barcode generation
-// Description: Demonstrates how to compute the XDimension (module size) to achieve a desired image width for a given barcode symbology and data.
+// Title: Barcode XDimension Optimizer
+// Description: Demonstrates calculating the optimal XDimension for a barcode to match a target image width.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator, EncodeTypes, and AutoSizeMode to control module size. Developers often need to fit barcodes into predefined layouts, requiring precise dimension calculations. The snippet shows measuring generated image size and adjusting XDimension accordingly.
// Prompt: Develop a method to calculate optimal XDimension based on desired image width and barcode symbology specifications.
-// Tags: barcode symbology, xdimension calculation, aspose.barcode, image generation, csharp
+// Tags: barcode symbology, xdimension calculation, image width, aspose.barcode, generation
using System;
-using System.Collections.Generic;
+using System.IO;
using System.Reflection;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
-///
-/// Example program that calculates an optimal XDimension for a barcode and generates the image.
-///
-class Program
+namespace BarcodeXDimensionCalculator
{
///
- /// Entry point. Calculates XDimension, resolves the symbology, and generates a barcode image.
+ /// Provides an example of calculating the optimal XDimension (module size) for a barcode
+ /// so that the generated image matches a desired width.
///
- static void Main()
+ class Program
{
- // Desired image width in pixels
- float desiredWidth = 300f;
-
- // Sample barcode data
- string codeText = "1234567890";
-
- // Symbology name (must match a field name in EncodeTypes)
- string symbologyName = "Code128";
-
- // Calculate optimal XDimension based on desired width and symbology
- float xDimension = CalculateOptimalXDimension(desiredWidth, symbologyName, codeText);
- if (xDimension <= 0f)
+ ///
+ /// Entry point of the example. Sets up sample data, invokes the calculation,
+ /// and outputs the resulting XDimension.
+ ///
+ static void Main()
{
- Console.WriteLine("Failed to calculate XDimension.");
- return;
+ // Sample inputs
+ string symbologyName = "Code128";
+ string codeText = "1234567890";
+ float desiredWidth = 300f; // Desired image width in pixels
+
+ try
+ {
+ // Calculate the optimal XDimension based on inputs
+ float optimalX = CalculateOptimalXDimension(symbologyName, codeText, desiredWidth);
+ Console.WriteLine($"Optimal XDimension for {symbologyName} with width {desiredWidth} px: {optimalX} pt");
+ }
+ catch (Exception ex)
+ {
+ // Output any errors that occur during calculation
+ Console.WriteLine($"Error: {ex.Message}");
+ }
}
- // Resolve symbology to BaseEncodeType using reflection
- var field = typeof(EncodeTypes).GetField(symbologyName);
- if (field == null)
+ ///
+ /// Calculates the optimal XDimension (module size) so that the generated barcode image
+ /// matches the desired width as closely as possible.
+ ///
+ /// Name of the barcode symbology (e.g., "Code128").
+ /// Text to encode.
+ /// Desired image width in pixels.
+ /// Calculated XDimension in points.
+ static float CalculateOptimalXDimension(string symbologyName, string codeText, float desiredWidth)
{
- Console.WriteLine($"Unknown symbology: {symbologyName}");
- return;
- }
- BaseEncodeType encodeType = (BaseEncodeType)field.GetValue(null);
-
- // Generate barcode with the calculated XDimension
- using (var generator = new BarcodeGenerator(encodeType, codeText))
- {
- // Disable auto‑size to use explicit XDimension
- generator.Parameters.AutoSizeMode = AutoSizeMode.None;
-
- // Apply calculated XDimension (in points)
- generator.Parameters.Barcode.XDimension.Point = xDimension;
-
- // Save the barcode image to file
- generator.Save("barcode.png");
+ // Validate symbology name
+ if (string.IsNullOrWhiteSpace(symbologyName))
+ throw new ArgumentException("Symbology name must be provided.", nameof(symbologyName));
+
+ // Validate desired width
+ if (desiredWidth <= 0f)
+ throw new ArgumentOutOfRangeException(nameof(desiredWidth), "Desired width must be greater than zero.");
+
+ // Resolve the symbology name to a BaseEncodeType using reflection.
+ FieldInfo field = typeof(EncodeTypes).GetField(symbologyName);
+ if (field == null)
+ throw new ArgumentException($"Unknown symbology: {symbologyName}", nameof(symbologyName));
+
+ BaseEncodeType encodeType = (BaseEncodeType)field.GetValue(null);
+
+ // Create a barcode generator with a default XDimension.
+ using (var generator = new BarcodeGenerator(encodeType, codeText))
+ {
+ // Disable automatic sizing to work with explicit XDimension.
+ generator.Parameters.AutoSizeMode = AutoSizeMode.None;
+
+ // Set an initial XDimension (points). This value will be adjusted.
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+
+ // Generate the barcode image to measure its current width.
+ using (Bitmap bitmap = generator.GenerateBarCodeImage())
+ {
+ int actualWidth = bitmap.Width;
+ if (actualWidth == 0)
+ throw new InvalidOperationException("Generated barcode has zero width.");
+
+ // Compute scaling factor needed to reach the desired width.
+ float scale = desiredWidth / actualWidth;
+
+ // Calculate the optimal XDimension based on the scale.
+ float optimalX = generator.Parameters.Barcode.XDimension.Point * scale;
+
+ // Apply the optimal XDimension back to the generator.
+ generator.Parameters.Barcode.XDimension.Point = optimalX;
+
+ // Optional: regenerate and save the barcode to verify the size.
+ // using (var output = new FileStream("optimal_barcode.png", FileMode.Create, FileAccess.Write))
+ // {
+ // generator.Save(output, BarCodeImageFormat.Png);
+ // }
+
+ return optimalX;
+ }
+ }
}
-
- Console.WriteLine($"Barcode generated with XDimension = {xDimension}pt (desired width {desiredWidth}px).");
- }
-
- ///
- /// Calculates an approximate optimal XDimension (module size) so that the generated barcode
- /// width is close to the desired image width. The calculation uses a simple estimation of
- /// the number of modules based on the symbology and the length of the codetext.
- ///
- /// Desired image width in pixels.
- /// Name of the symbology (e.g., "Code128").
- /// The text to encode.
- /// Calculated XDimension in points; returns 0 if calculation cannot be performed.
- static float CalculateOptimalXDimension(float desiredWidth, string symbologyName, string codeText)
- {
- // Validate input parameters
- if (desiredWidth <= 0f)
- throw new ArgumentOutOfRangeException(nameof(desiredWidth), "Desired width must be positive.");
- if (string.IsNullOrEmpty(codeText))
- throw new ArgumentException("Code text cannot be null or empty.", nameof(codeText));
-
- // Approximate modules per character for common symbologies.
- // These values are rough estimates and may vary per implementation.
- var modulesPerCharMap = new Dictionary(StringComparer.OrdinalIgnoreCase)
- {
- { "Code128", 11 },
- { "Code39", 13 },
- { "EAN13", 95 }, // Fixed length for EAN13
- { "QRCode", 0 }, // QR codes have variable module count; handled separately
- { "DataMatrix", 0 } // Handled separately
- };
-
- int totalModules;
-
- // Determine total module count based on symbology
- if (modulesPerCharMap.TryGetValue(symbologyName, out int modulesPerChar) && modulesPerChar > 0)
- {
- // Simple linear estimate: modules = characters * modules per character
- totalModules = codeText.Length * modulesPerChar;
- }
- else if (symbologyName.Equals("QRCode", StringComparison.OrdinalIgnoreCase) ||
- symbologyName.Equals("DataMatrix", StringComparison.OrdinalIgnoreCase))
- {
- // For 2D barcodes, estimate a square matrix where modules ≈ sqrt(desiredWidth / desiredModuleSize)
- // Assume a default module count of 21 (Version 1 QR) for estimation.
- totalModules = 21;
- }
- else
- {
- Console.WriteLine($"Symbology '{symbologyName}' not recognized for XDimension calculation.");
- return 0f;
- }
-
- // Convert desired width (pixels) to points.
- // For simplicity, treat 1 pixel ≈ 1 point in this context.
- float xDim = desiredWidth / totalModules;
-
- // Ensure a minimum reasonable size
- if (xDim < 0.5f)
- xDim = 0.5f;
-
- return xDim;
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/enable-barwidthreduction-to-improve-readability-of-dense-pdf417-barcodes-at-600-dpi-output.cs b/barcode-appearance-customization/enable-barwidthreduction-to-improve-readability-of-dense-pdf417-barcodes-at-600-dpi-output.cs
index 7eec7f8..3f6e160 100644
--- a/barcode-appearance-customization/enable-barwidthreduction-to-improve-readability-of-dense-pdf417-barcodes-at-600-dpi-output.cs
+++ b/barcode-appearance-customization/enable-barwidthreduction-to-improve-readability-of-dense-pdf417-barcodes-at-600-dpi-output.cs
@@ -1,45 +1,43 @@
-// Title: PDF417 Barcode Generation with Bar Width Reduction
-// Description: Demonstrates generating a dense PDF417 barcode, applying bar‑width reduction to improve readability at 600 dpi, and saving it as PNG.
+// Title: Enable BarWidthReduction for dense PDF417 barcode at 600 dpi
+// Description: Demonstrates how to generate a high‑resolution PDF417 barcode and improve its readability by applying bar‑width reduction.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on PDF417 symbology configuration. It shows how to adjust resolution and bar‑width reduction using the BarcodeGenerator and its Parameters properties. Developers creating dense PDF417 barcodes for print or high‑dpi displays often need these settings to ensure scannability.
// Prompt: Enable BarWidthReduction to improve readability of dense PDF417 barcodes at 600 dpi output.
-// Tags: pdf417, barcode, bar width reduction, resolution, png, aspose.barcode
+// Tags: pdf417, barwidthreduction, resolution, png, barcodegenerator, generation, aspose.barcode
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Example program that creates a PDF417 barcode with bar‑width reduction enabled.
+/// Generates a PDF417 barcode with bar‑width reduction applied to improve readability at 600 dpi.
///
class Program
{
///
- /// Entry point. Generates a dense PDF417 barcode, configures high‑resolution settings,
- /// enables bar‑width reduction, and saves the result as a PNG file.
+ /// Entry point of the example. Creates a PDF417 barcode, configures resolution and bar‑width reduction, and saves it as a PNG image.
///
static void Main()
{
- // Define the barcode content – dense data benefits most from bar‑width reduction.
- string codeText = "Sample PDF417 dense data for testing bar width reduction.";
- // Output file path.
- string outputPath = "pdf417.png";
+ // Sample dense data for PDF417
+ string codeText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
+ "Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. " +
+ "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";
- // Create a BarcodeGenerator for PDF417 with the specified text.
+ // Initialize a PDF417 barcode generator with the sample text
using (var generator = new BarcodeGenerator(EncodeTypes.Pdf417, codeText))
{
- // Set the image resolution to 600 dpi for high‑quality output.
+ // Set the output resolution to 600 dpi for high‑quality rendering
generator.Parameters.Resolution = 600;
- // Reduce the bar width by 0.2 points to compensate for ink spread at high DPI.
- generator.Parameters.Barcode.BarWidthReduction.Point = 0.2f;
+ // Enable bar‑width reduction (in points) to make dense barcodes more readable
+ // Adjust the value as needed; 0.5 points is a typical starting point
+ generator.Parameters.Barcode.BarWidthReduction.Point = 0.5f;
- // Use interpolation mode so the barcode size is controlled via image dimensions.
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
-
- // Save the generated barcode image as a PNG file.
- generator.Save(outputPath, BarCodeImageFormat.Png);
+ // Save the generated barcode as a PNG image file
+ generator.Save("pdf417.png");
}
- // Inform the user where the barcode image was saved.
- Console.WriteLine($"PDF417 barcode saved to {outputPath}");
+ // Inform the user that the barcode has been generated
+ Console.WriteLine("PDF417 barcode generated with BarWidthReduction at 600 dpi.");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/generate-barcode-image-using-autosizemodenearest-providing-only-imageheight-and-imagewidth-parameters.cs b/barcode-appearance-customization/generate-barcode-image-using-autosizemodenearest-providing-only-imageheight-and-imagewidth-parameters.cs
index 911c706..aa9e449 100644
--- a/barcode-appearance-customization/generate-barcode-image-using-autosizemodenearest-providing-only-imageheight-and-imagewidth-parameters.cs
+++ b/barcode-appearance-customization/generate-barcode-image-using-autosizemodenearest-providing-only-imageheight-and-imagewidth-parameters.cs
@@ -1,37 +1,43 @@
-// Title: Generate barcode with AutoSizeMode.Nearest using only image dimensions
-// Description: Demonstrates creating a Code128 barcode image by setting AutoSizeMode to Nearest and specifying only ImageWidth and ImageHeight. Useful for quickly generating barcodes with desired size without manual scaling.
+// Title: Generate barcode with AutoSizeMode.Nearest using image dimensions
+// Description: Demonstrates creating a Code128 barcode image by specifying only the image height and width while using AutoSizeMode.Nearest for automatic sizing.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure AutoSizeMode and image dimensions. It uses BarcodeGenerator, EncodeTypes, AutoSizeMode, and BarCodeImageFormat classes. Typical use cases include generating barcode images for labels, invoices, or web applications where precise image size is required. Developers often need to control output size while letting the library adjust barcode scaling automatically.
// Prompt: Generate a barcode image using AutoSizeMode.Nearest, providing only ImageHeight and ImageWidth parameters.
-// Tags: code128, barcode, autosizemode, nearest, imagegeneration, aspnet, csharp
+// Tags: code128, autosizemode, nearest, imagewidth, imageheight, png, generation, aspose.barcode
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Example program that generates a Code128 barcode image using AutoSizeMode.Nearest.
+/// Example program that generates a Code128 barcode image using AutoSizeMode.Nearest,
+/// specifying only the desired image width and height.
///
class Program
{
///
- /// Entry point. Creates a barcode generator, configures size, saves the image, and writes a confirmation to console.
+ /// Entry point of the application. Creates a barcode, configures sizing, and saves it as PNG.
///
static void Main()
{
- // Initialize a barcode generator for Code128 with sample text.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
+ // Define the output file path for the generated barcode image.
+ const string outputPath = "barcode.png";
+
+ // Initialize the barcode generator with Code128 symbology and sample data.
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Set AutoSizeMode to Nearest to let the library choose the best size.
+ // Set the automatic sizing mode to Nearest so the library adjusts the barcode
+ // to best fit the specified image dimensions.
generator.Parameters.AutoSizeMode = AutoSizeMode.Nearest;
- // Define only the image dimensions (width and height) in points.
- generator.Parameters.ImageWidth.Point = 300f; // Width in points.
- generator.Parameters.ImageHeight.Point = 150f; // Height in points.
+ // Specify the desired image width and height in points (1 point = 1/72 inch).
+ generator.Parameters.ImageWidth.Point = 300f;
+ generator.Parameters.ImageHeight.Point = 150f;
- // Save the generated barcode image to a PNG file.
- generator.Save("barcode.png");
+ // 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 created.
- Console.WriteLine("Barcode image generated: barcode.png");
+ // Inform the user that the barcode image has been saved.
+ Console.WriteLine($"Barcode image saved to '{outputPath}'.");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/generate-barcode-with-non-square-aspect-ratio-by-setting-imageheight-lower-than-imagewidth-in-interpolation-mode.cs b/barcode-appearance-customization/generate-barcode-with-non-square-aspect-ratio-by-setting-imageheight-lower-than-imagewidth-in-interpolation-mode.cs
index 95f96da..c29b546 100644
--- a/barcode-appearance-customization/generate-barcode-with-non-square-aspect-ratio-by-setting-imageheight-lower-than-imagewidth-in-interpolation-mode.cs
+++ b/barcode-appearance-customization/generate-barcode-with-non-square-aspect-ratio-by-setting-imageheight-lower-than-imagewidth-in-interpolation-mode.cs
@@ -1,7 +1,8 @@
-// Title: Generate non-square barcode using Interpolation mode
-// Description: Demonstrates creating a Code128 barcode with a rectangular aspect ratio by setting ImageWidth larger than ImageHeight in Interpolation auto-size mode.
+// Title: Generate non‑square barcode using Interpolation mode
+// Description: Demonstrates creating a barcode image where the height is smaller than the width by configuring ImageHeight and ImageWidth in Interpolation auto‑size mode.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to control barcode dimensions with AutoSizeMode.Interpolation. It showcases key classes like BarcodeGenerator, EncodeTypes, and the Parameters property to adjust size, colors, and output format. Developers often need to produce barcodes with custom aspect ratios for UI layouts, printed labels, or integration into graphics where non‑square dimensions are required.
// Prompt: Generate a barcode with a non‑square aspect ratio by setting ImageHeight lower than ImageWidth in Interpolation mode.
-// Tags: code128, barcode, interpolation, imagesize, aspose.barcode, aspose.drawing
+// Tags: code128, barcode generation, image size, interpolation, aspose.barcode, png
using System;
using Aspose.BarCode;
@@ -9,35 +10,38 @@
using Aspose.Drawing;
///
-/// Example program that generates a Code128 barcode with a non‑square aspect ratio
+/// Example program that creates a Code128 barcode with a non‑square aspect ratio
/// using the Interpolation auto‑size mode.
///
class Program
{
///
- /// Entry point. Creates the barcode, configures size and colors, saves the image, and writes a confirmation to the console.
+ /// Entry point of the application. Generates the barcode and saves it as a PNG file.
///
static void Main()
{
- // Initialize a barcode generator for Code128 with the sample text "123456".
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ // Define the output file path for the generated barcode image.
+ string outputPath = "non_square_barcode.png";
+
+ // Initialize a BarcodeGenerator for Code128 with the sample text "123456789".
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789"))
{
- // Switch to Interpolation mode so ImageWidth and ImageHeight directly control the output size.
+ // Set the auto‑size mode to Interpolation so we can specify exact dimensions.
generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- // Define a rectangular (non‑square) size: width larger than height.
- generator.Parameters.ImageWidth.Point = 300f; // Width: 300 points
- generator.Parameters.ImageHeight.Point = 100f; // Height: 100 points
+ // Configure a non‑square aspect ratio: width larger than height.
+ generator.Parameters.ImageWidth.Point = 300f; // Width in points.
+ generator.Parameters.ImageHeight.Point = 100f; // Height in points (lower than width).
- // Optional visual styling: white background and black bars.
- generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ // Optional: set background and barcode colors.
+ generator.Parameters.BackColor = Color.White;
+ generator.Parameters.Barcode.BarColor = Color.Black;
- // Save the generated barcode as a PNG file.
- generator.Save("barcode.png");
+ // Save the generated barcode image to the specified path.
+ generator.Save(outputPath);
}
- // Inform the user that the barcode image has been created.
- Console.WriteLine("Barcode generated: barcode.png");
+ // Inform the user where the barcode image has been saved.
+ Console.WriteLine($"Barcode saved to {outputPath}");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/implement-error-handling-for-invalid-rotationangle-values-exceeding-360-degrees-when-generating-barcode-images.cs b/barcode-appearance-customization/implement-error-handling-for-invalid-rotationangle-values-exceeding-360-degrees-when-generating-barcode-images.cs
index 24fef5b..01b1447 100644
--- a/barcode-appearance-customization/implement-error-handling-for-invalid-rotationangle-values-exceeding-360-degrees-when-generating-barcode-images.cs
+++ b/barcode-appearance-customization/implement-error-handling-for-invalid-rotationangle-values-exceeding-360-degrees-when-generating-barcode-images.cs
@@ -1,58 +1,87 @@
// Title: Barcode Generation with Rotation Angle Validation
-// Description: Demonstrates generating a Code128 barcode image while validating the rotation angle to ensure it does not exceed 360 degrees.
+// Description: Demonstrates generating a Code128 barcode image while validating the rotation angle to ensure it stays within 0‑360 degrees.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode parameters such as rotation, handle invalid input, and save images. It utilizes the BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes—key APIs for developers creating barcodes with custom orientation and robust error handling. Typical use cases include generating printable barcodes for inventory, shipping, or retail applications where rotation must be controlled.
// Prompt: Implement error handling for invalid RotationAngle values exceeding 360 degrees when generating barcode images.
-// Tags: barcode, code128, rotation, validation, image, aspose.barcode
+// Tags: barcode symbology, generation, rotation, validation, png, aspose.barcode, code128
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Example program that creates a barcode image with a validated rotation angle.
+/// Provides an example of generating Code128 barcodes with rotation angle validation using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the application. Generates a barcode and handles invalid rotation angles.
+ /// Entry point of the example. Generates a valid barcode and demonstrates handling of an invalid rotation angle.
///
static void Main()
{
- // Sample rotation angle (intentionally invalid for demonstration)
- float rotationAngle = 400f;
+ // Ensure the output directory exists
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(outputDir))
+ {
+ Directory.CreateDirectory(outputDir);
+ }
+ // -------------------------
+ // Generate a barcode with a valid rotation angle
+ // -------------------------
try
{
- // Validate that the rotation angle is within the allowed range
- ValidateRotationAngle(rotationAngle);
-
- // Create a Code128 barcode generator with the specified data
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
- {
- // Apply the validated rotation angle to the barcode parameters
- generator.Parameters.RotationAngle = rotationAngle;
-
- // Save the generated barcode image to a file
- generator.Save("barcode.png");
+ string validPath = Path.Combine(outputDir, "valid.png");
+ GenerateBarcode("1234567890", 45f, validPath);
+ Console.WriteLine($"Valid barcode saved to: {validPath}");
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Error generating valid barcode: {ex.Message}");
+ }
- // Inform the user of successful generation
- Console.WriteLine("Barcode generated successfully with rotation angle: " + rotationAngle);
- }
+ // -------------------------
+ // Attempt to generate a barcode with an invalid rotation angle (exceeds 360 degrees)
+ // -------------------------
+ try
+ {
+ string invalidPath = Path.Combine(outputDir, "invalid.png");
+ GenerateBarcode("1234567890", 400f, invalidPath);
+ Console.WriteLine($"Invalid barcode saved to: {invalidPath}");
}
catch (ArgumentOutOfRangeException ex)
{
- // Output a clear error message when the rotation angle is invalid
- Console.WriteLine("Error: " + ex.Message);
+ // Expected exception for out-of-range rotation angle
+ Console.WriteLine($"Caught expected exception for invalid rotation angle: {ex.Message}");
+ }
+ catch (Exception ex)
+ {
+ // Any other unexpected errors
+ Console.WriteLine($"Unexpected error: {ex.Message}");
}
}
- // Ensures the rotation angle is within the allowed range [0, 360]
- static void ValidateRotationAngle(float angle)
+ ///
+ /// Generates a barcode image with the specified text, rotation angle, and output path.
+ ///
+ /// The data to encode in the barcode.
+ /// The rotation angle in degrees (0‑360 inclusive).
+ /// The file path where the barcode image will be saved.
+ /// Thrown when rotationAngle is outside the 0‑360 range.
+ static void GenerateBarcode(string codeText, float rotationAngle, string outputPath)
{
- if (angle < 0f || angle > 360f)
+ // Validate rotation angle (must be between 0 and 360 inclusive)
+ if (rotationAngle < 0f || rotationAngle > 360f)
+ {
+ throw new ArgumentOutOfRangeException(nameof(rotationAngle),
+ $"RotationAngle must be between 0 and 360 degrees. Provided value: {rotationAngle}");
+ }
+
+ // Create and configure the barcode generator
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
{
- // Throw an exception with a descriptive message if the angle is out of bounds
- throw new ArgumentOutOfRangeException(nameof(angle),
- $"RotationAngle must be between 0 and 360 degrees. Provided value: {angle}");
+ generator.Parameters.RotationAngle = rotationAngle;
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/implement-feature-that-logs-chosen-autosizemode-and-resulting-image-dimensions-for-each-generated-barcode.cs b/barcode-appearance-customization/implement-feature-that-logs-chosen-autosizemode-and-resulting-image-dimensions-for-each-generated-barcode.cs
index 235d9d6..2c70e5a 100644
--- a/barcode-appearance-customization/implement-feature-that-logs-chosen-autosizemode-and-resulting-image-dimensions-for-each-generated-barcode.cs
+++ b/barcode-appearance-customization/implement-feature-that-logs-chosen-autosizemode-and-resulting-image-dimensions-for-each-generated-barcode.cs
@@ -1,7 +1,8 @@
-// Title: Demonstrate AutoSizeMode effects on barcode image generation
-// Description: Shows how different AutoSizeMode settings affect the size of a generated Code128 barcode and logs the resulting dimensions.
+// Title: Barcode generation with AutoSizeMode logging
+// Description: Demonstrates generating barcodes with different AutoSizeMode settings and logs the selected mode along with the resulting image dimensions.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, showcasing how to configure AutoSizeMode, set target image size, and retrieve image dimensions using BarcodeGenerator and related classes. Developers often need to adjust barcode sizing for various output formats and log details for debugging or reporting purposes.
// Prompt: Implement a feature that logs the chosen AutoSizeMode and resulting image dimensions for each generated barcode.
-// Tags: barcode, autosizemode, code128, image generation, logging
+// Tags: barcode symbology, autosizemode, image generation, logging, aspose.barcode, csharp
using System;
using System.IO;
@@ -11,56 +12,62 @@
using Aspose.Drawing.Imaging;
///
-/// Generates Code128 barcodes using different AutoSizeMode settings and logs image dimensions.
+/// Demonstrates barcode generation with different AutoSizeMode settings and logs details.
///
class Program
{
///
- /// Entry point. Generates barcodes for each AutoSizeMode, saves them, and logs dimensions.
+ /// Entry point. Generates sample barcodes, logs AutoSizeMode and image size, and saves PNG files.
///
static void Main()
{
- // Sample barcode text to encode
- const string codeText = "1234567890";
-
- // Output directory for generated images; ensure it exists
+ // Ensure the output directory exists
string outputDir = "Barcodes";
- Directory.CreateDirectory(outputDir);
+ if (!Directory.Exists(outputDir))
+ {
+ Directory.CreateDirectory(outputDir);
+ }
- // Define the AutoSizeMode variations to test
- AutoSizeMode[] modes = new AutoSizeMode[]
+ // Define sample barcodes together with the desired AutoSizeMode for each
+ var samples = new (BaseEncodeType EncodeType, string CodeText, AutoSizeMode Mode)[]
{
- AutoSizeMode.None,
- AutoSizeMode.Nearest,
- AutoSizeMode.Interpolation
+ (EncodeTypes.Code128, "1234567890", AutoSizeMode.None),
+ (EncodeTypes.QR, "https://example.com", AutoSizeMode.Interpolation),
+ (EncodeTypes.DataMatrix, "DataMatrix Sample", AutoSizeMode.Interpolation)
};
- // Iterate through each mode, generate a barcode, and log its size
- foreach (AutoSizeMode mode in modes)
+ // Process each sample
+ foreach (var sample in samples)
{
- // Create and configure the barcode generator for the current mode
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ // Create a BarcodeGenerator for the specified symbology and code text
+ using (var generator = new BarcodeGenerator(sample.EncodeType, sample.CodeText))
{
- generator.Parameters.AutoSizeMode = mode;
+ // Apply the chosen AutoSizeMode
+ generator.Parameters.AutoSizeMode = sample.Mode;
- // For modes other than None, specify a target image size (in points)
- if (mode != AutoSizeMode.None)
+ // If Interpolation mode is selected, set the target image dimensions
+ if (sample.Mode == AutoSizeMode.Interpolation)
{
generator.Parameters.ImageWidth.Point = 300f;
generator.Parameters.ImageHeight.Point = 150f;
}
- // Build the file path and save the barcode image as PNG
- string filePath = Path.Combine(outputDir, $"{mode}.png");
- generator.Save(filePath, BarCodeImageFormat.Png);
-
- // Load the saved image to obtain its actual dimensions
- using (var image = (Bitmap)Image.FromFile(filePath))
+ // Generate the barcode image as a Bitmap
+ using (Bitmap bitmap = generator.GenerateBarCodeImage())
{
- // Log the AutoSizeMode used and the resulting image width x height
- Console.WriteLine($"AutoSizeMode: {mode}, Image Size: {image.Width}x{image.Height}");
+ // Log the symbology, selected AutoSizeMode, and resulting image size
+ Console.WriteLine($"Symbology: {sample.EncodeType.TypeName}");
+ Console.WriteLine($"AutoSizeMode: {generator.Parameters.AutoSizeMode}");
+ Console.WriteLine($"Image Width: {bitmap.Width}px, Height: {bitmap.Height}px");
+
+ // Build the output file path and save the image as PNG
+ string filePath = Path.Combine(outputDir, $"{sample.EncodeType.TypeName}_{sample.Mode}.png");
+ bitmap.Save(filePath, ImageFormat.Png);
}
}
}
+
+ // Indicate that the process has finished
+ Console.WriteLine("Barcode generation completed.");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/implement-method-that-sets-autosizemode-based-on-target-dpi-choosing-interpolation-for-high-resolution-outputs.cs b/barcode-appearance-customization/implement-method-that-sets-autosizemode-based-on-target-dpi-choosing-interpolation-for-high-resolution-outputs.cs
index dcb3406..383faa2 100644
--- a/barcode-appearance-customization/implement-method-that-sets-autosizemode-based-on-target-dpi-choosing-interpolation-for-high-resolution-outputs.cs
+++ b/barcode-appearance-customization/implement-method-that-sets-autosizemode-based-on-target-dpi-choosing-interpolation-for-high-resolution-outputs.cs
@@ -1,76 +1,82 @@
-// Title: Barcode Generation with DPI‑Based AutoSizeMode
-// Description: Demonstrates setting the AutoSizeMode of a BarcodeGenerator based on the target DPI, using interpolation for high‑resolution outputs.
-// Prompt: Implement a method that sets AutoSizeMode based on target DPI, choosing Interpolation for high‑resolution outputs.
-// Tags: barcode, autosizemode, dpi, interpolation, aspose.barcode, c#
+// Title: AutoSizeMode Configuration Based on DPI
+// Description: Demonstrates setting AutoSizeMode for a barcode generator according to target DPI, using interpolation for high‑resolution outputs.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to control image resolution and sizing via the BarcodeGenerator, AutoSizeMode, and Resolution properties. Typical use cases include creating printable barcodes at various DPI settings, where developers need to switch between default sizing and interpolation for crisp high‑resolution results. Ideal for developers searching for barcode DPI handling, auto‑size configuration, and image scaling techniques in Aspose.BarCode.
+/// Prompt: Implement a method that sets AutoSizeMode based on target DPI, choosing Interpolation for high‑resolution outputs.
+/// Tags: barcode, code128, autosizemode, interpolation, high-resolution, dpi, aspose.barcode, generation
+
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Example program that creates a barcode image and adjusts its AutoSizeMode
-/// according to the desired output DPI.
+/// Provides an example of configuring AutoSizeMode based on target DPI
+/// and generating a barcode image using Aspose.BarCode.
///
class Program
{
///
- /// Sets the AutoSizeMode of the provided based on the target DPI.
- /// For DPI values greater than 300, is used;
- /// otherwise, is applied.
+ /// Configures the AutoSizeMode according to the specified DPI.
+ /// For DPI values greater than 150, Interpolation mode is applied; otherwise, No auto‑sizing is used.
///
/// The barcode generator to configure.
- /// The desired resolution in dots per inch.
- static void SetAutoSizeMode(BarcodeGenerator generator, float targetDpi)
+ /// The desired image resolution in dots per inch.
+ static void ConfigureAutoSize(BarcodeGenerator generator, float targetDpi)
{
- // Validate input arguments.
- if (generator == null)
- throw new ArgumentNullException(nameof(generator));
-
- if (targetDpi <= 0f)
- throw new ArgumentOutOfRangeException(nameof(targetDpi), "DPI must be greater than zero.");
-
- // Apply the requested resolution to the generator.
+ // Set the resolution for the barcode image.
generator.Parameters.Resolution = targetDpi;
- if (targetDpi > 300f)
+ if (targetDpi > 150f)
{
- // High‑resolution output: enable interpolation auto‑sizing.
+ // High‑resolution output: enable interpolation.
generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- // Example dimensions – adjust as needed for your use case.
- generator.Parameters.ImageWidth.Point = 400f;
- generator.Parameters.ImageHeight.Point = 150f;
+ // When using interpolation, control the final size via ImageWidth/ImageHeight.
+ generator.Parameters.ImageWidth.Point = 300f; // example width
+ generator.Parameters.ImageHeight.Point = 150f; // example height
}
else
{
- // Lower DPI: keep default sizing (no auto‑size).
+ // Standard resolution: no automatic resizing.
generator.Parameters.AutoSizeMode = AutoSizeMode.None;
}
}
///
- /// Entry point of the example. Generates a Code128 barcode, configures DPI‑based
- /// auto‑size settings, and saves the image to disk.
+ /// Entry point of the example. Generates a Code128 barcode image with DPI‑based auto‑size settings.
///
static void Main()
{
- // Create a barcode generator for Code128 with sample numeric data.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
- {
- // Define the target DPI for the output image.
- float targetDpi = 350f; // Modify to test different DPI thresholds.
+ // Sample barcode data.
+ const string codeText = "1234567890";
- // Configure the generator's AutoSizeMode based on the target DPI.
- SetAutoSizeMode(generator, targetDpi);
+ // Desired DPI for the output image (high‑resolution example).
+ const float targetDpi = 300f;
- // Optional: set a foreground color to illustrate additional parameter usage.
- generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.DarkBlue;
+ // Determine the output file path.
+ string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "barcode.png");
- // Save the generated barcode image to a file.
- string outputPath = "barcode.png";
- generator.Save(outputPath);
+ try
+ {
+ // Initialize the barcode generator with Code128 symbology.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ {
+ // Optional: set a foreground color.
+ generator.Parameters.Barcode.BarColor = Color.Black;
- // Inform the user about the saved file and the applied settings.
- Console.WriteLine($"Barcode saved to '{outputPath}' with DPI {targetDpi} and AutoSizeMode {generator.Parameters.AutoSizeMode}.");
+ // Apply DPI‑based auto‑size configuration.
+ ConfigureAutoSize(generator, targetDpi);
+
+ // Save the generated barcode image to the specified path.
+ generator.Save(outputPath);
+ }
+
+ Console.WriteLine($"Barcode saved to: {outputPath}");
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Error generating barcode: {ex.Message}");
}
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/integrate-barcode-generation-into-api-that-accepts-json-payload-specifying-appearance-options-and-returns-png-stream.cs b/barcode-appearance-customization/integrate-barcode-generation-into-api-that-accepts-json-payload-specifying-appearance-options-and-returns-png-stream.cs
index 869f487..65ec0c2 100644
--- a/barcode-appearance-customization/integrate-barcode-generation-into-api-that-accepts-json-payload-specifying-appearance-options-and-returns-png-stream.cs
+++ b/barcode-appearance-customization/integrate-barcode-generation-into-api-that-accepts-json-payload-specifying-appearance-options-and-returns-png-stream.cs
@@ -1,7 +1,8 @@
-// Title: Barcode Generation API Example
-// Description: Demonstrates how to accept a JSON payload with appearance options, generate a barcode, and return a PNG byte stream.
+// Title: Barcode generation API simulation with JSON payload
+// Description: Demonstrates how to accept a JSON request describing barcode appearance, generate the barcode using Aspose.BarCode, and return a PNG byte array.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and image formatting options. It shows typical use cases such as creating QR codes or linear barcodes with custom dimensions, colors, and padding, which developers often need when building web APIs that serve barcode images.
// Prompt: Integrate barcode generation into an API that accepts JSON payload specifying appearance options and returns a PNG stream.
-// Tags: barcode, generation, json, api, png, aspose
+// Tags: barcode, generation, json, api, png, aspose.barcode, encode-types, appearance
using System;
using System.IO;
@@ -9,104 +10,124 @@
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
namespace BarcodeApiSimulation
{
- // DTO for JSON payload
+ ///
+ /// Represents the JSON payload for barcode generation.
+ ///
public class BarcodeRequest
{
- public string Symbology { get; set; }
- public string CodeText { get; set; }
- public string ForeColor { get; set; } // Hex, e.g. "#FF0000"
- public string BackColor { get; set; } // Hex, e.g. "#FFFFFF"
- public float? ImageWidth { get; set; } // Points
- public float? ImageHeight { get; set; } // Points
- public float? XDimension { get; set; } // Points
- public float? BarHeight { get; set; } // Points (used only when AutoSizeMode = None)
- public string AutoSizeMode { get; set; } // "None", "Interpolation", "Nearest"
+ public string Symbology { get; set; } // e.g., "Code128", "QR"
+ public string CodeText { get; set; } // Text to encode
+ public AppearanceOptions Appearance { get; set; } // Optional appearance settings
}
///
- /// Simulates an API that generates barcodes from JSON requests.
+ /// Appearance options that can be supplied in the JSON payload.
+ ///
+ public class AppearanceOptions
+ {
+ public float? ImageWidth { get; set; } // Width in points
+ public float? ImageHeight { get; set; } // Height in points
+ public string ForegroundColor { get; set; } // Hex color, e.g., "#FF0000"
+ public string BackgroundColor { get; set; } // Hex color, e.g., "#FFFFFF"
+ public float? Padding { get; set; } // Uniform padding in points
+ }
+
+ ///
+ /// Simulates an API that receives a JSON payload describing barcode parameters,
+ /// generates the barcode image, and returns the PNG data.
///
class Program
{
///
- /// Parses a hex color string (e.g. "#RRGGBB") into an Aspose.Drawing.Color.
+ /// Entry point demonstrating the JSON deserialization, barcode generation,
+ /// and saving the resulting PNG to disk.
///
- /// Hexadecimal color string.
- /// Corresponding Color object.
- private static Color ParseColor(string hex)
+ static void Main()
{
- if (string.IsNullOrWhiteSpace(hex))
- throw new ArgumentException("Color string is null or empty.");
-
- // Remove leading '#' if present
- string clean = hex.TrimStart('#');
- if (clean.Length != 6)
- throw new ArgumentException($"Invalid color format: {hex}");
-
- // Convert each component from hex to int
- int r = Convert.ToInt32(clean.Substring(0, 2), 16);
- int g = Convert.ToInt32(clean.Substring(2, 2), 16);
- int b = Convert.ToInt32(clean.Substring(4, 2), 16);
- return Color.FromArgb(r, g, b);
+ // Sample JSON payload (in a real scenario this would come from an HTTP request)
+ string jsonPayload = @"
+ {
+ ""Symbology"": ""QR"",
+ ""CodeText"": ""https://example.com"",
+ ""Appearance"": {
+ ""ImageWidth"": 300,
+ ""ImageHeight"": 300,
+ ""ForegroundColor"": ""#0000FF"",
+ ""BackgroundColor"": ""#FFFFFF"",
+ ""Padding"": 5
+ }
+ }";
+
+ // Deserialize the JSON into a request object
+ BarcodeRequest request = JsonSerializer.Deserialize(jsonPayload);
+
+ // Generate the barcode and obtain the PNG bytes
+ byte[] pngData = GenerateBarcode(request);
+
+ // Write the PNG to a file for verification
+ const string outputPath = "generated_barcode.png";
+ File.WriteAllBytes(outputPath, pngData);
+ Console.WriteLine($"Barcode image saved to '{outputPath}'. Size: {pngData.Length} bytes.");
+
+ // In an actual API the pngData would be written to the HTTP response stream.
}
///
- /// Generates a barcode image from a JSON payload and returns the PNG bytes.
+ /// Generates a barcode based on the request and returns PNG bytes.
///
- /// JSON string containing barcode parameters.
- /// Byte array with PNG image data.
- private static byte[] GenerateBarcodeFromJson(string jsonPayload)
+ /// The barcode generation request.
+ /// Byte array containing the PNG image.
+ static byte[] GenerateBarcode(BarcodeRequest request)
{
- // Deserialize request
- BarcodeRequest request = JsonSerializer.Deserialize(jsonPayload);
if (request == null)
- throw new ArgumentException("Invalid JSON payload.");
+ throw new ArgumentException("Request cannot be null.");
- // Resolve symbology name to EncodeTypes field via reflection
+ // Resolve the symbology name to a BaseEncodeType using reflection
var field = typeof(EncodeTypes).GetField(request.Symbology);
if (field == null)
throw new ArgumentException($"Unknown symbology: {request.Symbology}");
+
BaseEncodeType encodeType = (BaseEncodeType)field.GetValue(null);
- // Create generator with codetext
- using (var generator = new BarcodeGenerator(encodeType, request.CodeText))
+ // Create the generator with the resolved type and code text
+ using (var generator = new BarcodeGenerator(encodeType, request.CodeText ?? string.Empty))
{
- // Set foreground color if provided
- if (!string.IsNullOrWhiteSpace(request.ForeColor))
- generator.Parameters.Barcode.BarColor = ParseColor(request.ForeColor);
-
- // Set background color if provided
- if (!string.IsNullOrWhiteSpace(request.BackColor))
- generator.Parameters.BackColor = ParseColor(request.BackColor);
-
- // Set AutoSizeMode if provided
- if (!string.IsNullOrWhiteSpace(request.AutoSizeMode))
+ // Apply appearance options if provided
+ if (request.Appearance != null)
{
- if (Enum.TryParse(request.AutoSizeMode, out var mode))
- generator.Parameters.AutoSizeMode = mode;
- else
- throw new ArgumentException($"Invalid AutoSizeMode: {request.AutoSizeMode}");
+ var ap = request.Appearance;
+
+ // Set image dimensions (using .Point as required)
+ if (ap.ImageWidth.HasValue)
+ generator.Parameters.ImageWidth.Point = ap.ImageWidth.Value;
+ if (ap.ImageHeight.HasValue)
+ generator.Parameters.ImageHeight.Point = ap.ImageHeight.Value;
+
+ // Set foreground (bar) color
+ if (!string.IsNullOrWhiteSpace(ap.ForegroundColor))
+ generator.Parameters.Barcode.BarColor = ParseColor(ap.ForegroundColor);
+
+ // Set background color
+ if (!string.IsNullOrWhiteSpace(ap.BackgroundColor))
+ generator.Parameters.BackColor = ParseColor(ap.BackgroundColor);
+
+ // Uniform padding on all sides
+ if (ap.Padding.HasValue)
+ {
+ generator.Parameters.Barcode.Padding.Left.Point = ap.Padding.Value;
+ generator.Parameters.Barcode.Padding.Top.Point = ap.Padding.Value;
+ generator.Parameters.Barcode.Padding.Right.Point = ap.Padding.Value;
+ generator.Parameters.Barcode.Padding.Bottom.Point = ap.Padding.Value;
+ }
}
- // Set image width/height if provided
- if (request.ImageWidth.HasValue)
- generator.Parameters.ImageWidth.Point = request.ImageWidth.Value;
- if (request.ImageHeight.HasValue)
- generator.Parameters.ImageHeight.Point = request.ImageHeight.Value;
+ // Use interpolation mode to respect explicit ImageWidth/ImageHeight if set
+ generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- // Set XDimension if provided
- if (request.XDimension.HasValue)
- generator.Parameters.Barcode.XDimension.Point = request.XDimension.Value;
-
- // Set BarHeight only when AutoSizeMode is None
- if (request.BarHeight.HasValue && generator.Parameters.AutoSizeMode == AutoSizeMode.None)
- generator.Parameters.Barcode.BarHeight.Point = request.BarHeight.Value;
-
- // Generate PNG into memory stream and return bytes
+ // Save to a memory stream as PNG
using (var ms = new MemoryStream())
{
generator.Save(ms, BarCodeImageFormat.Png);
@@ -116,37 +137,32 @@ private static byte[] GenerateBarcodeFromJson(string jsonPayload)
}
///
- /// Entry point that demonstrates barcode generation using a sample JSON payload.
+ /// Converts a hex color string to an Aspose.Drawing.Color.
///
- static void Main()
+ /// Hex color string (e.g., "#FF0000" or "FF0000FF").
+ /// Corresponding Color object.
+ static Aspose.Drawing.Color ParseColor(string hex)
{
- // Sample JSON payload representing an API request
- string sampleJson = @"{
- ""Symbology"": ""Code128"",
- ""CodeText"": ""1234567890"",
- ""ForeColor"": ""#0000FF"",
- ""BackColor"": ""#FFFFFF"",
- ""ImageWidth"": 300,
- ""ImageHeight"": 150,
- ""XDimension"": 2,
- ""AutoSizeMode"": ""Interpolation""
- }";
+ if (string.IsNullOrWhiteSpace(hex))
+ throw new ArgumentException("Color string cannot be null or empty.");
- try
- {
- // Generate PNG bytes from the JSON request
- byte[] pngBytes = GenerateBarcodeFromJson(sampleJson);
+ // Remove leading '#'
+ if (hex.StartsWith("#"))
+ hex = hex.Substring(1);
- // Simulate API response by outputting Base64 string
- string base64 = Convert.ToBase64String(pngBytes);
- Console.WriteLine("PNG Base64:");
- Console.WriteLine(base64);
- }
- catch (Exception ex)
- {
- // Output any errors encountered during processing
- Console.WriteLine($"Error: {ex.Message}");
- }
+ // Support RGB (6 chars) or ARGB (8 chars)
+ if (hex.Length == 6)
+ hex = "FF" + hex; // Assume fully opaque
+
+ if (hex.Length != 8)
+ throw new ArgumentException($"Invalid color format: #{hex}");
+
+ uint argb = Convert.ToUInt32(hex, 16);
+ byte a = (byte)((argb & 0xFF000000) >> 24);
+ byte r = (byte)((argb & 0x00FF0000) >> 16);
+ byte g = (byte)((argb & 0x0000FF00) >> 8);
+ byte b = (byte)(argb & 0x000000FF);
+ return Aspose.Drawing.Color.FromArgb(a, r, g, b);
}
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/override-default-sizing-by-setting-explicit-imageheight-and-imagewidth-while-autosizemode-remains-interpolation.cs b/barcode-appearance-customization/override-default-sizing-by-setting-explicit-imageheight-and-imagewidth-while-autosizemode-remains-interpolation.cs
index bce5c27..ed4d1a0 100644
--- a/barcode-appearance-customization/override-default-sizing-by-setting-explicit-imageheight-and-imagewidth-while-autosizemode-remains-interpolation.cs
+++ b/barcode-appearance-customization/override-default-sizing-by-setting-explicit-imageheight-and-imagewidth-while-autosizemode-remains-interpolation.cs
@@ -1,38 +1,39 @@
-// Title: Explicit Image Size with Interpolation AutoSizeMode
-// Description: Demonstrates overriding the default barcode image dimensions by setting ImageWidth and ImageHeight while keeping AutoSizeMode set to Interpolation.
+// Title: Override barcode image size with explicit dimensions while using Interpolation auto-size mode
+// Description: Demonstrates how to set ImageWidth and ImageHeight on a BarcodeGenerator, keeping AutoSizeMode set to Interpolation, and save the result as PNG.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating image sizing controls. It showcases the BarcodeGenerator class, its Parameters property, and the AutoSizeMode enumeration. Developers often need to produce barcodes with specific dimensions for UI layout, printing, or integration with other graphics pipelines.
// Prompt: Override default sizing by setting explicit ImageHeight and ImageWidth while AutoSizeMode remains Interpolation.
-// Tags: barcode, code128, explicit sizing, interpolation, aspose.barcode, image generation
+// Tags: code128, barcode generation, image sizing, autosizemode, png, aspose.barcode
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing.Imaging;
///
-/// Generates a Code128 barcode with custom image dimensions while using the Interpolation auto‑size mode.
+/// Generates a Code128 barcode with custom image dimensions while retaining the Interpolation auto‑size mode.
///
class Program
{
///
- /// Entry point of the application. Creates a barcode, sets explicit size parameters, and saves the image.
+ /// Entry point of the example. Creates a barcode, configures sizing, and saves it as a PNG file.
///
static void Main()
{
- // Initialize a barcode generator for Code128 with sample text
+ // Initialize the barcode generator with Code128 symbology and sample data.
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Keep automatic sizing mode as Interpolation (default behavior)
+ // Preserve automatic sizing behavior using the Interpolation mode.
generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- // Override default size by setting explicit image dimensions (points)
+ // Explicitly set the desired image dimensions (in points).
+ // The API expects float values, hence the 'f' suffix.
generator.Parameters.ImageWidth.Point = 300f; // Width = 300 points
- generator.Parameters.ImageHeight.Point = 150f; // Height = 150 points
+ generator.Parameters.ImageHeight.Point = 150f; // Height = 150 points
- // Save the generated barcode image to a PNG file
+ // Persist the generated barcode to a PNG file.
generator.Save("barcode.png");
}
- // Inform the user that the barcode has been created
- Console.WriteLine("Barcode generated and saved as barcode.png");
+ // Inform the user that the barcode has been created.
+ Console.WriteLine("Barcode generated and saved as 'barcode.png'.");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/produce-high-density-datamatrix-barcode-by-reducing-xdimension-and-enabling-barwidthreduction-for-optimal-readability.cs b/barcode-appearance-customization/produce-high-density-datamatrix-barcode-by-reducing-xdimension-and-enabling-barwidthreduction-for-optimal-readability.cs
index c79bced..703f426 100644
--- a/barcode-appearance-customization/produce-high-density-datamatrix-barcode-by-reducing-xdimension-and-enabling-barwidthreduction-for-optimal-readability.cs
+++ b/barcode-appearance-customization/produce-high-density-datamatrix-barcode-by-reducing-xdimension-and-enabling-barwidthreduction-for-optimal-readability.cs
@@ -1,51 +1,37 @@
// Title: High‑density DataMatrix barcode generation
-// Description: Demonstrates creating a DataMatrix barcode with reduced XDimension and bar‑width reduction for optimal readability.
+// Description: Demonstrates creating a DataMatrix barcode with reduced XDimension and bar‑width reduction for compact, high‑density output.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on DataMatrix symbology. It showcases key API classes such as BarcodeGenerator, EncodeTypes, and generation parameters (XDimension, BarWidthReduction). Typical use cases include printing small labels, packaging, or any scenario requiring dense encoding while maintaining readability. Developers often need to adjust module size and bar width to meet space constraints, and this snippet provides a concise reference.
// Prompt: Produce a high‑density DataMatrix barcode by reducing XDimension and enabling BarWidthReduction for optimal readability.
-// Tags: datamatrix, barcode, highdensity, xdimension, barwidthreduction, imageoutput, aspose.barcode
+// Tags: datamatrix, barcode, generation, xdimension, barwidthreduction, aspnet, aspnetcore, aspnet5, aspose.barcode
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
///
-/// Example program that generates a high‑density DataMatrix barcode
-/// by adjusting XDimension and enabling BarWidthReduction.
+/// Demonstrates generating a high‑density DataMatrix barcode using Aspose.BarCode.
///
class Program
{
///
- /// Entry point. Generates and saves a DataMatrix barcode image.
+ /// Entry point. Creates a DataMatrix barcode with reduced XDimension and zero bar‑width reduction, then saves it as PNG.
///
static void Main()
{
- // Sample data to encode
- const string codeText = "HighDensityDataMatrix123";
-
- // Create a DataMatrix barcode generator with the specified text
- using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, codeText))
+ // Initialize a DataMatrix barcode generator with the desired text
+ using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "High‑density DataMatrix"))
{
- // Use interpolation mode to control size via image dimensions
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
-
- // Set desired image dimensions (points) – adjust as needed
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 300f;
-
- // Reduce XDimension for higher barcode density (smaller modules)
- generator.Parameters.Barcode.XDimension.Point = 0.5f; // small module size
-
- // Enable bar width reduction to compensate for ink spread
- generator.Parameters.Barcode.BarWidthReduction.Point = 0.1f;
+ // Reduce the module (X) dimension to increase barcode density
+ generator.Parameters.Barcode.XDimension.Point = 0.5f; // small XDimension
- // Optional: set barcode bar color (black by default)
- generator.Parameters.Barcode.BarColor = Color.Black;
+ // Set bar width reduction to zero for maximum compactness
+ generator.Parameters.Barcode.BarWidthReduction.Point = 0.0f;
// Save the generated barcode image to a file
- generator.Save("datamatrix_high_density.png");
+ generator.Save("datamatrix.png");
}
// Inform the user that the barcode has been generated
- Console.WriteLine("DataMatrix barcode generated: datamatrix_high_density.png");
+ Console.WriteLine("DataMatrix barcode generated: datamatrix.png");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/programmatically-retrieve-generated-barcode-image-dimensions-to-confirm-they-match-specified-imagewidth-and-imageheight.cs b/barcode-appearance-customization/programmatically-retrieve-generated-barcode-image-dimensions-to-confirm-they-match-specified-imagewidth-and-imageheight.cs
index 45ad437..7a5882d 100644
--- a/barcode-appearance-customization/programmatically-retrieve-generated-barcode-image-dimensions-to-confirm-they-match-specified-imagewidth-and-imageheight.cs
+++ b/barcode-appearance-customization/programmatically-retrieve-generated-barcode-image-dimensions-to-confirm-they-match-specified-imagewidth-and-imageheight.cs
@@ -1,67 +1,56 @@
// Title: Retrieve and verify barcode image dimensions
-// Description: Demonstrates generating a Code128 barcode with specific dimensions and programmatically confirming the generated image size matches the requested width and height.
+// Description: Demonstrates how to generate a barcode with specific width and height, then programmatically confirm the resulting image dimensions match the requested size.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, AutoSizeMode, and image parameter settings to control output size. Developers often need to ensure generated barcode images meet exact dimension requirements for layout or printing, and this snippet shows how to validate those dimensions using Aspose.Drawing.Imaging.
// Prompt: Programmatically retrieve the generated barcode image dimensions to confirm they match the specified ImageWidth and ImageHeight.
-// Tags: barcode, code128, dimensions, verification, aspose.barcode, image
+// Tags: code128, image-size, png, barcodelibrary, barcodegenerator, parameters
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Example program that generates a Code128 barcode with specified dimensions and verifies the output size.
+/// Example program that generates a Code128 barcode with specified dimensions
+/// and verifies that the resulting image size matches the requested width and height.
///
class Program
{
///
- /// Entry point. Generates the barcode, checks dimensions, and saves the image.
+ /// Entry point of the example. Generates the barcode, saves it, and checks its dimensions.
///
static void Main()
{
// Desired dimensions in points (1 point = 1/72 inch)
- float desiredWidth = 300f;
- float desiredHeight = 150f;
+ const float desiredWidth = 300f;
+ const float desiredHeight = 150f;
+ const string outputFile = "barcode.png";
- // Create a barcode generator for Code128 symbology
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128))
+ // Initialize the barcode generator with Code128 symbology and sample data
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
{
- // Set the data to encode
- generator.CodeText = "1234567890";
-
- // Use interpolation mode so ImageWidth/ImageHeight are respected
+ // Configure AutoSizeMode to use interpolation so ImageWidth/ImageHeight control the size
generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
-
- // Assign the requested image size using the Point unit
generator.Parameters.ImageWidth.Point = desiredWidth;
generator.Parameters.ImageHeight.Point = desiredHeight;
- // Generate the barcode image as a bitmap
+ // Generate the barcode image in memory
using (var bitmap = generator.GenerateBarCodeImage())
{
- // Actual pixel dimensions of the generated image
+ // Save the image to disk (optional, for visual verification)
+ bitmap.Save(outputFile, ImageFormat.Png);
+
+ // Retrieve the actual pixel dimensions of the generated image
int actualWidth = bitmap.Width;
int actualHeight = bitmap.Height;
- // Output expected dimensions (points) and actual dimensions (pixels)
- Console.WriteLine($"Expected width (points): {desiredWidth}");
- Console.WriteLine($"Expected height (points): {desiredHeight}");
- Console.WriteLine($"Actual image width (pixels): {actualWidth}");
- Console.WriteLine($"Actual image height (pixels): {actualHeight}");
-
- // Convert expected points to pixels using the generator's resolution (dpi)
- float resolution = generator.Parameters.Resolution; // default 96 dpi
- int expectedPixelWidth = (int)Math.Round(desiredWidth * resolution / 72f);
- int expectedPixelHeight = (int)Math.Round(desiredHeight * resolution / 72f);
-
- // Verify whether the actual pixel dimensions match the expected values
- bool widthMatches = actualWidth == expectedPixelWidth;
- bool heightMatches = actualHeight == expectedPixelHeight;
-
- Console.WriteLine($"Width matches expected pixels: {widthMatches}");
- Console.WriteLine($"Height matches expected pixels: {heightMatches}");
+ // Compare actual dimensions with the expected values (rounded to nearest integer)
+ bool widthMatches = actualWidth == (int)Math.Round(desiredWidth);
+ bool heightMatches = actualHeight == (int)Math.Round(desiredHeight);
- // Save the barcode image to a file (optional)
- generator.Save("barcode.png");
+ // Output the comparison results
+ Console.WriteLine($"Expected Width: {desiredWidth} pt, Actual Width: {actualWidth} px, Match: {widthMatches}");
+ Console.WriteLine($"Expected Height: {desiredHeight} pt, Actual Height: {actualHeight} px, Match: {heightMatches}");
}
}
}
diff --git a/barcode-appearance-customization/set-autosizemode-to-none-assign-xdimension-and-generate-barcode-suitable-for-low-resolution-screen-display.cs b/barcode-appearance-customization/set-autosizemode-to-none-assign-xdimension-and-generate-barcode-suitable-for-low-resolution-screen-display.cs
index d59c092..a7dbd92 100644
--- a/barcode-appearance-customization/set-autosizemode-to-none-assign-xdimension-and-generate-barcode-suitable-for-low-resolution-screen-display.cs
+++ b/barcode-appearance-customization/set-autosizemode-to-none-assign-xdimension-and-generate-barcode-suitable-for-low-resolution-screen-display.cs
@@ -1,36 +1,46 @@
-// Title: Generate Code128 Barcode with Fixed Size for Low‑Resolution Screens
-// Description: Demonstrates disabling auto‑size, setting XDimension, and saving a PNG barcode suitable for low‑resolution display.
+// Title: Generate Code128 barcode with manual sizing for screen display
+// Description: Demonstrates disabling auto‑size, setting XDimension, and saving a low‑resolution PNG suitable for screen rendering.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to control barcode dimensions and resolution using the BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes. Developers often need to produce barcodes that render clearly on low‑resolution displays or when precise sizing is required, such as in web or mobile applications. The snippet shows typical usage of AutoSizeMode, XDimension, and resolution settings.
// Prompt: Set AutoSizeMode to None, assign XDimension, and generate a barcode suitable for low‑resolution screen display.
-// Tags: code128, autosizemode, xdimension, png, aspnet.barcode, barcode generation
+// Tags: code128, autosizemode, xdimension, lowresolution, png, aspose.barcode, barcodegenerator
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Example program that creates a Code128 barcode with manual sizing for low‑resolution screens.
+/// Example program that creates a Code128 barcode with manual sizing,
+/// optimized for low‑resolution screen display.
///
class Program
{
///
- /// Entry point. Generates the barcode, saves it as PNG, and writes a confirmation to the console.
+ /// Entry point of the application.
+ /// Generates the barcode, configures sizing and resolution, and saves it as a PNG file.
///
static void Main()
{
- // Initialize a barcode generator for Code128 with the sample text "1234567890"
+ // Define the output file path for the generated barcode image.
+ string outputPath = "barcode.png";
+
+ // Initialize a BarcodeGenerator for Code128 with the desired text.
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Disable automatic sizing to keep full control over the barcode dimensions
+ // Disable automatic sizing to allow manual dimension control.
generator.Parameters.AutoSizeMode = AutoSizeMode.None;
- // Set a small XDimension (module width) in points, suitable for low‑resolution screen display
- generator.Parameters.Barcode.XDimension.Point = 1f;
+ // Set the module (X) dimension to a larger value (2 points) for better visibility on low‑resolution screens.
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+
+ // Optionally lower the image resolution to 72 DPI, matching typical screen resolution.
+ generator.Parameters.Resolution = 72f;
- // Save the generated barcode image as a PNG file
- generator.Save("barcode.png");
+ // Save the configured barcode as a PNG image to the specified path.
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
- // Inform the user that the barcode has been generated
- Console.WriteLine("Barcode generated: barcode.png");
+ // Inform the user where the barcode image has been saved.
+ Console.WriteLine($"Barcode image saved to: {outputPath}");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/set-uniform-padding-of-20-pixels-around-code128-barcode-and-verify-no-clipping-after-rotation.cs b/barcode-appearance-customization/set-uniform-padding-of-20-pixels-around-code128-barcode-and-verify-no-clipping-after-rotation.cs
index 85af046..7090f77 100644
--- a/barcode-appearance-customization/set-uniform-padding-of-20-pixels-around-code128-barcode-and-verify-no-clipping-after-rotation.cs
+++ b/barcode-appearance-customization/set-uniform-padding-of-20-pixels-around-code128-barcode-and-verify-no-clipping-after-rotation.cs
@@ -1,7 +1,8 @@
-// Title: Code128 Barcode with Uniform Padding and Rotation
-// Description: Generates a Code128 barcode with 20-pixel padding on all sides, rotates it 90°, saves to PNG, and verifies readability to ensure no clipping.
+// Title: Code128 barcode with uniform padding and rotation verification
+// Description: Demonstrates setting a 20-pixel padding around a Code128 barcode, rotating it, and confirming that the image is not clipped.
+// Category-Description: This example belongs to the Aspose.BarCode image generation and recognition category. It shows how to use BarcodeGenerator to configure padding and rotation, and BarCodeReader to validate the output. Developers often need to adjust barcode margins and verify readability after transformations, especially for printing and scanning workflows.
// Prompt: Set uniform Padding of 20 pixels around a Code128 barcode and verify no clipping after rotation.
-// Tags: code128, padding, rotation, png, aspose.barcode, barcodegeneration, barcoderecognition
+// Tags: code128, padding, rotation, png, barcode generation, barcode recognition, aspose.barcode
using System;
using System.IO;
@@ -10,30 +11,22 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Demonstrates creating a Code128 barcode with uniform padding, rotating it,
-/// saving the image, and verifying that the barcode can still be read.
+/// Demonstrates setting uniform padding around a Code128 barcode, rotating it, and verifying readability.
///
class Program
{
///
- /// Entry point of the example. Generates the barcode, applies padding and rotation,
- /// saves the image, and checks that the barcode is readable after rotation.
+ /// Entry point. Generates the barcode, saves it, and validates that it can be read after rotation.
///
static void Main()
{
// Define the output file path for the generated barcode image
- string outputPath = "code128_padded_rotated.png";
+ string outputPath = "code128.png";
- // Remove any existing file with the same name to avoid conflicts
- if (File.Exists(outputPath))
- {
- File.Delete(outputPath);
- }
-
- // Create a Code128 barcode generator with the desired text
+ // Create a Code128 barcode generator with the sample text "1234567890"
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Apply uniform padding of 20 pixels on all four sides
+ // Apply a uniform padding of 20 pixels on all four sides
generator.Parameters.Barcode.Padding.Left.Pixels = 20f;
generator.Parameters.Barcode.Padding.Top.Pixels = 20f;
generator.Parameters.Barcode.Padding.Right.Pixels = 20f;
@@ -42,33 +35,30 @@ static void Main()
// Rotate the barcode image by 90 degrees
generator.Parameters.RotationAngle = 90f;
- // Save the generated barcode image to the specified path
- generator.Save(outputPath);
+ // Save the generated barcode as a PNG file
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
- // Ensure the barcode image was successfully created before attempting to read it
+ // Verify that the barcode image file was successfully created
if (!File.Exists(outputPath))
{
Console.WriteLine("Error: Barcode image was not created.");
return;
}
- // Use BarCodeReader to verify that the rotated barcode can be decoded (i.e., not clipped)
+ // Use BarCodeReader to decode the saved image and confirm the content matches the original text
using (var reader = new BarCodeReader(outputPath, DecodeType.Code128))
{
- bool found = false;
+ var results = reader.ReadBarCodes();
- // Iterate through all detected barcodes in the image
- foreach (var result in reader.ReadBarCodes())
+ // Check if at least one barcode was read and the decoded text is correct
+ if (results.Length > 0 && results[0].CodeText == "1234567890")
{
- Console.WriteLine($"Read barcode: Type={result.CodeType}, CodeText={result.CodeText}");
- found = true;
+ Console.WriteLine("Success: Barcode read correctly after rotation. No clipping detected.");
}
-
- // If no barcode was detected, report a possible clipping issue
- if (!found)
+ else
{
- Console.WriteLine("Failed to read the barcode. It may be clipped after rotation.");
+ Console.WriteLine("Warning: Barcode could not be read after rotation. Possible clipping.");
}
}
}
diff --git a/barcode-appearance-customization/specify-individual-left-top-right-and-bottom-paddings-to-align-datamatrix-barcode-within-layout.cs b/barcode-appearance-customization/specify-individual-left-top-right-and-bottom-paddings-to-align-datamatrix-barcode-within-layout.cs
index acd8287..4d33c23 100644
--- a/barcode-appearance-customization/specify-individual-left-top-right-and-bottom-paddings-to-align-datamatrix-barcode-within-layout.cs
+++ b/barcode-appearance-customization/specify-individual-left-top-right-and-bottom-paddings-to-align-datamatrix-barcode-within-layout.cs
@@ -1,41 +1,46 @@
-// Title: DataMatrix Barcode with Individual Padding
-// Description: Demonstrates how to set left, top, right, and bottom paddings for a DataMatrix barcode to control its alignment within an image.
-// Prompt: Specify individual left, top, right, and bottom paddings to align a DataMatrix barcode within a layout.
-// Tags: datamatrix, padding, barcode, aspnet, image generation
-
+// Title: DataMatrix Barcode with Individual Padding Settings
+// Description: Demonstrates how to set left, top, right, and bottom paddings for a DataMatrix barcode and save it as a PNG image.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to customize barcode layout using the BarcodeGenerator class and its Parameters property. Typical use cases include aligning barcodes within forms, labels, or UI components where precise padding is required. Developers often need to control individual padding values to meet design specifications or printing constraints.
+///
+/// Provides an example of configuring individual padding values for a DataMatrix barcode using Aspose.BarCode.
+///
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Example program that generates a DataMatrix barcode with custom padding values.
+/// Entry point for the DataMatrix padding demonstration.
///
class Program
{
///
- /// Entry point of the application. Creates a DataMatrix barcode, applies individual paddings,
- /// sets image dimensions, saves the image, and writes a confirmation to the console.
+ /// Generates a DataMatrix barcode with custom left, top, right, and bottom paddings and saves it as a PNG file.
///
static void Main()
{
- // Initialize a DataMatrix barcode generator with the desired text.
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "Aspose.DataMatrix"))
+ // Define the output file name and location.
+ string outputPath = "datamatrix_padding.png";
+
+ // Text that will be encoded into the barcode.
+ string codeText = "Hello Aspose";
+
+ // Initialize the barcode generator for DataMatrix symbology.
+ using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, codeText))
{
- // Apply individual padding values (in points) to each side of the barcode.
- generator.Parameters.Barcode.Padding.Left.Point = 10f; // 10 points on the left
- generator.Parameters.Barcode.Padding.Top.Point = 20f; // 20 points on the top
- generator.Parameters.Barcode.Padding.Right.Point = 15f; // 15 points on the right
- generator.Parameters.Barcode.Padding.Bottom.Point = 5f; // 5 points at the bottom
+ // Set individual padding values (in points) to control barcode positioning.
+ generator.Parameters.Barcode.Padding.Left.Point = 10f; // left padding
+ generator.Parameters.Barcode.Padding.Top.Point = 20f; // top padding
+ generator.Parameters.Barcode.Padding.Right.Point = 30f; // right padding
+ generator.Parameters.Barcode.Padding.Bottom.Point = 40f; // bottom padding
- // Define the output image size to clearly see the effect of the padding.
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 300f;
+ // Optional: increase module size for better visual clarity.
+ generator.Parameters.Barcode.XDimension.Point = 2f;
- // Save the generated barcode image to a file.
- generator.Save("datamatrix.png");
+ // Save the generated barcode image in PNG format.
+ generator.Save(outputPath, BarCodeImageFormat.Png);
}
- // Inform the user that the barcode has been generated.
- Console.WriteLine("DataMatrix barcode generated with custom paddings.");
+ // 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/barcode-appearance-customization/test-barcode-generation-with-interpolation-mode-at-150-dpi-to-confirm-distortion-thresholds-before-recommending-higher-d.cs b/barcode-appearance-customization/test-barcode-generation-with-interpolation-mode-at-150-dpi-to-confirm-distortion-thresholds-before-recommending-higher-d.cs
index 05f3400..c78fd25 100644
--- a/barcode-appearance-customization/test-barcode-generation-with-interpolation-mode-at-150-dpi-to-confirm-distortion-thresholds-before-recommending-higher-d.cs
+++ b/barcode-appearance-customization/test-barcode-generation-with-interpolation-mode-at-150-dpi-to-confirm-distortion-thresholds-before-recommending-higher-d.cs
@@ -1,69 +1,81 @@
-// Title: Barcode generation with interpolation at different DPI
-// Description: Demonstrates generating a Code128 barcode using interpolation auto-size mode at 150 dpi and 300 dpi to evaluate image distortion.
+// Title: Barcode generation with interpolation mode at different DPI settings
+// Description: Demonstrates generating Code128 barcodes at 150 dpi and 300 dpi using Aspose.BarCode with interpolation auto‑size mode to evaluate image distortion.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to configure AutoSizeMode, resolution, and image dimensions when creating barcodes. It highlights typical use cases such as quality testing, DPI comparison, and visual verification for developers working with barcode image rendering.
// Prompt: Test barcode generation with Interpolation mode at 150 dpi to confirm distortion thresholds before recommending higher DPI.
-// Tags: code128, barcode, interpolation, dpi, image generation, aspose.barcode
+// Tags: barcode symbology, generation, png, interpolation, dpi, aspose.barcode, autosizemode
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Example program that creates Code128 barcodes at two different DPI settings
-/// using the Interpolation auto‑size mode to compare visual quality.
+/// Generates Code128 barcodes at specified DPI values using the Interpolation auto‑size mode.
///
class Program
{
///
- /// Entry point of the application. Generates two barcode images and prompts the user to compare them.
+ /// Entry point of the example. Generates barcodes at 150 dpi and 300 dpi for visual comparison.
///
static void Main()
{
- // Barcode content and output file names
- const string codeText = "1234567890";
- const string output150 = "barcode_150dpi.png";
- const string output300 = "barcode_300dpi.png";
+ // Determine the folder where output images will be saved (current directory)
+ string outputFolder = Directory.GetCurrentDirectory();
- // ------------------------------------------------------------
- // Generate barcode with Interpolation mode at 150 DPI
- // ------------------------------------------------------------
- using (var generator150 = new BarcodeGenerator(EncodeTypes.Code128, codeText))
- {
- // Enable interpolation auto‑size mode
- generator150.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ // Generate a barcode image at 150 dpi
+ GenerateBarcode(
+ outputFolder,
+ "barcode_150dpi.png",
+ 150f,
+ "Test150DPI");
- // Set image resolution to 150 DPI
- generator150.Parameters.Resolution = 150f;
+ // Generate a barcode image at 300 dpi for comparison
+ GenerateBarcode(
+ outputFolder,
+ "barcode_300dpi.png",
+ 300f,
+ "Test300DPI");
- // Define target image dimensions in points (1 point = 1/72 inch)
- generator150.Parameters.ImageWidth.Point = 300f;
- generator150.Parameters.ImageHeight.Point = 150f;
+ // Inform the user that generation is complete and where to find the files
+ Console.WriteLine("Barcode generation completed. Check the generated PNG files in:");
+ Console.WriteLine(outputFolder);
+ }
- // Save the generated barcode image
- generator150.Save(output150);
- Console.WriteLine($"Generated barcode at 150 dpi: {output150}");
- }
+ ///
+ /// Creates a Code128 barcode image with the specified DPI and saves it to the given folder.
+ ///
+ /// The directory where the image will be saved.
+ /// The name of the output PNG file.
+ /// Resolution in dots per inch.
+ /// The text to encode in the barcode.
+ private static void GenerateBarcode(string folder, string fileName, float dpi, string codeText)
+ {
+ // Combine folder and file name to get the full path
+ string filePath = Path.Combine(folder, fileName);
- // ------------------------------------------------------------
- // Generate the same barcode at a higher DPI (300) for comparison
- // ------------------------------------------------------------
- using (var generator300 = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ // Initialize the barcode generator with Code128 symbology and the provided text
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
{
- // Use the same interpolation mode
- generator300.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ // Use Interpolation auto‑size mode to let the generator scale the image
+ generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+
+ // Set the desired resolution (DPI)
+ generator.Parameters.Resolution = dpi;
- // Increase resolution to 300 DPI
- generator300.Parameters.Resolution = 300f;
+ // Define the target image dimensions in pixels
+ generator.Parameters.ImageWidth.Pixels = 300f;
+ generator.Parameters.ImageHeight.Pixels = 150f;
- // Keep image dimensions identical to the 150 dpi version
- generator300.Parameters.ImageWidth.Point = 300f;
- generator300.Parameters.ImageHeight.Point = 150f;
+ // Optional: set foreground (barcode) and background colors
+ generator.Parameters.Barcode.BarColor = Color.Black;
+ generator.Parameters.BackColor = Color.White;
- // Save the higher‑resolution barcode image
- generator300.Save(output300);
- Console.WriteLine($"Generated barcode at 300 dpi: {output300}");
+ // Save the generated barcode as a PNG file
+ generator.Save(filePath);
}
- // Simple visual check hint
- Console.WriteLine("Compare the two images to assess distortion at 150 dpi.");
+ // Output the location of the generated file
+ Console.WriteLine($"Generated barcode at {dpi} DPI: {filePath}");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/test-effect-of-barwidthreduction-on-barcode-scanning-speed-by-measuring-decode-times-for-dense-barcodes.cs b/barcode-appearance-customization/test-effect-of-barwidthreduction-on-barcode-scanning-speed-by-measuring-decode-times-for-dense-barcodes.cs
index 15b908c..e8e036a 100644
--- a/barcode-appearance-customization/test-effect-of-barwidthreduction-on-barcode-scanning-speed-by-measuring-decode-times-for-dense-barcodes.cs
+++ b/barcode-appearance-customization/test-effect-of-barwidthreduction-on-barcode-scanning-speed-by-measuring-decode-times-for-dense-barcodes.cs
@@ -1,7 +1,8 @@
// Title: BarWidthReduction Impact on Code128 Decode Speed
-// Description: Demonstrates how varying BarWidthReduction affects scanning time for dense Code128 barcodes.
+// Description: Demonstrates how varying BarWidthReduction affects decoding time for dense Code128 barcodes.
+// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It showcases the use of BarcodeGenerator (generation) and BarCodeReader (recognition) to create dense barcodes, adjust the BarWidthReduction property, and measure decode performance. Developers often need to fine‑tune barcode rendering parameters for optimal scanning speed in high‑density scenarios.
// Prompt: Test the effect of BarWidthReduction on barcode scanning speed by measuring decode times for dense barcodes.
-// Tags: code128, barwidthreduction, performance, decoding, aspnet.barcode, generation, recognition
+// Tags: code128, barwidthreduction, performance, benchmark, generation, recognition, aspnet, aspose.barcode
using System;
using System.Diagnostics;
@@ -11,67 +12,74 @@
using Aspose.BarCode.BarCodeRecognition;
///
-/// Program to generate dense Code128 barcodes with different BarWidthReduction values and measure decode performance.
+/// Example program that benchmarks the impact of the BarWidthReduction property on
+/// decoding speed for dense Code128 barcodes using Aspose.BarCode.
///
class Program
{
///
- /// Entry point. Generates barcodes, decodes them, and reports timing for each BarWidthReduction setting.
+ /// Entry point. Generates a dense Code128 barcode with different BarWidthReduction values,
+ /// decodes each version multiple times, and reports the average decode time.
///
static void Main()
{
- // Sample dense Code128 text (long numeric string)
- string codeText = "12345678901234567890123456789012345678901234567890";
+ // Sample dense Code128 barcode text (50 characters)
+ const string codeText = "12345678901234567890123456789012345678901234567890";
- // Different BarWidthReduction values to test (in points)
- float[] reductions = new float[] { 0f, 0.5f, 1f };
+ // BarWidthReduction values to test (in points)
+ float[] reductions = { 0f, 0.5f, 1f };
- // Ensure output directory exists
- string outputDir = "BarWidthReductionSamples";
- if (!Directory.Exists(outputDir))
- {
- Directory.CreateDirectory(outputDir);
- }
+ // Number of repetitions for each setting (kept small for CI)
+ const int repetitions = 5;
- // Iterate over each reduction value, generate barcode, and measure decode time
+ Console.WriteLine("BarWidthReduction benchmark (dense Code128)");
+ Console.WriteLine($"CodeText length: {codeText.Length}");
+ Console.WriteLine();
+
+ // Iterate over each BarWidthReduction setting
foreach (float reduction in reductions)
{
- // Build file path for the generated barcode image
- string filePath = Path.Combine(outputDir, $"barcode_{reduction}.png");
+ long totalTicks = 0;
- // Generate barcode image with specific BarWidthReduction
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ // Perform multiple runs to obtain an average decode time
+ for (int i = 0; i < repetitions; i++)
{
- // Use fixed size (no auto-sizing) to keep dimensions comparable
- generator.Parameters.AutoSizeMode = AutoSizeMode.None;
- generator.Parameters.Barcode.BarHeight.Point = 50f; // Fixed bar height
- generator.Parameters.Barcode.XDimension.Point = 2f; // Module size
- generator.Parameters.Barcode.BarWidthReduction.Point = reduction; // Test value
+ // Generate barcode with the current BarWidthReduction
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ {
+ generator.Parameters.Barcode.BarWidthReduction.Point = reduction;
- // Save the generated image to disk
- generator.Save(filePath);
- }
+ // Save 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
- // Measure decoding time for the generated barcode
- using (var reader = new BarCodeReader(filePath, DecodeType.Code128))
- {
- var stopwatch = Stopwatch.StartNew();
- var results = reader.ReadBarCodes();
- stopwatch.Stop();
-
- // Expect exactly one result for this test
- string decodedText = results.Length > 0 ? results[0].CodeText : "No result";
+ // Measure decoding time using a stopwatch
+ var stopwatch = Stopwatch.StartNew();
+ using (var reader = new BarCodeReader(ms, DecodeType.Code128))
+ {
+ // Read all barcodes (there will be only one)
+ foreach (var result in reader.ReadBarCodes())
+ {
+ // Access result to ensure full processing
+ var _ = result.CodeText;
+ }
+ }
+ stopwatch.Stop();
- // Output reduction value, decode time, and decoded text
- Console.WriteLine($"Reduction: {reduction} pt | Decode time: {stopwatch.ElapsedMilliseconds} ms | Decoded: {decodedText}");
+ // Accumulate elapsed ticks
+ totalTicks += stopwatch.ElapsedTicks;
+ }
+ }
}
+
+ // Calculate average decode time in milliseconds
+ double avgMs = (totalTicks * 1000.0) / Stopwatch.Frequency / repetitions;
+ Console.WriteLine($"BarWidthReduction = {reduction} pt => Average decode time: {avgMs:F3} ms over {repetitions} runs");
}
- // Cleanup: optional removal of generated files
- // foreach (var file in Directory.GetFiles(outputDir))
- // {
- // File.Delete(file);
- // }
- // Directory.Delete(outputDir);
+ Console.WriteLine();
+ Console.WriteLine("Benchmark completed.");
}
}
\ No newline at end of file
diff --git a/barcode-appearance-customization/validate-barcode-readability-after-applying-interpolation-mode-at-300-dpi-by-scanning-saved-image.cs b/barcode-appearance-customization/validate-barcode-readability-after-applying-interpolation-mode-at-300-dpi-by-scanning-saved-image.cs
index cc3abac..85e7d88 100644
--- a/barcode-appearance-customization/validate-barcode-readability-after-applying-interpolation-mode-at-300-dpi-by-scanning-saved-image.cs
+++ b/barcode-appearance-customization/validate-barcode-readability-after-applying-interpolation-mode-at-300-dpi-by-scanning-saved-image.cs
@@ -1,78 +1,70 @@
-// Title: Barcode Generation with Interpolation Mode and Validation
-// Description: Generates a Code128 barcode using interpolation auto-size at 300 dpi, saves it as PNG, then reads it back to confirm readability.
+// Title: Validate barcode readability with interpolation at 300 dpi
+// Description: Demonstrates generating a Code128 barcode using interpolation mode at 300 dpi, saving it, and verifying readability by scanning the image.
+// Category-Description: This example belongs to the Aspose.BarCode image generation and recognition category. It showcases the BarcodeGenerator for creating high‑resolution barcodes with AutoSizeMode.Interpolation and the BarCodeReader for decoding. Developers use these APIs to produce printable barcodes and ensure they can be read by scanners in real‑world applications.
// Prompt: Validate barcode readability after applying Interpolation mode at 300 dpi by scanning the saved image.
-// Tags: code128, interpolation, 300dpi, png, barcode generation, barcode recognition, aspose.barcode
+// Tags: code128, interpolation, 300dpi, barcode generation, barcode recognition, aspose.barcode
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
-using Aspose.Drawing;
///
-/// Demonstrates creating a barcode with interpolation auto‑size at 300 dpi,
-/// saving it as an image, and then verifying that the barcode can be read back.
+/// Demonstrates generating a barcode with interpolation mode at 300 dpi and validating its readability.
///
class Program
{
///
- /// Entry point of the example. Generates a barcode, saves it, and validates its readability.
+ /// Entry point. Generates a barcode image, saves it, and reads it back to confirm the encoded text.
///
static void Main()
{
- // Define the output file path for the generated barcode image.
- string outputPath = "barcode.png";
+ const string barcodePath = "sample_barcode.png";
+ const string codeText = "ABC1234567890";
- // --------------------------------------------------------------------
- // Generate the barcode image
- // --------------------------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ // Generate barcode with Interpolation mode and 300 dpi resolution
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
{
- // Apply the Interpolation auto‑size mode so the image is scaled automatically.
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
-
- // Set the image resolution to 300 dpi for high‑quality output.
- generator.Parameters.Resolution = 300f;
-
- // Specify explicit image dimensions (in points) because BarHeight is ignored in Interpolation mode.
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 150f;
-
- // Save the generated barcode as a PNG file.
- generator.Save(outputPath, BarCodeImageFormat.Png);
+ generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; // Enable interpolation for smoother scaling
+ generator.Parameters.Resolution = 300f; // Set resolution to 300 DPI
+ generator.Save(barcodePath); // Save the generated barcode image
}
- // --------------------------------------------------------------------
- // Verify that the image file was created successfully
- // --------------------------------------------------------------------
- if (!File.Exists(outputPath))
+ // Verify that the image was created successfully
+ if (!File.Exists(barcodePath))
{
- Console.WriteLine($"Error: Barcode image not found at '{outputPath}'.");
+ Console.WriteLine($"Error: Barcode image not found at '{barcodePath}'.");
return;
}
- // --------------------------------------------------------------------
// Read and validate the barcode from the saved image
- // --------------------------------------------------------------------
- using (var reader = new BarCodeReader(outputPath, DecodeType.AllSupportedTypes))
+ using (var reader = new BarCodeReader(barcodePath, DecodeType.AllSupportedTypes))
{
bool found = false;
- // Iterate through all detected barcodes in the image.
+ // Iterate through all detected barcodes
foreach (var result in reader.ReadBarCodes())
{
- found = true;
- Console.WriteLine($"Detected Barcode Type: {result.CodeTypeName}");
- Console.WriteLine($"Decoded Text: {result.CodeText}");
- Console.WriteLine($"Confidence: {result.Confidence}");
+ Console.WriteLine($"Detected Type: {result.CodeType}");
+ Console.WriteLine($"Detected Text: {result.CodeText}");
Console.WriteLine($"Reading Quality: {result.ReadingQuality}");
+
+ // Check if the decoded text matches the original
+ if (result.CodeText == codeText)
+ {
+ found = true;
+ }
}
- // Inform the user if no barcode was detected.
- if (!found)
+ // Output validation result
+ if (found)
+ {
+ Console.WriteLine("Barcode readability validation succeeded.");
+ }
+ else
{
- Console.WriteLine("No barcode detected in the image.");
+ Console.WriteLine("Barcode readability validation failed: expected text not found.");
}
}
}
diff --git a/barcode-appearance-customization/write-unit-tests-that-compare-expected-and-actual-image-dimensions-after-applying-autosizemodenearest-with-given-paramet.cs b/barcode-appearance-customization/write-unit-tests-that-compare-expected-and-actual-image-dimensions-after-applying-autosizemodenearest-with-given-paramet.cs
index 7f82eab..7aef709 100644
--- a/barcode-appearance-customization/write-unit-tests-that-compare-expected-and-actual-image-dimensions-after-applying-autosizemodenearest-with-given-paramet.cs
+++ b/barcode-appearance-customization/write-unit-tests-that-compare-expected-and-actual-image-dimensions-after-applying-autosizemodenearest-with-given-paramet.cs
@@ -1,68 +1,116 @@
-// Title: Demonstrate AutoSizeMode.Nearest barcode dimension verification
-// Description: Generates barcodes with specified point dimensions and checks that the resulting image does not exceed those dimensions.
+// Title: AutoSizeMode.Nearest Barcode Image Dimension Test
+// Description: Demonstrates how to generate a barcode image with AutoSizeMode.Nearest and verifies that the resulting image dimensions stay within the specified target size while preserving aspect ratio.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and AutoSizeMode to control barcode image sizing. Developers often need to generate barcodes that fit within predefined dimensions for UI layouts, reports, or printing, and this snippet shows how to test that the AutoSizeMode.Nearest setting produces expected dimensions.
// Prompt: Write unit tests that compare expected and actual image dimensions after applying AutoSizeMode.Nearest with given parameters.
-// Tags: barcode, autosizemode, nearest, dimensions, unit-test, aspose.barcode, aspose.drawing
+// Tags: barcode symbology, autosize, image generation, aspose.barcode, aspose.drawing
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Contains the entry point and test runner for barcode dimension verification using AutoSizeMode.Nearest.
+/// Contains a simple test harness that generates Code128 barcodes using AutoSizeMode.Nearest
+/// and validates that the produced image dimensions respect the target size and aspect ratio.
///
class Program
{
///
- /// Main entry point that runs sample barcode dimension tests.
+ /// Entry point of the example. Executes a series of dimension validation tests.
///
static void Main()
{
- // Test case 1: ImageWidth = 200pt, ImageHeight = 100pt, AutoSizeMode = Nearest
- RunTest(EncodeTypes.Code128, "Test123", 200f, 100f);
+ int totalTests = 0;
+ int failedTests = 0;
- // Test case 2: ImageWidth = 150pt, ImageHeight = 150pt, AutoSizeMode = Nearest
- RunTest(EncodeTypes.QR, "https://example.com", 150f, 150f);
+ // Test 1: Target size 200x100, Code128 barcode
+ RunTest(
+ testName: "Test1",
+ expectedWidth: 200,
+ expectedHeight: 100,
+ targetWidth: 200,
+ targetHeight: 100,
+ ref totalTests,
+ ref failedTests);
+
+ // Test 2: Target size 300x150, Code128 barcode
+ RunTest(
+ testName: "Test2",
+ expectedWidth: 300,
+ expectedHeight: 150,
+ targetWidth: 300,
+ targetHeight: 150,
+ ref totalTests,
+ ref failedTests);
+
+ // Test 3: Target size 250x250 (square), Code128 barcode
+ RunTest(
+ testName: "Test3",
+ expectedWidth: 250,
+ expectedHeight: 250,
+ targetWidth: 250,
+ targetHeight: 250,
+ ref totalTests,
+ ref failedTests);
+
+ // Summary of test results
+ Console.WriteLine($"TOTAL: {totalTests} tests, FAILED: {failedTests} tests.");
}
///
- /// Generates a barcode with the specified parameters, then validates that the actual image dimensions
- /// do not exceed the requested point dimensions when AutoSizeMode.Nearest is applied.
+ /// Generates a barcode image with the specified target dimensions and checks that the actual
+ /// image size does not exceed the target while preserving the aspect ratio.
///
- /// The barcode symbology to use.
- /// The data to encode in the barcode.
- /// Desired maximum image width in points.
- /// Desired maximum image height in points.
- static void RunTest(BaseEncodeType encodeType, string codeText, float widthPt, float heightPt)
+ /// Identifier for the test case.
+ /// Expected maximum width (not used directly, kept for compatibility).
+ /// Expected maximum height (not used directly, kept for compatibility).
+ /// Desired width for the generated image.
+ /// Desired height for the generated image.
+ /// Reference to the total test counter.
+ /// Reference to the failed test counter.
+ static void RunTest(
+ string testName,
+ int expectedWidth,
+ int expectedHeight,
+ int targetWidth,
+ int targetHeight,
+ ref int totalTests,
+ ref int failedTests)
{
- // Initialize the barcode generator with the chosen symbology and data.
- using (var generator = new BarcodeGenerator(encodeType, codeText))
+ totalTests++;
+
+ // Initialize a barcode generator for Code128 with sample text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Configure AutoSizeMode to Nearest and set target dimensions in points.
+ // Configure AutoSizeMode to Nearest and set the target dimensions.
generator.Parameters.AutoSizeMode = AutoSizeMode.Nearest;
- generator.Parameters.ImageWidth.Point = widthPt;
- generator.Parameters.ImageHeight.Point = heightPt;
+ generator.Parameters.ImageWidth.Point = (float)targetWidth;
+ generator.Parameters.ImageHeight.Point = (float)targetHeight;
// Generate the barcode image.
using (Bitmap bitmap = generator.GenerateBarCodeImage())
{
- // Actual dimensions of the generated bitmap (in pixels).
int actualWidth = bitmap.Width;
int actualHeight = bitmap.Height;
- // Verify that the actual dimensions do not exceed the requested dimensions.
- // AutoSizeMode.Nearest may reduce the size to the nearest lower possible value.
- bool widthOk = actualWidth <= widthPt;
- bool heightOk = actualHeight <= heightPt;
+ // Validate that the actual dimensions are within the target bounds.
+ bool sizeOk = actualWidth <= targetWidth && actualHeight <= targetHeight;
+
+ // Validate that the aspect ratio is preserved within a small tolerance.
+ bool aspectOk = Math.Abs((float)actualWidth / actualHeight - (float)targetWidth / targetHeight) < 0.01f;
- // Output the test results to the console.
- Console.WriteLine($"Test for {encodeType.TypeName} with CodeText \"{codeText}\":");
- Console.WriteLine($" Expected max width: {widthPt}pt, actual width: {actualWidth}px");
- Console.WriteLine($" Expected max height: {heightPt}pt, actual height: {actualHeight}px");
- Console.WriteLine($" Width check: {(widthOk ? "PASS" : "FAIL")}");
- Console.WriteLine($" Height check: {(heightOk ? "PASS" : "FAIL")}");
- Console.WriteLine();
+ if (sizeOk && aspectOk)
+ {
+ Console.WriteLine($"{testName}: PASS (Actual: {actualWidth}x{actualHeight})");
+ }
+ else
+ {
+ failedTests++;
+ Console.WriteLine($"{testName}: FAIL");
+ Console.WriteLine($" Expected max size: {targetWidth}x{targetHeight}");
+ Console.WriteLine($" Actual size: {actualWidth}x{actualHeight}");
+ Console.WriteLine($" Size OK: {sizeOk}, Aspect OK: {aspectOk}");
+ }
}
}
}