diff --git a/barcode-size-and-resolution/calculate-xdimension-in-pixels-for-2-mm-module-width-at-300-dpi-then-set-it-on-generator.cs b/barcode-size-and-resolution/calculate-xdimension-in-pixels-for-2-mm-module-width-at-300-dpi-then-set-it-on-generator.cs
index c5322e6..ad553ba 100644
--- a/barcode-size-and-resolution/calculate-xdimension-in-pixels-for-2-mm-module-width-at-300-dpi-then-set-it-on-generator.cs
+++ b/barcode-size-and-resolution/calculate-xdimension-in-pixels-for-2-mm-module-width-at-300-dpi-then-set-it-on-generator.cs
@@ -1,51 +1,47 @@
// Title: Calculate XDimension in Pixels for 2 mm Module Width at 300 dpi
-// Description: Demonstrates how to compute the X‑dimension (module width) in pixels for a 2 mm barcode module at 300 dpi and apply it to a barcode generator.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to control barcode sizing by setting resolution and X‑dimension. It uses the BarcodeGenerator, EncodeTypes, and generation parameters classes, which are commonly employed when developers need precise physical dimensions for printed barcodes. Typical use cases include packaging, labeling, and compliance with industry standards that require exact module widths.
+// Description: Demonstrates how to compute the XDimension (module width) in pixels for a given millimeter size and DPI, then apply it to a barcode generator.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to configure barcode dimensions using the BarcodeGenerator and its Parameters.Barcode.XDimension properties. Typical use cases include customizing barcode size for printing or display at specific resolutions. Developers often need to convert physical measurements (mm) to pixel units to ensure consistent rendering across devices.
// Prompt: Calculate XDimension in Pixels for 2 mm module width at 300 dpi, then set it on generator.
-// Tags: barcode, xdimension, resolution, dpi, code128, image, aspose.barcode, generation
+// Tags: barcode, xdimension, module width, dpi, pixel conversion, aspose.barcode, code128, image generation
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Example program that calculates the X‑dimension in pixels for a 2 mm module width at 300 dpi
+/// Example program that calculates the XDimension in pixels for a 2 mm module width at 300 dpi
/// and applies the value to a barcode generator.
///
class Program
{
///
- /// Entry point. Performs the calculation, configures the generator, and saves the barcode image.
+ /// Entry point of the example. Performs the conversion and saves a barcode image.
///
static void Main()
{
- // Desired module (X‑dimension) width: 2 mm.
- // Convert millimetres to inches: 2 mm = 0.0787401575 inches.
- // At 300 dpi, pixels = inches × DPI ≈ 23.622 pixels.
- // Use the exact float value for maximum precision.
- const float xDimensionPixels = 23.622f;
- const float resolutionDpi = 300f;
-
- // Create a barcode generator for Code128 (any symbology could be used here).
+ // Desired module width in millimeters.
+ const float moduleWidthMm = 2f;
+
+ // Target resolution in dots per inch.
+ const float dpi = 300f;
+
+ // Convert millimeters to inches (1 inch = 25.4 mm).
+ float moduleWidthInches = moduleWidthMm / 25.4f;
+
+ // Calculate the module width in pixels: inches multiplied by DPI.
+ float xDimensionPixels = moduleWidthInches * dpi;
+
+ // Create a barcode generator for Code128 symbology.
using (var generator = new BarcodeGenerator(EncodeTypes.Code128))
{
- // Set the generator's resolution to match the DPI used in the calculation.
- generator.Parameters.Resolution = resolutionDpi;
+ // Set the data to encode.
+ generator.CodeText = "1234567890";
- // Apply the calculated X‑dimension in pixels.
+ // Apply the calculated XDimension (pixel width of a single module).
generator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels;
- // Example codetext to encode.
- generator.CodeText = "1234567890";
-
// Save the generated barcode as a PNG image.
generator.Save("barcode.png");
}
-
- // Inform the user that the barcode has been generated with the specified settings.
- Console.WriteLine(
- "Barcode generated with XDimension = {0} pixels at {1} DPI.",
- xDimensionPixels,
- resolutionDpi);
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/configure-barcodegenerator-with-millimeters-set-barcodeheight-to-30-barcodewidth-to-50-and-save-jpeg.cs b/barcode-size-and-resolution/configure-barcodegenerator-with-millimeters-set-barcodeheight-to-30-barcodewidth-to-50-and-save-jpeg.cs
index 9ada662..44e24bf 100644
--- a/barcode-size-and-resolution/configure-barcodegenerator-with-millimeters-set-barcodeheight-to-30-barcodewidth-to-50-and-save-jpeg.cs
+++ b/barcode-size-and-resolution/configure-barcodegenerator-with-millimeters-set-barcodeheight-to-30-barcodewidth-to-50-and-save-jpeg.cs
@@ -1,15 +1,16 @@
// Title: Generate Code128 Barcode with Millimeter Dimensions and Save as JPEG
-// Description: Demonstrates configuring Aspose.BarCode's BarcodeGenerator to use millimeter units, set specific height and width, and export the barcode as a JPEG image.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to control image size using the Parameters.ImageHeight and ImageWidth properties with millimeter units. Developers commonly use these APIs to produce barcodes with precise physical dimensions for printing on labels, packaging, or documents. The key classes shown are BarcodeGenerator, EncodeTypes, and the Parameters sub‑objects, which are essential for customizing barcode appearance.
+// Description: Demonstrates configuring Aspose.BarCode's BarcodeGenerator to use millimeter units, set specific height and width, and save the result as a JPEG image.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to create barcodes with precise physical dimensions using the BarcodeGenerator class. Typical use cases include printing barcodes on labels or packaging where exact size specifications are required. Developers often need to set image size units, adjust dimensions, and export to common image formats.
// Prompt: Configure BarcodeGenerator with Millimeters, set BarCodeHeight to 30, BarCodeWidth to 50, and save JPEG.
-// Tags: code128, barcode generation, jpeg, millimeters, aspose.barcode, barcodegenerator, parameters
+// Tags: code128, barcode generation, image size, millimeters, jpeg, aspose.barcode
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Example program that creates a Code128 barcode, sets its size in millimeters, and saves it as a JPEG file.
+/// Example program that creates a Code128 barcode, sets its size using millimeter units,
+/// and saves the image as a JPEG file.
///
class Program
{
@@ -18,17 +19,23 @@ class Program
///
static void Main()
{
- // Initialize a BarcodeGenerator for Code128 with the sample text "123456"
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ // Initialize a BarcodeGenerator for the Code128 symbology
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128))
{
- // Configure the barcode image height to 30 millimeters
+ // Define the text to encode in the barcode
+ generator.CodeText = "123456";
+
+ // Set the barcode image height to 30 millimeters
generator.Parameters.ImageHeight.Millimeters = 30f;
- // Configure the barcode image width to 50 millimeters
+ // Set the barcode image width to 50 millimeters
generator.Parameters.ImageWidth.Millimeters = 50f;
- // Save the generated barcode as a JPEG image file named "barcode.jpg"
+ // Save the generated barcode as a JPEG image file
generator.Save("barcode.jpg");
}
+
+ // Inform the user that the barcode image has been saved
+ Console.WriteLine("Barcode image saved as barcode.jpg");
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/convert-dimensions-from-pixels-to-points-via-unit-class-then-generate-code128-image-using-converted-values.cs b/barcode-size-and-resolution/convert-dimensions-from-pixels-to-points-via-unit-class-then-generate-code128-image-using-converted-values.cs
index 5f78f1f..842f398 100644
--- a/barcode-size-and-resolution/convert-dimensions-from-pixels-to-points-via-unit-class-then-generate-code128-image-using-converted-values.cs
+++ b/barcode-size-and-resolution/convert-dimensions-from-pixels-to-points-via-unit-class-then-generate-code128-image-using-converted-values.cs
@@ -1,49 +1,51 @@
// Title: Convert Pixels to Points and Generate Code128 Barcode Image
-// Description: Demonstrates converting image dimensions from pixels to points using Aspose.BarCode's Unit class and generating a Code128 barcode with those dimensions.
-// Category-Description: This example belongs to the Aspose.BarCode image sizing and barcode generation category. It showcases the use of the BarcodeGenerator class, AutoSizeMode, and Unit properties (ImageWidth, ImageHeight) to control output size. Developers often need to convert between measurement units (pixels, points, inches) when creating barcodes for print or screen, and this snippet illustrates the typical workflow for such scenarios.
+// Description: Demonstrates converting barcode dimensions from pixels to points using the Unit class, then creates a Code128 barcode image.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, showcasing how to set size parameters in pixels and retrieve their point equivalents via the Unit class. It highlights key classes such as BarcodeGenerator, EncodeTypes, and the Parameters property, which developers commonly use to customize barcode appearance for printing and screen display.
// Prompt: Convert dimensions from Pixels to Points via Unit class, then generate Code128 image using converted values.
-// Tags: barcode, code128, image sizing, unit conversion, points, pixels, aspnet, aspose.barcode, generation, png
+// Tags: code128, dimension conversion, png, barcodegenerator, unit
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Example program that converts pixel dimensions to points and generates a Code128 barcode image.
+/// Demonstrates converting dimensions from pixels to points and generating a Code128 barcode image.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Sets barcode parameters in pixels, obtains point values, and saves the barcode as PNG.
///
static void Main()
{
- // Desired dimensions in pixels
- float widthPixels = 300f;
- float heightPixels = 150f;
-
- // Convert pixels to points (1 point = 1/72 inch, 1 pixel = 1/96 inch)
- // points = pixels * (72 / 96) = pixels * 0.75
- float widthPoints = widthPixels * 0.75f;
- float heightPoints = heightPixels * 0.75f;
-
- // Create a Code128 barcode generator with sample text
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ // Define barcode image dimensions and bar metrics in pixels
+ float imageWidthPixels = 300f;
+ float imageHeightPixels = 150f;
+ float xDimensionPixels = 2f;
+ float barHeightPixels = 40f;
+
+ // Initialize a Code128 barcode generator with sample data
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Use interpolation mode so ImageWidth/ImageHeight control the size
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
-
- // Apply the converted dimensions (points) to the generator
- generator.Parameters.ImageWidth.Point = widthPoints;
- generator.Parameters.ImageHeight.Point = heightPoints;
-
- // Optional: set resolution (dpi) if needed
- generator.Parameters.Resolution = 96f;
-
- // Save the barcode image as PNG
+ // Assign pixel values; the Unit class will automatically convert them to points
+ generator.Parameters.ImageWidth.Pixels = imageWidthPixels;
+ generator.Parameters.ImageHeight.Pixels = imageHeightPixels;
+ generator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels;
+ generator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels;
+
+ // Retrieve the converted values in points for demonstration purposes
+ float imageWidthPoints = generator.Parameters.ImageWidth.Point;
+ float imageHeightPoints = generator.Parameters.ImageHeight.Point;
+ float xDimensionPoints = generator.Parameters.Barcode.XDimension.Point;
+ float barHeightPoints = generator.Parameters.Barcode.BarHeight.Point;
+
+ // Output the point values to the console
+ Console.WriteLine($"Image size: {imageWidthPoints}pt x {imageHeightPoints}pt");
+ Console.WriteLine($"XDimension: {xDimensionPoints}pt, BarHeight: {barHeightPoints}pt");
+
+ // Save the generated barcode as a PNG image file
generator.Save("code128.png");
}
-
- Console.WriteLine("Barcode generated and saved as code128.png");
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/create-console-utility-reading-csv-values-assigning-size-units-and-outputting-png-files.cs b/barcode-size-and-resolution/create-console-utility-reading-csv-values-assigning-size-units-and-outputting-png-files.cs
index c2fa264..e645fcd 100644
--- a/barcode-size-and-resolution/create-console-utility-reading-csv-values-assigning-size-units-and-outputting-png-files.cs
+++ b/barcode-size-and-resolution/create-console-utility-reading-csv-values-assigning-size-units-and-outputting-png-files.cs
@@ -1,114 +1,83 @@
-// Title: Generate Code128 barcodes from CSV and save as PNG
-// Description: Reads a CSV file containing barcode text and image dimensions, then creates PNG images using Aspose.BarCode.
-// Category-Description: Demonstrates Aspose.BarCode generation with size control, covering BarcodeGenerator, EncodeTypes, and image format settings. Useful for developers needing batch barcode creation, custom dimensions, and file output in console utilities.
-// Prompt: Create console utility reading CSV values, assigning size units, and outputting PNG files.
-// Tags: barcode symbology, generation, png, csv, console, aspose.barcode, code128, size units
-
using System;
-using System.Collections.Generic;
-using System.Globalization;
using System.IO;
+using System.Globalization;
using Aspose.BarCode.Generation;
+using Aspose.BarCode;
using Aspose.Drawing;
-///
-/// Console utility that reads barcode data from a CSV file (or uses sample data) and generates PNG images with specified dimensions.
-///
class Program
{
- ///
- /// Entry point. Accepts optional CSV file path argument, processes each line, and saves generated barcodes.
- ///
- /// Command‑line arguments; first argument may be the CSV file path.
- static void Main(string[] args)
+ static void Main()
{
- // Determine CSV file path (first argument or default)
- string csvPath = args.Length > 0 ? args[0] : "input.csv";
+ // Define CSV file path
+ string csvPath = "data.csv";
- // Prepare data list: each item holds the code text and desired image size (width, height) in points
- var items = new List<(string CodeText, float Width, float Height)>();
-
- if (File.Exists(csvPath))
+ // If CSV does not exist, create a sample file with a few rows
+ if (!File.Exists(csvPath))
{
- // Read CSV lines
- foreach (var line in File.ReadAllLines(csvPath))
+ using (var writer = new StreamWriter(csvPath))
{
- // Skip empty lines
- if (string.IsNullOrWhiteSpace(line))
- continue;
-
- // Expected format: CodeText,Width,Height
- var parts = line.Split(',');
- if (parts.Length != 3)
- {
- Console.WriteLine($"Invalid line (expected 3 columns): {line}");
- continue;
- }
-
- // Parse barcode text
- string code = parts[0].Trim();
+ // Format: CodeText,XDimension(Point),ImageWidth(Point),ImageHeight(Point)
+ writer.WriteLine("ABC123,2.5,300,150");
+ writer.WriteLine("XYZ789,3.0,250,120");
+ writer.WriteLine("123456,1.8,200,100");
+ }
+ }
- // Parse width (points)
- if (!float.TryParse(parts[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out float width))
- {
- Console.WriteLine($"Invalid width value: {parts[1]}");
- continue;
- }
+ // Read all lines from CSV
+ string[] lines = File.ReadAllLines(csvPath);
+ int index = 1;
- // Parse height (points)
- if (!float.TryParse(parts[2].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out float height))
- {
- Console.WriteLine($"Invalid height value: {parts[2]}");
- continue;
- }
+ foreach (string line in lines)
+ {
+ if (string.IsNullOrWhiteSpace(line))
+ continue;
- // Add valid entry to the collection
- items.Add((code, width, height));
+ // Split CSV fields
+ string[] parts = line.Split(',');
+ if (parts.Length < 4)
+ {
+ Console.WriteLine($"Skipping invalid line {index}: {line}");
+ index++;
+ continue;
}
- }
- else
- {
- // Fallback sample data (5 items) when CSV is missing
- items.Add(("Sample001", 200f, 100f));
- items.Add(("Sample002", 250f, 120f));
- items.Add(("Sample003", 180f, 90f));
- items.Add(("Sample004", 220f, 110f));
- items.Add(("Sample005", 240f, 130f));
- Console.WriteLine($"CSV file not found at '{csvPath}'. Using sample data.");
- }
- // Ensure output directory exists
- string outputDir = "Barcodes";
- if (!Directory.Exists(outputDir))
- Directory.CreateDirectory(outputDir);
+ string codeText = parts[0].Trim();
- // Process each item and generate a PNG barcode
- foreach (var item in items)
- {
- // Use Code128 as a generic 1D barcode type
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, item.CodeText))
+ // Parse numeric values using invariant culture
+ if (!float.TryParse(parts[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out float xDim) ||
+ !float.TryParse(parts[2].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out float imgWidth) ||
+ !float.TryParse(parts[3].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out float imgHeight))
{
- // Set image size using point units
- generator.Parameters.ImageWidth.Point = item.Width;
- generator.Parameters.ImageHeight.Point = item.Height;
+ Console.WriteLine($"Skipping line with invalid numbers {index}: {line}");
+ index++;
+ continue;
+ }
- // Use interpolation mode to respect the explicit size
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ // Create barcode generator for Code128 (as a common 1D symbology)
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ {
+ // Assign size units
+ generator.Parameters.Barcode.XDimension.Point = xDim; // smallest bar width
+ generator.Parameters.ImageWidth.Point = imgWidth; // overall image width
+ generator.Parameters.ImageHeight.Point = imgHeight; // overall image height
- // Optional visual settings
+ // Optional: set colors
generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
generator.Parameters.BackColor = Aspose.Drawing.Color.White;
- // Build a safe output file name
- string safeCode = string.Concat(item.CodeText.Split(Path.GetInvalidFileNameChars()));
- string outputPath = Path.Combine(outputDir, $"{safeCode}.png");
+ // Build output file name
+ string outputFile = $"barcode_{index}.png";
// Save as PNG
- generator.Save(outputPath, BarCodeImageFormat.Png);
- Console.WriteLine($"Generated barcode for '{item.CodeText}' -> {outputPath}");
+ generator.Save(outputFile, BarCodeImageFormat.Png);
+
+ Console.WriteLine($"Generated {outputFile} for code '{codeText}'");
}
+
+ index++;
}
- // Program ends automatically
+ Console.WriteLine("Processing completed.");
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/create-helper-method-converting-values-between-inches-and-millimeters-for-barcode-size-calculations.cs b/barcode-size-and-resolution/create-helper-method-converting-values-between-inches-and-millimeters-for-barcode-size-calculations.cs
index 30a10e1..2204051 100644
--- a/barcode-size-and-resolution/create-helper-method-converting-values-between-inches-and-millimeters-for-barcode-size-calculations.cs
+++ b/barcode-size-and-resolution/create-helper-method-converting-values-between-inches-and-millimeters-for-barcode-size-calculations.cs
@@ -1,66 +1,85 @@
-// Title: Barcode size conversion between inches and millimeters
-// Description: Demonstrates helper methods for converting inches to millimeters and vice versa, used for setting barcode image dimensions.
-// Category-Description: This example belongs to the Aspose.BarCode image sizing category, illustrating how to use the AutoSizeMode.Interpolation mode and the ImageWidth/ImageHeight properties (Millimeters unit) to control barcode dimensions. Developers often need to convert measurement units when integrating barcode generation into print layouts or UI designs, and these helper methods simplify that process.
+// Title: Unit conversion helper for barcode dimensions
+// Description: Demonstrates converting inches to millimeters and vice‑versa for sizing Aspose.BarCode images and XDimension.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to use the BarcodeGenerator class with size parameters. It shows typical use cases such as setting image dimensions in inches and barcode module size (XDimension) in millimeters, helping developers who need precise physical measurements for printed barcodes. The snippet highlights the Parameters.ImageWidth, Parameters.Barcode.XDimension properties and custom conversion helpers.
// Prompt: Create helper method converting values between Inches and Millimeters for barcode size calculations.
-// Tags: barcode, size conversion, inches, millimeters, autosizemode, imagewidth, imageheight, aspose.barcode
+// Tags: barcode, conversion, inches, millimeters, aspose.barcode, generation, dimensions
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
-///
-/// Demonstrates conversion helpers and barcode generation with size set in millimeters.
-///
-class Program
+namespace BarcodeConversionHelper
{
- // Convert inches to millimeters (1 inch = 25.4 mm)
- static float InchesToMillimeters(float inches)
+ ///
+ /// Helper methods for converting between inches and millimeters.
+ ///
+ public static class UnitConverter
{
- return inches * 25.4f;
- }
+ // Conversion factor: 1 inch = 25.4 millimeters
+ private const float InchesToMillimetersFactor = 25.4f;
- // Convert millimeters to inches
- static float MillimetersToInches(float millimeters)
- {
- return millimeters / 25.4f;
+ ///
+ /// Converts inches to millimeters.
+ ///
+ /// Value in inches.
+ /// Equivalent value in millimeters.
+ public static float InchesToMillimeters(float inches)
+ {
+ return inches * InchesToMillimetersFactor;
+ }
+
+ ///
+ /// Converts millimeters to inches.
+ ///
+ /// Value in millimeters.
+ /// Equivalent value in inches.
+ public static float MillimetersToInches(float millimeters)
+ {
+ return millimeters / InchesToMillimetersFactor;
+ }
}
///
- /// Entry point: converts sample dimensions, generates a Code128 barcode with specified size, and saves it as PNG.
+ /// Demonstrates usage of UnitConverter with Aspose.BarCode to generate a barcode image.
///
- static void Main()
+ class Program
{
- // Sample dimensions in inches (typical for print layouts)
- float widthInInches = 2.0f;
- float heightInInches = 1.0f;
+ ///
+ /// Entry point of the example. Performs sample conversions and creates a barcode image.
+ ///
+ static void Main()
+ {
+ // Sample conversion: inches to millimeters
+ float widthInInches = 2.5f;
+ float widthInMillimeters = UnitConverter.InchesToMillimeters(widthInInches);
+ Console.WriteLine($"Width: {widthInInches} inches = {widthInMillimeters} mm");
- // Convert to millimeters for barcode size calculations
- float widthInMillimeters = InchesToMillimeters(widthInInches);
- float heightInMillimeters = InchesToMillimeters(heightInInches);
+ // Sample conversion: millimeters to inches
+ float heightInMillimeters = 50f;
+ float heightInInches = UnitConverter.MillimetersToInches(heightInMillimeters);
+ Console.WriteLine($"Height: {heightInMillimeters} mm = {heightInInches} inches");
- // Output conversion results to console
- Console.WriteLine($"Width: {widthInInches} inches = {widthInMillimeters} mm");
- Console.WriteLine($"Height: {heightInInches} inches = {heightInMillimeters} mm");
+ // Example usage with Aspose.BarCode:
+ // - Set image width in inches
+ // - Convert desired XDimension from millimeters to inches before assigning
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128))
+ {
+ // Set image width to 3 inches
+ generator.Parameters.ImageWidth.Inches = 3f;
- // Create a simple barcode and apply the converted size
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
- {
- // Use Interpolation mode to control size via ImageWidth/ImageHeight
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ // Desired XDimension is 0.5 mm; convert to inches for the generator
+ float xDimMillimeters = 0.5f;
+ float xDimInches = UnitConverter.MillimetersToInches(xDimMillimeters);
+ generator.Parameters.Barcode.XDimension.Inches = xDimInches;
- // Set size using the millimeter values
- generator.Parameters.ImageWidth.Millimeters = widthInMillimeters;
- generator.Parameters.ImageHeight.Millimeters = heightInMillimeters;
+ // Set the code text to encode
+ generator.CodeText = "12345";
- // Optional: set background and bar colors
- generator.Parameters.BackColor = Color.White;
- generator.Parameters.Barcode.BarColor = Color.Black;
+ // Save the barcode image to file
+ generator.Save("barcode.png");
+ }
- // Save the barcode image
- string outputPath = "barcode.png";
- generator.Save(outputPath);
- Console.WriteLine($"Barcode saved to {outputPath}");
+ Console.WriteLine("Barcode generated and saved as barcode.png");
}
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/create-unit-test-confirming-setting-resolution-to-300-dpi-scales-width-and-height-pixel-values-proportionally.cs b/barcode-size-and-resolution/create-unit-test-confirming-setting-resolution-to-300-dpi-scales-width-and-height-pixel-values-proportionally.cs
index 9dbc806..8e07f57 100644
--- a/barcode-size-and-resolution/create-unit-test-confirming-setting-resolution-to-300-dpi-scales-width-and-height-pixel-values-proportionally.cs
+++ b/barcode-size-and-resolution/create-unit-test-confirming-setting-resolution-to-300-dpi-scales-width-and-height-pixel-values-proportionally.cs
@@ -1,63 +1,78 @@
// Title: Verify barcode image resolution scaling
-// Description: Demonstrates that setting the barcode generator resolution to 300 dpi scales the image width and height proportionally compared to the default 96 dpi.
-// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how the Resolution property and AutoSizeMode.Interpolation affect pixel dimensions. It shows typical usage of BarcodeGenerator, its Parameters, and the Aspose.Drawing.Bitmap class for creating barcode images at different DPI settings, a common requirement for high‑resolution printing and scanning scenarios.
+// Description: Demonstrates how setting the barcode generator resolution to 300 dpi scales the resulting image dimensions proportionally compared to the default 96 dpi.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, its Parameters.ImageWidth/Height, and Parameters.Resolution properties. Developers often need to control output resolution for high‑quality printing or screen rendering, and this snippet shows the typical workflow of generating, saving, and measuring barcode images at different DPI settings.
// Prompt: Create unit test confirming setting resolution to 300 dpi scales width and height pixel values proportionally.
-// Tags: barcode, code128, resolution, dpi, interpolation, image generation, aspose.barcode, unit test
+// Tags: barcode symbology, resolution, png, barcodegenerator, image
using System;
+using System.IO;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Example program that verifies the effect of changing the barcode image resolution
-/// on the generated bitmap's pixel dimensions. It compares a 96 dpi image with a
-/// 300 dpi image to ensure proportional scaling.
+/// Demonstrates resolution scaling of barcode images using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the example. Generates barcode images at two different DPI
- /// settings and checks that width and height scale proportionally.
+ /// Entry point that generates barcode images at 96 dpi and 300 dpi, then verifies proportional scaling of pixel dimensions.
///
static void Main()
{
- // Create a barcode generator for Code128 with the value "Test"
+ // Define logical size in points (1 point = 1/72 inch)
+ const float logicalWidthPoints = 200f;
+ const float logicalHeightPoints = 100f;
+
+ // Generate first image with default resolution (96 dpi)
+ var size96 = GenerateBarcodeImage(logicalWidthPoints, logicalHeightPoints, 96f);
+
+ // Generate second image with higher resolution (300 dpi)
+ var size300 = GenerateBarcodeImage(logicalWidthPoints, logicalHeightPoints, 300f);
+
+ // Expected scaling factor based on DPI change
+ float expectedFactor = 300f / 96f;
+
+ // Verify that width and height are scaled proportionally within a small tolerance
+ bool widthMatches = Math.Abs((float)size300.width / size96.width - expectedFactor) < 0.01f;
+ bool heightMatches = Math.Abs((float)size300.height / size96.height - expectedFactor) < 0.01f;
+
+ if (widthMatches && heightMatches)
+ {
+ Console.WriteLine("PASSED: Resolution scaling works as expected.");
+ }
+ else
+ {
+ Console.WriteLine("FAILED: Resolution scaling mismatch.");
+ Console.WriteLine($"96dpi size: {size96.width}x{size96.height}");
+ Console.WriteLine($"300dpi size: {size300.width}x{size300.height}");
+ }
+ }
+
+ // Generates a barcode image with the specified logical size and resolution,
+ // then returns the pixel dimensions of the saved image.
+ static (int width, int height) GenerateBarcodeImage(float widthPoints, float heightPoints, float resolutionDpi)
+ {
+ // Initialize the barcode generator with Code128 symbology and sample text
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Test"))
{
- // Enable interpolation mode so that resolution changes affect pixel size
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ // Set logical image size in points
+ generator.Parameters.ImageWidth.Point = widthPoints;
+ generator.Parameters.ImageHeight.Point = heightPoints;
- // Define a base image size in pixels (width = 200, height = 100)
- generator.Parameters.ImageWidth.Pixels = 200f;
- generator.Parameters.ImageHeight.Pixels = 100f;
+ // Apply the desired resolution (DPI)
+ generator.Parameters.Resolution = resolutionDpi;
- // Generate image at the default resolution of 96 dpi
- generator.Parameters.Resolution = 96f;
- using (Bitmap bmp96 = generator.GenerateBarCodeImage())
+ // Save the generated barcode to a memory stream in PNG format
+ using (var ms = new MemoryStream())
{
- int width96 = bmp96.Width;
- int height96 = bmp96.Height;
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0;
- // Generate image at a higher resolution of 300 dpi
- generator.Parameters.Resolution = 300f;
- using (Bitmap bmp300 = generator.GenerateBarCodeImage())
+ // Load the image from the stream to read its pixel dimensions
+ using (var bitmap = (Bitmap)Image.FromStream(ms))
{
- int width300 = bmp300.Width;
- int height300 = bmp300.Height;
-
- // Expected scaling factor based on DPI change
- float factor = 300f / 96f;
-
- // Allow a tolerance of 1 pixel due to rounding differences
- bool widthOk = Math.Abs(width300 - (int)Math.Round(width96 * factor)) <= 1;
- bool heightOk = Math.Abs(height300 - (int)Math.Round(height96 * factor)) <= 1;
-
- // Output test result
- if (widthOk && heightOk)
- Console.WriteLine("PASSED");
- else
- Console.WriteLine($"FAILED: Expected width≈{width96 * factor}, got {width300}; height≈{height96 * factor}, got {height300}");
+ return (bitmap.Width, bitmap.Height);
}
}
}
diff --git a/barcode-size-and-resolution/create-unit-test-verifying-barcode-with-barcodeheight-zero-enables-auto-size-based-on-content-using-default-units.cs b/barcode-size-and-resolution/create-unit-test-verifying-barcode-with-barcodeheight-zero-enables-auto-size-based-on-content-using-default-units.cs
index ac068b4..0fa6d4d 100644
--- a/barcode-size-and-resolution/create-unit-test-verifying-barcode-with-barcodeheight-zero-enables-auto-size-based-on-content-using-default-units.cs
+++ b/barcode-size-and-resolution/create-unit-test-verifying-barcode-with-barcodeheight-zero-enables-auto-size-based-on-content-using-default-units.cs
@@ -1,73 +1,83 @@
-// Title: Verify auto‑size behavior of barcode when BarCodeHeight is zero
-// Description: Demonstrates a unit‑test‑style check that a barcode generated with BarCodeHeight left at its default (zero) automatically sizes itself based on the encoded content.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the AutoSizeMode property (especially Interpolation) together with default measurement units to let the library determine optimal barcode dimensions. Developers working with dynamic barcode rendering, layout‑aware image creation, or automated testing of barcode size behavior will find this pattern useful.
+// Title: Verify auto‑size of barcode when BarCodeHeight is zero
+// Description: Demonstrates that setting BarCodeHeight to zero (by not assigning it) and using AutoSizeMode.Interpolation automatically adjusts the barcode height based on its content.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to control barcode dimensions using the AutoSizeMode property of BarcodeGenerator. It shows default behavior versus interpolation auto‑sizing, a common requirement when developers need dynamic barcode sizing without manually calculating dimensions.
// Prompt: Create unit test verifying barcode with BarCodeHeight zero enables auto‑size based on content, using default units.
-// Tags: barcode, autosize, interpolation, code128, unit-test, default-units, aspnet, aspose.barcode
+// Tags: barcode, code128, autosize, interpolation, generation, unit-test, aspose.barcode
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Contains a simple console‑based test that verifies auto‑size functionality
-/// of a generated barcode when the bar height is not explicitly set (default zero).
+/// Example program that compares default barcode height with height obtained
+/// when AutoSizeMode.Interpolation is applied (BarCodeHeight left unset, i.e., zero).
///
class Program
{
///
- /// Entry point of the console application. Executes the auto‑size test and
- /// writes the result to the console.
+ /// Entry point. Generates two barcodes and validates that interpolation auto‑size
+ /// produces a greater image height than the default configuration.
///
static void Main()
{
- // Run the test and output result
- try
- {
- bool result = TestAutoSizeWithDefaultUnits();
+ // Sample barcode text to encode
+ const string codeText = "12345678901234567890";
- // Report PASS or FAIL based on the test outcome
- Console.WriteLine(result ? "PASS: Auto-size enabled correctly." : "FAIL: Auto-size not as expected.");
- }
- catch (Exception ex)
+ // --------------------------------------------------------------------
+ // Generate barcode using default settings (AutoSizeMode = None)
+ // --------------------------------------------------------------------
+ int defaultHeight;
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
{
- // Unexpected exception handling – report as failure
- Console.WriteLine($"FAIL: Unexpected exception - {ex.GetType().Name}: {ex.Message}");
- }
- }
+ // No explicit BarHeight or AutoSizeMode assignment – defaults are used
+ using (Bitmap bitmap = generator.GenerateBarCodeImage())
+ {
+ // Capture the height of the generated image
+ defaultHeight = bitmap.Height;
- // Verifies that when AutoSizeMode is set to Interpolation (and BarHeight is not set),
- // the generated barcode image size adapts to the content using default units.
- static bool TestAutoSizeWithDefaultUnits()
- {
- // Sample barcode text
- const string codeText = "Test12345";
+ // Optional: save image to memory stream for visual inspection
+ using (var stream = new MemoryStream())
+ {
+ bitmap.Save(stream, ImageFormat.Png);
+ }
+ }
+ }
- // Create generator for Code128 (a 1D barcode)
+ // --------------------------------------------------------------------
+ // Generate barcode with AutoSizeMode.Interpolation (auto‑size based on content)
+ // --------------------------------------------------------------------
+ int interpolatedHeight;
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
{
- // Enable auto-size via interpolation mode.
+ // Enable interpolation auto‑size; BarHeight remains unset (zero)
generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- // Do NOT set BarHeight; leaving it at default allows auto-sizing.
- // Generate the barcode image.
using (Bitmap bitmap = generator.GenerateBarCodeImage())
{
- // Ensure an image was created.
- if (bitmap == null)
- return false;
-
- // Verify that the image has a non‑zero height and width (auto‑sized).
- if (bitmap.Height <= 0 || bitmap.Width <= 0)
- return false;
+ // Capture the height of the interpolated image
+ interpolatedHeight = bitmap.Height;
- // Optionally, save the image for manual inspection (not required for the test).
- // bitmap.Save("autoSizeBarcode.png", ImageFormat.Png);
-
- // If we reach this point, auto‑size behaved as expected.
- return true;
+ // Optional: save image to memory stream for visual inspection
+ using (var stream = new MemoryStream())
+ {
+ bitmap.Save(stream, ImageFormat.Png);
+ }
}
}
+
+ // --------------------------------------------------------------------
+ // Validation: interpolated height should be greater than default height
+ // --------------------------------------------------------------------
+ if (interpolatedHeight > defaultHeight && interpolatedHeight > 0)
+ {
+ Console.WriteLine("PASS: AutoSizeMode.Interpolation increased barcode height based on content.");
+ }
+ else
+ {
+ Console.WriteLine("FAIL: AutoSizeMode.Interpolation did not adjust barcode height as expected.");
+ }
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/create-web-api-endpoint-accepting-width-height-and-unit-generating-barcode-and-returning-image-bytes.cs b/barcode-size-and-resolution/create-web-api-endpoint-accepting-width-height-and-unit-generating-barcode-and-returning-image-bytes.cs
index c82b27e..acb0d12 100644
--- a/barcode-size-and-resolution/create-web-api-endpoint-accepting-width-height-and-unit-generating-barcode-and-returning-image-bytes.cs
+++ b/barcode-size-and-resolution/create-web-api-endpoint-accepting-width-height-and-unit-generating-barcode-and-returning-image-bytes.cs
@@ -1,8 +1,8 @@
-// Title: Generate barcode image with custom dimensions via console arguments
-// Description: Demonstrates how to set barcode image size using width, height, and measurement unit, then output the PNG bytes.
-// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes. Developers often need to create barcodes with specific dimensions for web APIs, reports, or print media; this snippet shows how to control size units (points, pixels, inches, millimeters) and disable auto‑sizing.
+// Title: Generate barcode image with custom dimensions via simulated API endpoint
+// Description: Demonstrates how to accept width, height, and unit parameters, generate a Code128 barcode using Aspose.BarCode, and return the PNG image bytes as a Base64 string, mimicking a web API response.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes to create barcode images with explicit sizing. Typical scenarios include web services that need to produce barcode graphics on‑the‑fly based on client‑supplied dimensions. Developers often need to control image size units (points, pixels, millimeters, inches) and return the binary data directly in HTTP responses.
// Prompt: Create web API endpoint accepting width, height, and unit, generating barcode and returning image bytes.
-// Tags: barcode, code128, image generation, png, dimensions, unit conversion, aspnet, aspnetcore, aspnet-webapi
+// Tags: code128, barcode generation, png, image dimensions, autosizemode, aspnet, aspnetcore, aspose.barcode
using System;
using System.IO;
@@ -11,91 +11,72 @@
using Aspose.Drawing.Imaging;
///
-/// Demonstrates barcode generation with explicit image dimensions supplied via command‑line arguments.
+/// Simulates a web API endpoint that generates a barcode image based on supplied dimensions
+/// and returns the image bytes as a Base64 string.
///
class Program
{
///
- /// Entry point of the console application. Parses width, height, and unit arguments,
- /// configures the barcode generator, and outputs the PNG image bytes.
+ /// Entry point that parses command‑line arguments for width, height, and unit,
+ /// creates a Code128 barcode with the specified size, and writes the PNG image bytes
+ /// to the console as a Base64 string (representing an HTTP response body).
///
static void Main()
{
- // The snippet runner cannot host an HTTP server, so we demonstrate the core barcode logic.
- // Width, height and unit are taken from command‑line arguments; defaults are used if missing.
+ // Default dimensions for CI environments where no arguments are provided
+ float width = 300f;
+ float height = 150f;
+ string unit = "pt";
- float widthValue = 300f; // default width
- float heightValue = 150f; // default height
- string unit = "pt"; // default unit (points)
-
- // Retrieve command‑line arguments; args[0] is the executable name.
+ // Retrieve command‑line arguments (args[0] is the executable name)
string[] args = Environment.GetCommandLineArgs();
- // Parse optional width argument.
- if (args.Length > 1 && float.TryParse(args[1], out float w))
- widthValue = w;
-
- // Parse optional height argument.
- if (args.Length > 2 && float.TryParse(args[2], out float h))
- heightValue = h;
-
- // Parse optional unit argument.
- if (args.Length > 3)
- unit = args[3].ToLowerInvariant();
+ // Override defaults if valid arguments are supplied
+ if (args.Length > 1 && float.TryParse(args[1], out float w)) width = w;
+ if (args.Length > 2 && float.TryParse(args[2], out float h)) height = h;
+ if (args.Length > 3) unit = args[3].ToLowerInvariant();
- // Create the barcode generator for Code128 with a sample codetext.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ // Initialize the barcode generator for Code128 symbology
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128))
{
- // Set explicit image size using the requested unit.
+ // Disable automatic sizing to enforce explicit dimensions
+ generator.Parameters.AutoSizeMode = AutoSizeMode.None;
+
+ // Apply the requested unit to the image width and height
switch (unit)
{
case "pt":
- case "point":
- case "points":
- generator.Parameters.ImageWidth.Point = widthValue;
- generator.Parameters.ImageHeight.Point = heightValue;
+ generator.Parameters.ImageWidth.Point = width;
+ generator.Parameters.ImageHeight.Point = height;
break;
case "px":
- case "pixel":
- case "pixels":
- generator.Parameters.ImageWidth.Pixels = widthValue;
- generator.Parameters.ImageHeight.Pixels = heightValue;
- break;
- case "in":
- case "inch":
- case "inches":
- generator.Parameters.ImageWidth.Inches = widthValue;
- generator.Parameters.ImageHeight.Inches = heightValue;
+ generator.Parameters.ImageWidth.Pixels = width;
+ generator.Parameters.ImageHeight.Pixels = height;
break;
case "mm":
- case "millimeter":
- case "millimeters":
- generator.Parameters.ImageWidth.Millimeters = widthValue;
- generator.Parameters.ImageHeight.Millimeters = heightValue;
+ generator.Parameters.ImageWidth.Millimeters = width;
+ generator.Parameters.ImageHeight.Millimeters = height;
break;
- default:
- // Fallback to points if the unit is unsupported.
- Console.WriteLine($"Unsupported unit '{unit}'. Using points as fallback.");
- generator.Parameters.ImageWidth.Point = widthValue;
- generator.Parameters.ImageHeight.Point = heightValue;
+ case "in":
+ generator.Parameters.ImageWidth.Inches = width;
+ generator.Parameters.ImageHeight.Inches = height;
break;
+ default:
+ throw new ArgumentException($"Unsupported unit '{unit}'. Use pt, px, mm, or in.");
}
- // Ensure AutoSizeMode is None so that the explicit size is respected.
- generator.Parameters.AutoSizeMode = AutoSizeMode.None;
+ // Set the barcode content
+ generator.CodeText = "123456";
- // Generate the barcode image into a memory stream.
+ // Save the barcode to a memory stream in PNG format
using (var ms = new MemoryStream())
{
generator.Save(ms, BarCodeImageFormat.Png);
byte[] imageBytes = ms.ToArray();
- // Output the size of the generated image byte array.
- Console.WriteLine($"Generated barcode image bytes: {imageBytes.Length}");
-
- // Optionally, write the image to a file for verification.
- File.WriteAllBytes("barcode.png", imageBytes);
- Console.WriteLine("Barcode saved as 'barcode.png' in the current directory.");
+ // Convert the image bytes to Base64 to simulate an HTTP response body
+ string base64 = Convert.ToBase64String(imageBytes);
+ Console.WriteLine(base64);
}
}
}
diff --git a/barcode-size-and-resolution/design-ui-control-allowing-users-to-toggle-between-pixels-and-millimeters-for-barcode-size-updating-preview-instantly.cs b/barcode-size-and-resolution/design-ui-control-allowing-users-to-toggle-between-pixels-and-millimeters-for-barcode-size-updating-preview-instantly.cs
index 27120e9..d255f30 100644
--- a/barcode-size-and-resolution/design-ui-control-allowing-users-to-toggle-between-pixels-and-millimeters-for-barcode-size-updating-preview-instantly.cs
+++ b/barcode-size-and-resolution/design-ui-control-allowing-users-to-toggle-between-pixels-and-millimeters-for-barcode-size-updating-preview-instantly.cs
@@ -1,79 +1,60 @@
// Title: Barcode size unit toggle demonstration
-// Description: Shows how to generate barcodes with dimensions specified in pixels or millimeters, illustrating the core logic behind a UI toggle control.
-// Category-Description: This example belongs to the Aspose.BarCode image generation category, demonstrating the use of BarcodeGenerator, AutoSizeMode, and size unit properties (Pixels, Millimeters). Developers often need to switch measurement units for barcode rendering in UI applications, printing, or labeling scenarios. The snippet provides a reference for implementing unit toggles and instant preview updates.
+// Description: Shows how to generate barcodes using pixel and millimeter units, illustrating the logic behind a UI control that lets users switch units and see instant preview updates.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, focusing on size and measurement settings. It demonstrates using BarcodeGenerator, EncodeTypes, and the Parameters property to configure XDimension, ImageWidth, and ImageHeight in different units. Developers often need to switch between pixels and physical units like millimeters when creating barcodes for screen display versus print, making this a common scenario in UI-driven barcode design tools.
// Prompt: Design UI control allowing users to toggle between Pixels and Millimeters for barcode size, updating preview instantly.
-// Tags: barcode, size, unit, pixels, millimeters, generation, aspose.barcode, autosizemode, preview
+// Tags: barcode, size, unit, pixels, millimeters, generation, aspose.barcode, code128
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
///
-/// Demonstrates generating barcode images with size specified in pixels and millimeters.
+/// Demonstrates generating barcodes with size specified in pixels and millimeters.
///
class Program
{
///
- /// Entry point. Generates two barcode files using different size units and prints their paths.
+ /// Entry point. Generates two barcode images using different measurement units.
///
static void Main()
{
- // NOTE: The original request was for a UI control to toggle units.
- // The snippet runner does not support UI frameworks, so we demonstrate the core logic
- // by generating two barcode images: one sized in pixels and one sized in millimeters.
- // The images are saved to the current directory and their file names are printed.
-
- // Barcode content and symbology
- const string codeText = "1234567890";
- var encodeType = EncodeTypes.Code128;
-
- // ---------- Generate barcode with size specified in pixels ----------
- using (var generatorPixels = new BarcodeGenerator(encodeType))
+ // Define common barcode data and output file names
+ const string codeText = "123456";
+ const string outputPixels = "barcode_pixels.png";
+ const string outputMillimeters = "barcode_mm.png";
+
+ // ------------------------------------------------------------
+ // Generate barcode with size specified in Pixels
+ // ------------------------------------------------------------
+ using (var generatorPixels = new BarcodeGenerator(EncodeTypes.Code128, codeText))
{
- // Set the text to encode
- generatorPixels.CodeText = codeText;
-
- // Use interpolation mode to control exact image size
- generatorPixels.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
-
- // Set image size in pixels
- generatorPixels.Parameters.ImageWidth.Pixels = 300f; // 300 pixels width
- generatorPixels.Parameters.ImageHeight.Pixels = 150f; // 150 pixels height
+ // Set module (X) dimension in pixels
+ generatorPixels.Parameters.Barcode.XDimension.Pixels = 2f;
- // Optional: set background and bar colors
- generatorPixels.Parameters.BackColor = Color.White;
- generatorPixels.Parameters.Barcode.BarColor = Color.Black;
+ // Optionally set overall image dimensions in pixels
+ generatorPixels.Parameters.ImageWidth.Pixels = 300f;
+ generatorPixels.Parameters.ImageHeight.Pixels = 100f;
// Save the barcode image
- const string pixelFile = "barcode_pixels.png";
- generatorPixels.Save(pixelFile);
- Console.WriteLine($"Barcode saved with pixel dimensions: {pixelFile}");
+ generatorPixels.Save(outputPixels);
+ Console.WriteLine($"Barcode saved with pixel units: {outputPixels}");
}
- // ---------- Generate barcode with size specified in millimeters ----------
- using (var generatorMillimeters = new BarcodeGenerator(encodeType))
+ // ------------------------------------------------------------
+ // Generate barcode with size specified in Millimeters
+ // ------------------------------------------------------------
+ using (var generatorMm = new BarcodeGenerator(EncodeTypes.Code128, codeText))
{
- // Set the text to encode
- generatorMillimeters.CodeText = codeText;
+ // Set module (X) dimension in millimeters
+ generatorMm.Parameters.Barcode.XDimension.Millimeters = 0.5f;
- // Use interpolation mode to control exact image size
- generatorMillimeters.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
-
- // Set image size in millimeters
- generatorMillimeters.Parameters.ImageWidth.Millimeters = 80f; // 80 mm width
- generatorMillimeters.Parameters.ImageHeight.Millimeters = 40f; // 40 mm height
-
- // Optional: set background and bar colors
- generatorMillimeters.Parameters.BackColor = Color.White;
- generatorMillimeters.Parameters.Barcode.BarColor = Color.Black;
+ // Optionally set overall image dimensions in millimeters
+ generatorMm.Parameters.ImageWidth.Millimeters = 80f;
+ generatorMm.Parameters.ImageHeight.Millimeters = 30f;
// Save the barcode image
- const string mmFile = "barcode_millimeters.png";
- generatorMillimeters.Save(mmFile);
- Console.WriteLine($"Barcode saved with millimeter dimensions: {mmFile}");
+ generatorMm.Save(outputMillimeters);
+ Console.WriteLine($"Barcode saved with millimeter units: {outputMillimeters}");
}
-
- // End of demonstration
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/design-unit-test-verifying-barcodewidth-set-in-pixels-yields-correct-pixel-width-after-generation.cs b/barcode-size-and-resolution/design-unit-test-verifying-barcodewidth-set-in-pixels-yields-correct-pixel-width-after-generation.cs
index 7d1b7ff..b3addb7 100644
--- a/barcode-size-and-resolution/design-unit-test-verifying-barcodewidth-set-in-pixels-yields-correct-pixel-width-after-generation.cs
+++ b/barcode-size-and-resolution/design-unit-test-verifying-barcodewidth-set-in-pixels-yields-correct-pixel-width-after-generation.cs
@@ -1,58 +1,57 @@
-// Title: Verify barcode image width when setting BarCodeWidth in pixels
-// Description: Demonstrates how to set the barcode image width in pixels using Aspose.BarCode and validates the generated image matches the expected width.
-// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, AutoSizeMode, and ImageWidth properties to control output dimensions. Developers often need to produce barcodes with exact pixel sizes for UI layout or printing requirements; this snippet shows how to configure and verify those settings.
+// Title: Verify barcode pixel width using BarCodeWidth property
+// Description: Demonstrates setting the barcode image width in pixels and validates that the generated image matches the expected width.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to control barcode dimensions via the AutoSizeMode and ImageWidth properties. It uses BarcodeGenerator, EncodeTypes, and related parameter classes to produce barcodes of specific sizes, a common requirement for UI layout, printing, and automated testing scenarios.
// Prompt: Design unit test verifying BarCodeWidth set in Pixels yields correct pixel width after generation.
-// Tags: code128, barcode width, pixel, image generation, aspose.barcode, aspose.drawing, unit test
+// Tags: barcode, code128, imagewidth, pixels, autosize, unit-test, aspose.barcode, generation
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Entry point for the barcode width verification example.
+/// Example program that generates a Code128 barcode with a specific pixel width
+/// and validates that the resulting image matches the expected dimensions.
///
class Program
{
///
- /// Generates a Code128 barcode with a specified pixel width and validates the resulting image dimensions.
+ /// Entry point of the example. Sets up the barcode generator, defines the desired width,
+ /// creates the barcode image, verifies its width, and saves the result to a temporary file.
///
static void Main()
{
- // Expected barcode image width in pixels
- int expectedWidth = 300;
+ // Desired barcode image width in pixels
+ const int expectedWidth = 300;
- // Initialize a barcode generator for Code128 symbology
+ // Initialize a barcode generator for the Code128 symbology
using (var generator = new BarcodeGenerator(EncodeTypes.Code128))
{
- // Set the data to encode in the barcode
+ // Assign the text to be encoded in the barcode
generator.CodeText = "Test123";
- // Enable interpolation mode so the ImageWidth setting is applied accurately
+ // Configure the generator to use interpolation for sizing
generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- // Define the desired image width in pixels
+ // Set the target image width in pixels
generator.Parameters.ImageWidth.Pixels = expectedWidth;
// Generate the barcode image as a bitmap
- using (var bitmap = generator.GenerateBarCodeImage())
+ using (Bitmap bitmap = generator.GenerateBarCodeImage())
{
- // Capture the actual width of the generated bitmap
- int actualWidth = bitmap.Width;
-
- // Output expected and actual widths for diagnostic purposes
- Console.WriteLine($"Expected width: {expectedWidth} px");
- Console.WriteLine($"Actual width: {actualWidth} px");
-
- // Simple verification: compare actual width to expected width
- if (actualWidth == expectedWidth)
+ // Validate that the generated bitmap width matches the expected pixel width
+ if (bitmap.Width != expectedWidth)
{
- Console.WriteLine("Test passed: BarCodeWidth set in pixels yields correct image width.");
- }
- else
- {
- Console.WriteLine("Test failed: Image width does not match the expected value.");
+ throw new InvalidOperationException(
+ $"Barcode width mismatch. Expected: {expectedWidth}px, Actual: {bitmap.Width}px");
}
+
+ // Save the bitmap to a temporary PNG file for optional visual verification
+ string outputPath = Path.Combine(Path.GetTempPath(), "barcode_test.png");
+ bitmap.Save(outputPath, ImageFormat.Png);
+ Console.WriteLine($"Barcode generated successfully with width {bitmap.Width}px. Saved to {outputPath}");
}
}
}
diff --git a/barcode-size-and-resolution/develop-batch-job-reading-barcode-specs-from-xml-applying-unit-conversions-and-saving-pngs-to-directory.cs b/barcode-size-and-resolution/develop-batch-job-reading-barcode-specs-from-xml-applying-unit-conversions-and-saving-pngs-to-directory.cs
index 32dea43..c9c02df 100644
--- a/barcode-size-and-resolution/develop-batch-job-reading-barcode-specs-from-xml-applying-unit-conversions-and-saving-pngs-to-directory.cs
+++ b/barcode-size-and-resolution/develop-batch-job-reading-barcode-specs-from-xml-applying-unit-conversions-and-saving-pngs-to-directory.cs
@@ -1,166 +1,107 @@
-// Title: Batch barcode generation from XML specifications
-// Description: Demonstrates reading barcode definition XML files, converting dimensions from millimeters to points, and saving PNG images.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to import settings from XML, apply unit conversions, and produce barcode images. It uses BarcodeGenerator, its Parameters, and image saving APIs—common tasks for developers automating barcode creation in batch processes.
+// Title: Batch Barcode Generation from XML
+// Description: Demonstrates reading barcode specifications from an XML file, applying unit conversions, and saving PNG images.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator, EncodeTypes, and related parameter classes to create barcodes in bulk. Typical use cases include automated creation of product labels, inventory tags, or any scenario where barcode data is defined in external files. Developers often need to parse specifications, apply measurements, and export images in common formats.
// Prompt: Develop batch job reading barcode specs from XML, applying unit conversions, and saving PNGs to directory.
-// Tags: barcode generation, xml import, unit conversion, png output, aspose.barcode, batch processing
+// Tags: barcode symbology, batch processing, png output, aspose.barcode, xml parsing
using System;
using System.IO;
+using System.Xml.Linq;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
///
-/// Provides a console application that reads barcode specifications from XML files,
-/// converts measurement units, and generates PNG barcode images.
+/// Reads barcode specifications from an XML file, converts dimensions, and generates PNG images using Aspose.BarCode.
///
class Program
{
- // Conversion factor from millimeters to points (1 mm = 2.83465 points)
- private const float MmToPoint = 2.83465f;
-
///
- /// Entry point. Processes up to 10 XML specification files, converts units, and saves PNGs.
+ /// Entry point of the batch barcode generation example.
///
static void Main()
{
- // Input folder containing XML specifications
- string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "BarcodeSpecs");
- // Output folder for generated PNG images
- string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "GeneratedBarcodes");
+ // Path to the XML file containing barcode specifications.
+ const string xmlPath = "barcodespecs.xml";
- // Ensure input folder exists; if not, create and place a sample XML
- if (!Directory.Exists(inputFolder))
+ // Verify that the specification file exists before proceeding.
+ if (!File.Exists(xmlPath))
{
- Directory.CreateDirectory(inputFolder);
- // Sample XML (minimal) – in a real scenario replace with actual specs
- string sampleXml = Path.Combine(inputFolder, "SampleSpec.xml");
- File.WriteAllText(sampleXml,
-@"
- Sample123
- Code128
-
-
- 50
-
-
- 20
-
-
-
- 0.5
-
-
- 10
-
-
-
- 2
-
-
- 2
-
-
- 2
-
-
- 2
-
-
-
-
-");
+ Console.WriteLine($"Specification file not found: {xmlPath}");
+ return;
}
- // Ensure output folder exists
+ // Directory where generated PNG images will be saved.
+ const string outputFolder = "OutputBarcodes";
+
+ // Ensure the output directory exists.
if (!Directory.Exists(outputFolder))
{
Directory.CreateDirectory(outputFolder);
}
- // Process each XML file in the input folder (max 10 for safety)
- string[] xmlFiles = Directory.GetFiles(inputFolder, "*.xml");
- int processedCount = 0;
- foreach (string xmlPath in xmlFiles)
+ // Load the XML document containing barcode definitions.
+ XDocument doc;
+ using (FileStream fs = new FileStream(xmlPath, FileMode.Open, FileAccess.Read))
{
- if (processedCount >= 10) break; // safety cap
+ doc = XDocument.Load(fs);
+ }
- try
- {
- // Import barcode generator settings from XML
- using (BarcodeGenerator generator = BarcodeGenerator.ImportFromXml(xmlPath))
- {
- // Apply unit conversions from millimeters to points where applicable
- ConvertUnits(generator);
+ // Conversion factor: 1 millimeter = 2.83465 points (Aspose uses points for dimensions).
+ const float mmToPoints = 2.83465f;
- // Determine output file name (same as XML but with .png)
- string fileNameWithoutExt = Path.GetFileNameWithoutExtension(xmlPath);
- string outputPath = Path.Combine(outputFolder, fileNameWithoutExt + ".png");
+ int index = 0;
- // Save the barcode image as PNG
- generator.Save(outputPath, BarCodeImageFormat.Png);
- Console.WriteLine($"Generated barcode saved to: {outputPath}");
- }
- }
- catch (Exception ex)
+ // Iterate over each element in the XML.
+ foreach (XElement barcodeElem in doc.Root.Elements("Barcode"))
+ {
+ index++;
+
+ // Extract required and optional values from the XML.
+ string symbologyName = barcodeElem.Element("Symbology")?.Value?.Trim();
+ string codeText = barcodeElem.Element("CodeText")?.Value?.Trim() ?? string.Empty;
+ string xDimMmStr = barcodeElem.Element("XDimensionMm")?.Value?.Trim();
+
+ // Validate that a symbology name is provided.
+ if (string.IsNullOrEmpty(symbologyName))
{
- Console.WriteLine($"Error processing '{xmlPath}': {ex.Message}");
+ Console.WriteLine($"Barcode #{index}: Symbology name missing, skipping.");
+ continue;
}
- processedCount++;
- }
+ // Resolve the symbology name to an EncodeTypes field using reflection.
+ var fieldInfo = typeof(EncodeTypes).GetField(symbologyName);
+ if (fieldInfo == null)
+ {
+ Console.WriteLine($"Barcode #{index}: Unknown symbology '{symbologyName}', skipping.");
+ continue;
+ }
- // If no XML files were found, inform the user
- if (xmlFiles.Length == 0)
- {
- Console.WriteLine("No XML specification files found in the input folder.");
- }
- }
+ BaseEncodeType encodeType = (BaseEncodeType)fieldInfo.GetValue(null);
- // Converts relevant unit properties from millimeters to points
- private static void ConvertUnits(BarcodeGenerator generator)
- {
- // Image width
- if (generator.Parameters.ImageWidth.Millimeters > 0)
- {
- generator.Parameters.ImageWidth.Point = generator.Parameters.ImageWidth.Millimeters * MmToPoint;
- }
+ // Create a BarcodeGenerator instance with the resolved type and code text.
+ using (var generator = new BarcodeGenerator(encodeType, codeText))
+ {
+ // If an XDimension value (in mm) is provided, convert it to points and apply.
+ if (!string.IsNullOrEmpty(xDimMmStr) && float.TryParse(xDimMmStr, out float xDimMm))
+ {
+ float xDimPoints = xDimMm * mmToPoints;
+ generator.Parameters.Barcode.XDimension.Point = xDimPoints;
+ }
- // Image height
- if (generator.Parameters.ImageHeight.Millimeters > 0)
- {
- generator.Parameters.ImageHeight.Point = generator.Parameters.ImageHeight.Millimeters * MmToPoint;
- }
+ // Optional: set the barcode foreground color to black.
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
- // X dimension (module size)
- if (generator.Parameters.Barcode.XDimension.Millimeters > 0)
- {
- generator.Parameters.Barcode.XDimension.Point = generator.Parameters.Barcode.XDimension.Millimeters * MmToPoint;
- }
+ // Build the output file name and path.
+ string fileName = $"{symbologyName}_{index}.png";
+ string outPath = Path.Combine(outputFolder, fileName);
- // Bar height (for 1D barcodes)
- if (generator.Parameters.Barcode.BarHeight.Millimeters > 0)
- {
- generator.Parameters.Barcode.BarHeight.Point = generator.Parameters.Barcode.BarHeight.Millimeters * MmToPoint;
+ // Save the generated barcode as a PNG image.
+ generator.Save(outPath, BarCodeImageFormat.Png);
+ Console.WriteLine($"Barcode #{index} saved to: {outPath}");
+ }
}
- // Padding
- var padding = generator.Parameters.Barcode.Padding;
- if (padding.Left.Millimeters > 0)
- {
- padding.Left.Point = padding.Left.Millimeters * MmToPoint;
- }
- if (padding.Top.Millimeters > 0)
- {
- padding.Top.Point = padding.Top.Millimeters * MmToPoint;
- }
- if (padding.Right.Millimeters > 0)
- {
- padding.Right.Point = padding.Right.Millimeters * MmToPoint;
- }
- if (padding.Bottom.Millimeters > 0)
- {
- padding.Bottom.Point = padding.Bottom.Millimeters * MmToPoint;
- }
+ Console.WriteLine("Batch processing completed.");
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/develop-function-accepting-barcode-symbology-size-unit-and-resolution-returning-memory-stream-with-image.cs b/barcode-size-and-resolution/develop-function-accepting-barcode-symbology-size-unit-and-resolution-returning-memory-stream-with-image.cs
index f3859f7..82ff51e 100644
--- a/barcode-size-and-resolution/develop-function-accepting-barcode-symbology-size-unit-and-resolution-returning-memory-stream-with-image.cs
+++ b/barcode-size-and-resolution/develop-function-accepting-barcode-symbology-size-unit-and-resolution-returning-memory-stream-with-image.cs
@@ -1,31 +1,33 @@
-// Title: Generate barcode image with customizable symbology, size unit, and resolution
-// Description: Demonstrates creating a barcode using Aspose.BarCode, allowing callers to specify the symbology, measurement unit, and DPI, and returns the image as a MemoryStream.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use BarcodeGenerator, EncodeTypes, and image parameter settings (AutoSizeMode, ImageWidth/Height, Resolution) to produce PNG barcodes. Developers often need to dynamically create barcodes with specific dimensions and resolutions for printing or web display, and this snippet illustrates the typical workflow.
+// Title: Generate barcode image as PNG in memory stream
+// Description: Demonstrates creating a barcode with a specified symbology, size unit, and resolution, returning the image as a MemoryStream.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to use BarcodeGenerator, EncodeTypes, and image parameter settings to produce barcode graphics. Developers often need to generate barcodes on the fly for reports, PDFs, or web responses, and this snippet shows the typical workflow for configuring size, resolution, and output format.
// Prompt: Develop function accepting barcode symbology, size unit, and resolution, returning memory stream with image.
-// Tags: barcode, symbology, generation, png, memorystream, aspnet, aspnetcore, aspose.barcode, encode types, resolution, size unit
+// Tags: barcode, symbology, image generation, memory stream, aspose.barcode, png, resolution, size unit
using System;
using System.IO;
-using System.Reflection;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Example program demonstrating barcode generation with customizable parameters.
+/// Provides an example of generating a barcode image in memory using Aspose.BarCode.
///
class Program
{
///
- /// Entry point that calls and displays the resulting stream size.
+ /// Entry point of the example. Demonstrates calling and reports the resulting stream size.
///
static void Main()
{
- // Sample call to the barcode generation function
+ // Example usage of the GenerateBarcode function
using (MemoryStream stream = GenerateBarcode("Code128", "Point", 300f))
{
- // Output the size of the generated PNG image
+ // Output the size of the generated PNG image (in bytes)
Console.WriteLine($"Generated barcode image size: {stream.Length} bytes");
- // The stream contains the PNG image; in a real scenario you could write it to a file:
+
+ // The stream contains a PNG image; you could write it to a file for verification:
// File.WriteAllBytes("barcode.png", stream.ToArray());
}
}
@@ -33,65 +35,56 @@ static void Main()
///
/// Generates a barcode image and returns it as a .
///
- /// Name of the barcode symbology (e.g., "Code128").
- /// Unit for image dimensions: "Point", "Pixels", "Inches", or "Millimeters".
+ /// Name of the barcode symbology (e.g., "Code128", "QR").
+ /// Unit for image dimensions: "Point", "Pixels", or "Millimeters".
/// Resolution (dpi) for the generated image.
/// MemoryStream containing the PNG image.
static MemoryStream GenerateBarcode(string symbologyName, string sizeUnit, float resolution)
{
- // Validate symbology name input
- if (string.IsNullOrWhiteSpace(symbologyName))
- throw new ArgumentException("Symbology name must be provided.", nameof(symbologyName));
-
// Resolve the symbology name to a BaseEncodeType using reflection
- FieldInfo field = typeof(EncodeTypes).GetField(symbologyName, BindingFlags.Public | BindingFlags.Static);
+ var field = typeof(EncodeTypes).GetField(symbologyName);
if (field == null)
- throw new ArgumentException($"Unknown symbology: {symbologyName}", nameof(symbologyName));
+ throw new ArgumentException($"Unknown symbology: {symbologyName}");
BaseEncodeType encodeType = (BaseEncodeType)field.GetValue(null);
- // Create the barcode generator with the resolved encode type
- using (var generator = new BarcodeGenerator(encodeType))
- {
- // Set sample codetext; adjust as needed for specific symbologies
- generator.CodeText = "Sample123";
-
- // Use interpolation mode to control image size via ImageWidth/ImageHeight
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ // Create the barcode generator with the resolved symbology
+ var generator = new BarcodeGenerator(encodeType);
+ generator.CodeText = "Sample123";
- // Define a constant dimension value (example size)
- const float dimensionValue = 200f;
+ // Set the desired image resolution (dpi)
+ generator.Parameters.Resolution = resolution;
- // Set image dimensions based on the requested unit
- switch (sizeUnit?.Trim().ToLowerInvariant())
- {
- case "point":
- generator.Parameters.ImageWidth.Point = dimensionValue;
- generator.Parameters.ImageHeight.Point = dimensionValue;
- break;
- case "pixels":
- generator.Parameters.ImageWidth.Pixels = dimensionValue;
- generator.Parameters.ImageHeight.Pixels = dimensionValue;
- break;
- case "inches":
- generator.Parameters.ImageWidth.Inches = dimensionValue;
- generator.Parameters.ImageHeight.Inches = dimensionValue;
- break;
- case "millimeters":
- generator.Parameters.ImageWidth.Millimeters = dimensionValue;
- generator.Parameters.ImageHeight.Millimeters = dimensionValue;
- break;
- default:
- throw new ArgumentException($"Unsupported size unit: {sizeUnit}", nameof(sizeUnit));
- }
+ // Configure image size using the specified unit (example dimensions: 200 x 100)
+ switch (sizeUnit?.Trim().ToLowerInvariant())
+ {
+ case "point":
+ generator.Parameters.ImageWidth.Point = 200f;
+ generator.Parameters.ImageHeight.Point = 100f;
+ break;
+ case "pixel":
+ case "pixels":
+ generator.Parameters.ImageWidth.Pixels = 200f;
+ generator.Parameters.ImageHeight.Pixels = 100f;
+ break;
+ case "millimeter":
+ case "millimeters":
+ generator.Parameters.ImageWidth.Millimeters = 50f; // approx 200 points
+ generator.Parameters.ImageHeight.Millimeters = 25f; // approx 100 points
+ break;
+ default:
+ throw new ArgumentException($"Unsupported size unit: {sizeUnit}");
+ }
- // Apply the requested resolution (dpi)
- generator.Parameters.Resolution = resolution;
+ // Disable automatic sizing so the explicit dimensions are used
+ generator.Parameters.AutoSizeMode = AutoSizeMode.None;
- // Save the barcode to a memory stream in PNG format
+ // Generate the barcode image and save it to a memory stream in PNG format
+ using (Bitmap bitmap = generator.GenerateBarCodeImage())
+ {
var ms = new MemoryStream();
- generator.Save(ms, BarCodeImageFormat.Png);
- ms.Position = 0; // Reset stream position for reading
+ bitmap.Save(ms, ImageFormat.Png);
+ ms.Position = 0; // Reset stream position for downstream consumers
return ms;
}
}
diff --git a/barcode-size-and-resolution/develop-function-accepting-size-value-and-unit-enum-applying-to-barcodewidth-and-returning-pixel-width.cs b/barcode-size-and-resolution/develop-function-accepting-size-value-and-unit-enum-applying-to-barcodewidth-and-returning-pixel-width.cs
index 8ba8bd5..ae5a6ec 100644
--- a/barcode-size-and-resolution/develop-function-accepting-size-value-and-unit-enum-applying-to-barcodewidth-and-returning-pixel-width.cs
+++ b/barcode-size-and-resolution/develop-function-accepting-size-value-and-unit-enum-applying-to-barcodewidth-and-returning-pixel-width.cs
@@ -1,8 +1,8 @@
-// Title: Barcode width conversion example
-// Description: Demonstrates how to set barcode image width using different measurement units and retrieve the resulting pixel width.
-// Category-Description: This example belongs to the Aspose.BarCode image sizing category, illustrating the use of BarcodeGenerator, ImageWidth, and unit conversion properties. Developers often need to define barcode dimensions in pixels, inches, millimeters, or points to fit layout requirements, and this snippet shows the typical approach for such operations.
+// Title: Barcode Width Conversion Example
+// Description: Demonstrates how to set a barcode image width using different measurement units and retrieve the resulting pixel width.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, AutoSizeMode, and ImageWidth properties. Developers often need to control barcode dimensions in various units (pixels, inches, millimeters, points) for printing, UI layout, or export scenarios. The snippet shows typical unit conversion and pixel retrieval, a common requirement when integrating barcodes into graphics pipelines.
// Prompt: Develop function accepting size value and unit enum, applying to BarCodeWidth and returning pixel width.
-// Tags: barcode, width, unit conversion, image sizing, aspnet, aspose.barcode, code128
+// Tags: barcode, width, unit conversion, code128, aspose.barcode, imagewidth, pixel, generation
using System;
using Aspose.BarCode;
@@ -11,75 +11,81 @@
namespace BarcodeWidthExample
{
// Supported units for setting barcode width
- enum WidthUnit
+ enum SizeUnit
{
Pixels,
Inches,
Millimeters,
- Points
+ Point
}
///
- /// Demonstrates setting barcode width using various units and retrieving pixel width.
+ /// Contains methods that demonstrate setting barcode width in various units
+ /// and obtaining the equivalent pixel width using Aspose.BarCode.
///
class Program
{
///
- /// Sets the barcode image width according to the supplied size and unit,
+ /// Sets the barcode image width according to the provided value and unit,
/// then returns the calculated width in pixels.
///
- /// The numeric size value.
- /// The measurement unit for the size.
- /// Width of the barcode image in whole pixels.
- static int SetBarcodeWidth(float size, WidthUnit unit)
+ /// Numeric size value.
+ /// Unit of measurement for the size.
+ /// Width of the barcode image in pixels.
+ static int GetBarCodePixelWidth(float sizeValue, SizeUnit unit)
{
// Use Code128 as a simple symbology for the example
using (var generator = new BarcodeGenerator(EncodeTypes.Code128))
{
- // Assign the width based on the selected unit
+ // Enable interpolation mode so ImageWidth controls the output size
+ generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+
+ // Apply the size to the ImageWidth property using the selected unit
switch (unit)
{
- case WidthUnit.Pixels:
- generator.Parameters.ImageWidth.Pixels = size;
+ case SizeUnit.Pixels:
+ generator.Parameters.ImageWidth.Pixels = sizeValue;
break;
- case WidthUnit.Inches:
- generator.Parameters.ImageWidth.Inches = size;
+ case SizeUnit.Inches:
+ generator.Parameters.ImageWidth.Inches = sizeValue;
break;
- case WidthUnit.Millimeters:
- generator.Parameters.ImageWidth.Millimeters = size;
+ case SizeUnit.Millimeters:
+ generator.Parameters.ImageWidth.Millimeters = sizeValue;
break;
- case WidthUnit.Points:
- generator.Parameters.ImageWidth.Point = size;
+ case SizeUnit.Point:
+ generator.Parameters.ImageWidth.Point = sizeValue;
break;
default:
- throw new ArgumentOutOfRangeException(nameof(unit), "Unsupported width unit.");
+ throw new ArgumentException("Unsupported size unit.", nameof(unit));
}
- // Return the width expressed in pixels (rounded down to integer)
+ // The ImageWidth property now holds the value in all units.
+ // Return the pixel representation.
return (int)generator.Parameters.ImageWidth.Pixels;
}
}
///
- /// Entry point demonstrating SetBarcodeWidth with different units.
+ /// Entry point of the example. Calls with
+ /// different units and writes the resulting pixel widths to the console.
///
static void Main()
{
- // Example usage: width specified in pixels
- int widthPx1 = SetBarcodeWidth(200f, WidthUnit.Pixels);
- Console.WriteLine($"Width set to 200 pixels => {widthPx1} pixels");
+ // Example usage with pixel unit
+ int widthPx = GetBarCodePixelWidth(200f, SizeUnit.Pixels);
+ Console.WriteLine($"Width set to 200 pixels => {widthPx} pixels");
- // Example usage: width specified in inches
- int widthPx2 = SetBarcodeWidth(2.5f, WidthUnit.Inches);
- Console.WriteLine($"Width set to 2.5 inches => {widthPx2} pixels");
+ // Example usage with inches unit
+ int widthInches = GetBarCodePixelWidth(2f, SizeUnit.Inches);
+ Console.WriteLine($"Width set to 2 inches => {widthInches} pixels");
- // Example usage: width specified in millimeters
- int widthPx3 = SetBarcodeWidth(50f, WidthUnit.Millimeters);
- Console.WriteLine($"Width set to 50 millimeters => {widthPx3} pixels");
+ // Example usage with millimeters unit
+ int widthMm = GetBarCodePixelWidth(50f, SizeUnit.Millimeters);
+ Console.WriteLine($"Width set to 50 mm => {widthMm} pixels");
- // Example usage: width specified in points
- int widthPx4 = SetBarcodeWidth(72f, WidthUnit.Points);
- Console.WriteLine($"Width set to 72 points => {widthPx4} pixels");
+ // Example usage with point unit
+ int widthPt = GetBarCodePixelWidth(72f, SizeUnit.Point);
+ Console.WriteLine($"Width set to 72 points => {widthPt} pixels");
}
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/develop-logging-mechanism-recording-configured-measurement-unit-dimensions-and-dpi-for-each-generated-barcode-image.cs b/barcode-size-and-resolution/develop-logging-mechanism-recording-configured-measurement-unit-dimensions-and-dpi-for-each-generated-barcode-image.cs
index a9015c2..19e139f 100644
--- a/barcode-size-and-resolution/develop-logging-mechanism-recording-configured-measurement-unit-dimensions-and-dpi-for-each-generated-barcode-image.cs
+++ b/barcode-size-and-resolution/develop-logging-mechanism-recording-configured-measurement-unit-dimensions-and-dpi-for-each-generated-barcode-image.cs
@@ -1,8 +1,8 @@
-// Title: Barcode generation with logging of measurement unit, dimensions, and DPI
-// Description: Demonstrates creating barcodes with specific size settings and logs the configured unit, dimensions, and resolution for each image.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator, AutoSizeMode, and resolution settings. Developers often need to control image size, measurement units, and DPI when generating barcodes for print or digital media; this snippet shows typical configuration and logging patterns for such scenarios.
+// Title: Barcode generation with logging of measurement units, dimensions, and DPI
+// Description: Demonstrates creating Code128 and QR barcodes while logging their configured measurement unit, image dimensions, and resolution (DPI) to a text file.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to configure barcode parameters such as XDimension, image size, and resolution using the BarcodeGenerator class. Typical use cases include generating barcodes for product labeling, inventory systems, and marketing materials where precise sizing and DPI settings are required. Developers often need to record these settings for compliance, debugging, or documentation purposes.
// Prompt: Develop logging mechanism recording configured measurement unit, dimensions, and DPI for each generated barcode image.
-// Tags: barcode generation, logging, measurement unit, dimensions, dpi, aspose.barcode, encode types, png output
+// Tags: barcode, code128, qr, generation, logging, dimensions, resolution, aspose.barcode
using System;
using System.IO;
@@ -10,80 +10,78 @@
using Aspose.BarCode.Generation;
///
-/// Example program that generates barcodes with specific size and resolution settings,
-/// then logs the configuration details for each generated image.
+/// Generates barcodes (Code128 and QR) and logs their configuration settings such as measurement unit, dimensions, and DPI.
///
class Program
{
///
- /// Entry point of the application. Iterates over predefined barcode configurations,
- /// creates each barcode, saves it as a PNG file, and records its settings.
+ /// Entry point of the application. Creates barcode images and records their settings to a log file.
///
static void Main()
{
- // Define a simple list of barcode configurations to process
- var configs = new[]
- {
- new { Type = EncodeTypes.Code128, Text = "ABC123", Width = 300f, Height = 150f, XDim = 2f, BarH = 40f, Dpi = 300f, Unit = "Point" },
- new { Type = EncodeTypes.QR, Text = "https://example.com", Width = 200f, Height = 200f, XDim = 3f, BarH = 0f, Dpi = 200f, Unit = "Point" }
- };
+ // Define the path for the log file and ensure it starts empty.
+ string logPath = "barcode_log.txt";
+ File.WriteAllText(logPath, string.Empty);
- // Process each configuration
- foreach (var cfg in configs)
+ // -------------------- Generate Code128 barcode --------------------
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123ABC"))
{
- // Create and configure the barcode generator for the current settings
- using (var generator = new BarcodeGenerator(cfg.Type, cfg.Text))
- {
- // Use interpolation mode so ImageWidth/ImageHeight control the final size
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ // Configure measurement unit (points) and size parameters.
+ generator.Parameters.Barcode.XDimension.Point = 2f;
+ generator.Parameters.ImageWidth.Point = 300f;
+ generator.Parameters.ImageHeight.Point = 150f;
+ generator.Parameters.Barcode.BarHeight.Point = 40f;
+ generator.Parameters.Resolution = 300f; // DPI
- // Apply dimensions using the chosen measurement unit (Point in this example)
- generator.Parameters.ImageWidth.Point = cfg.Width;
- generator.Parameters.ImageHeight.Point = cfg.Height;
- generator.Parameters.Barcode.XDimension.Point = cfg.XDim;
+ // Save the barcode image to a file.
+ string outputPath = "code128.png";
+ generator.Save(outputPath);
- // BarHeight is ignored in Interpolation mode, but set it when a positive value is provided
- if (cfg.BarH > 0f)
- {
- generator.Parameters.Barcode.BarHeight.Point = cfg.BarH;
- }
+ // Log the configured settings for this barcode.
+ LogSettings(generator, "Code128", outputPath, logPath);
+ }
- // Set the image resolution (dots per inch)
- generator.Parameters.Resolution = cfg.Dpi;
+ // -------------------- Generate QR barcode --------------------
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"))
+ {
+ // Configure measurement unit (points) and size parameters.
+ generator.Parameters.Barcode.XDimension.Point = 3f;
+ generator.Parameters.ImageWidth.Point = 250f;
+ generator.Parameters.ImageHeight.Point = 250f;
+ generator.Parameters.Resolution = 200f; // DPI
- // Generate a unique file name and save the barcode image as PNG
- string fileName = $"{cfg.Type}_{Guid.NewGuid()}.png";
- generator.Save(fileName);
+ // Save the barcode image to a file.
+ string outputPath = "qr.png";
+ generator.Save(outputPath);
- // Log the configuration details for the generated image
- LogBarcodeSettings(fileName, cfg.Unit, cfg.Width, cfg.Height, cfg.XDim, cfg.BarH, cfg.Dpi);
- }
+ // Log the configured settings for this barcode.
+ LogSettings(generator, "QR", outputPath, logPath);
}
+
+ // Inform the user that generation is complete and where the log can be found.
+ Console.WriteLine("Barcode generation completed. Log written to " + Path.GetFullPath(logPath));
}
///
- /// Writes a log entry containing the barcode image name, measurement unit, dimensions, X-dimension,
- /// bar height, and DPI to both the console and a persistent text file.
+ /// Appends a formatted entry to the log file containing the barcode type, image path, and configured parameters.
///
- /// Full path of the generated barcode image.
- /// Measurement unit used for dimensions (e.g., Point).
- /// Configured image width.
- /// Configured image height.
- /// Configured X-dimension of barcode modules.
- /// Configured bar height (if applicable).
- /// Configured image resolution in dots per inch.
- static void LogBarcodeSettings(string imagePath, string unit, float width, float height, float xDim, float barHeight, float dpi)
+ /// The BarcodeGenerator instance containing the current settings.
+ /// A friendly name for the barcode symbology.
+ /// The file path where the barcode image was saved.
+ /// The file path of the log file to append to.
+ static void LogSettings(BarcodeGenerator generator, string barcodeType, string imagePath, string logPath)
{
- // Build a formatted log entry string
- string logEntry = $"Image: {Path.GetFileName(imagePath)} | Unit: {unit} | Width: {width}{unit} | Height: {height}{unit} | XDimension: {xDim}{unit} | BarHeight: {barHeight}{unit} | DPI: {dpi}";
+ // Build a multi-line log entry with all relevant settings.
+ string entry = $"Barcode Type: {barcodeType}{Environment.NewLine}" +
+ $"Image File: {imagePath}{Environment.NewLine}" +
+ $"Resolution (DPI): {generator.Parameters.Resolution}{Environment.NewLine}" +
+ $"XDimension: {generator.Parameters.Barcode.XDimension.Point} pt{Environment.NewLine}" +
+ $"Image Width: {generator.Parameters.ImageWidth.Point} pt{Environment.NewLine}" +
+ $"Image Height: {generator.Parameters.ImageHeight.Point} pt{Environment.NewLine}" +
+ $"Bar Height: {generator.Parameters.Barcode.BarHeight.Point} pt{Environment.NewLine}" +
+ $"---{Environment.NewLine}";
- // Output the log entry to the console for immediate visibility
- Console.WriteLine(logEntry);
-
- // Append the log entry to a persistent log file
- using (var writer = new StreamWriter("barcode_log.txt", true))
- {
- writer.WriteLine(logEntry);
- }
+ // Append the entry to the log file.
+ File.AppendAllText(logPath, entry);
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/generate-barcode-image-then-resize-bitmap-to-double-pixel-dimensions-while-preserving-original-dpi.cs b/barcode-size-and-resolution/generate-barcode-image-then-resize-bitmap-to-double-pixel-dimensions-while-preserving-original-dpi.cs
index 0fab3d5..1a8bf56 100644
--- a/barcode-size-and-resolution/generate-barcode-image-then-resize-bitmap-to-double-pixel-dimensions-while-preserving-original-dpi.cs
+++ b/barcode-size-and-resolution/generate-barcode-image-then-resize-bitmap-to-double-pixel-dimensions-while-preserving-original-dpi.cs
@@ -1,63 +1,70 @@
-// Title: Generate and Resize Barcode Image
-// Description: Creates a Code128 barcode, saves the original image, then doubles its pixel dimensions while preserving the original DPI.
-// Category-Description: This example belongs to the Aspose.BarCode generation and Aspose.Drawing image manipulation category. It demonstrates how to use BarcodeGenerator to produce a barcode, then employs Aspose.Drawing's Bitmap and Graphics classes to resize the image. Developers often need to adjust barcode image sizes for printing or UI display while maintaining DPI for accurate physical dimensions.
+// Title: Generate and resize a barcode image while preserving DPI
+// Description: This example creates a Code128 barcode, saves it, then doubles its pixel dimensions without altering the original DPI.
+// Category-Description: Demonstrates Aspose.BarCode image generation and manipulation using Aspose.Drawing. It covers barcode generation (BarcodeGenerator), bitmap handling (Bitmap), and DPI preservation—common tasks for developers needing high‑resolution barcode graphics for printing or UI scaling. Suitable for searches about barcode image resizing with Aspose.
// Prompt: Generate barcode image, then resize bitmap to double pixel dimensions while preserving original DPI.
-// Tags: barcode, code128, resize, bitmap, dpi, aspose.barcode, aspose.drawing, png
+// Tags: barcode, code128, image-resize, dpi-preservation, aspose.barcode, aspose.drawing, png
using System;
+using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
using Aspose.Drawing.Imaging;
-using Aspose.Drawing.Drawing2D;
-namespace BarcodeResizeDemo
+///
+/// Example program that generates a Code128 barcode, saves the original image,
+/// then creates a resized version with double the pixel dimensions while keeping the original DPI.
+///
+class Program
{
///
- /// Demonstrates generating a barcode image and resizing it while preserving DPI.
+ /// Entry point of the example. Performs barcode generation, saves the original image,
+ /// resizes it, and saves the resized version.
///
- class Program
+ static void Main()
{
- ///
- /// Entry point of the demo. Generates a Code128 barcode, saves the original,
- /// creates a double‑size bitmap, and saves the resized image.
- ///
- static void Main()
+ // Define file paths for the original and resized barcode images.
+ string originalPath = Path.Combine(Directory.GetCurrentDirectory(), "barcode_original.png");
+ string resizedPath = Path.Combine(Directory.GetCurrentDirectory(), "barcode_resized.png");
+
+ // Initialize a barcode generator for Code128 with sample text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Initialize a barcode generator for Code128 with sample text "123456"
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ // Configure image size using interpolation mode for smoother scaling.
+ generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ generator.Parameters.ImageWidth.Point = 200f;
+ generator.Parameters.ImageHeight.Point = 100f;
+
+ // Generate the barcode image as a bitmap.
+ using (Bitmap originalBitmap = generator.GenerateBarCodeImage())
{
- // Generate the barcode as a Bitmap object
- using (Bitmap original = generator.GenerateBarCodeImage())
- {
- // Store the original DPI values to apply them later
- float dpiX = original.HorizontalResolution;
- float dpiY = original.VerticalResolution;
+ // Save the original bitmap to PNG.
+ originalBitmap.Save(originalPath, ImageFormat.Png);
- // Compute new dimensions: double the width and height in pixels
- int newWidth = original.Width * 2;
- int newHeight = original.Height * 2;
+ // Compute new dimensions: double the width and height in pixels.
+ int newWidth = originalBitmap.Width * 2;
+ int newHeight = originalBitmap.Height * 2;
- // Create a new bitmap with the doubled size and the same pixel format as the original
- using (Bitmap resized = new Bitmap(newWidth, newHeight, original.PixelFormat))
+ // Create a new bitmap with the doubled dimensions.
+ using (Bitmap resizedBitmap = new Bitmap(newWidth, newHeight))
+ {
+ // Preserve the original DPI (resolution) on the new bitmap.
+ resizedBitmap.SetResolution(originalBitmap.HorizontalResolution, originalBitmap.VerticalResolution);
+
+ // Draw the original image onto the new bitmap, scaling it to the new size.
+ using (Graphics graphics = Graphics.FromImage(resizedBitmap))
{
- // Apply the original DPI to the resized bitmap to keep physical size consistent
- resized.SetResolution(dpiX, dpiY);
-
- // Use a Graphics object to draw the original image onto the resized bitmap with high‑quality scaling
- using (Graphics graphics = Graphics.FromImage(resized))
- {
- graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
- graphics.DrawImage(original, new Rectangle(0, 0, newWidth, newHeight));
- }
-
- // Save the resized bitmap as a PNG file
- resized.Save("resized.png", ImageFormat.Png);
+ graphics.DrawImage(originalBitmap, 0, 0, newWidth, newHeight);
}
- // Optionally, save the original barcode image for comparison
- original.Save("original.png", ImageFormat.Png);
+ // Save the resized bitmap to PNG.
+ resizedBitmap.Save(resizedPath, ImageFormat.Png);
}
}
}
+
+ // Output the locations of the saved images.
+ Console.WriteLine($"Original barcode saved to: {originalPath}");
+ Console.WriteLine($"Resized barcode saved to: {resizedPath}");
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/generate-barcode-with-barcodeheight-zero-to-enable-auto-size-based-on-content-using-default-units.cs b/barcode-size-and-resolution/generate-barcode-with-barcodeheight-zero-to-enable-auto-size-based-on-content-using-default-units.cs
index 8bcc856..4d27a69 100644
--- a/barcode-size-and-resolution/generate-barcode-with-barcodeheight-zero-to-enable-auto-size-based-on-content-using-default-units.cs
+++ b/barcode-size-and-resolution/generate-barcode-with-barcodeheight-zero-to-enable-auto-size-based-on-content-using-default-units.cs
@@ -1,38 +1,38 @@
-// Title: Generate barcode with auto‑sized height using Aspose.BarCode
-// Description: Demonstrates how to create a Code128 barcode where the bar height is automatically determined from the content by setting BarCodeHeight to zero (auto‑size mode). The barcode is saved as a PNG image.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on auto‑sizing and layout configuration. It showcases the use of BarcodeGenerator, EncodeTypes, and AutoSizeMode to let the library calculate optimal dimensions based on the encoded data. Developers often need to generate barcodes that adapt to varying content lengths without manually specifying size parameters, especially for dynamic reporting or label printing scenarios.
+// Title: Generate Code128 barcode with auto‑sized height
+// Description: Demonstrates creating a Code128 barcode where BarCodeHeight is set to zero, allowing the library to auto‑size the height based on the encoded content.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating the use of AutoSizeMode to let the engine determine optimal dimensions. It showcases key classes such as BarcodeGenerator, EncodeTypes, and AutoSizeMode, which developers commonly use when they need dynamic barcode sizing for various output formats like PNG, JPEG, or PDF.
// Prompt: Generate barcode with BarCodeHeight zero to enable auto‑size based on content, using default units.
-// Tags: code128, autosize, barcodeheight, png, aspnet, aspose.barcode, generation
+// Tags: code128, barcode generation, autosize, png, aspose.barcode, csharp
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-///
-/// Example program that generates a Code128 barcode with automatic height sizing.
-///
-class Program
+namespace BarcodeExample
{
///
- /// Entry point of the application. Creates a barcode, enables auto‑size mode, and saves it as a PNG file.
+ /// Provides an entry point that generates a Code128 barcode image with automatic height sizing.
///
- static void Main()
+ class Program
{
- // Initialize a barcode generator for Code128 with the sample text "Sample123".
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ ///
+ /// Generates a barcode, saves it as a PNG file, and writes the output path to the console.
+ ///
+ static void Main()
{
- // Set the auto‑size mode to Interpolation.
- // In this mode the BarCodeHeight property is ignored, allowing the library to determine the optimal height.
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ // Initialize a BarcodeGenerator for Code128 with the sample text "Sample123".
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ {
+ // Enable auto‑size mode so the library determines the optimal barcode height.
+ // Setting BarCodeHeight to zero is implicit; no explicit height assignment is needed.
+ generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- // Define the output file path.
- const string outputPath = "barcode.png";
+ // Save the generated barcode image to a PNG file named "barcode.png".
+ generator.Save("barcode.png");
+ }
- // Save the generated barcode image to the specified path.
- generator.Save(outputPath);
-
- // Inform the user that the barcode has been saved.
- Console.WriteLine($"Barcode saved to {outputPath}");
+ // Inform the user that the barcode image has been created.
+ Console.WriteLine("Barcode generated: barcode.png");
}
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/implement-batch-processing-to-generate-100-barcodes-with-varying-millimeter-xdimension-values-storing-each-as-tiff.cs b/barcode-size-and-resolution/implement-batch-processing-to-generate-100-barcodes-with-varying-millimeter-xdimension-values-storing-each-as-tiff.cs
index cdd17cc..0f69a6e 100644
--- a/barcode-size-and-resolution/implement-batch-processing-to-generate-100-barcodes-with-varying-millimeter-xdimension-values-storing-each-as-tiff.cs
+++ b/barcode-size-and-resolution/implement-batch-processing-to-generate-100-barcodes-with-varying-millimeter-xdimension-values-storing-each-as-tiff.cs
@@ -1,62 +1,60 @@
-// Title: Batch Generation of Code128 Barcodes with Varying XDimension Saved as TIFF
-// Description: Demonstrates creating 100 Code128 barcodes, each with a different XDimension measured in millimeters, and saving them as TIFF images.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to use the BarcodeGenerator class to produce multiple barcodes in a batch. Typical use cases include bulk creation of product labels, inventory tags, or QR codes where each item requires a unique size or dimension. Developers often need to adjust parameters like XDimension, image format, and auto‑size mode while iterating over large datasets.
+// Title: Batch generation of 100 Code128 barcodes with varying XDimension saved as TIFF
+// Description: Generates 100 Code128 barcodes, each with a unique XDimension value in millimeters, and saves them as TIFF images.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, demonstrating how to configure barcode dimensions (XDimension) and perform batch processing. It showcases the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes to create high‑resolution TIFF outputs—common tasks for developers needing bulk barcode creation for labeling, inventory, or printing workflows.
// Prompt: Implement batch processing to generate 100 barcodes with varying Millimeter XDimension values, storing each as TIFF.
-// Tags: code128, barcode, batch-processing, tiff, xdimension, generation, aspose.barcode
+// Tags: code128, generation, tiff, xdimension, aspose.barcode, aspose.drawing, batch-processing
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Generates a batch of Code128 barcodes with incrementally changing XDimension values
-/// and saves each barcode as a TIFF image.
+/// Demonstrates batch creation of 100 Code128 barcodes with incremental XDimension values,
+/// saving each barcode as a TIFF image using Aspose.BarCode.
///
class Program
{
///
- /// Entry point of the example. Creates 100 barcode images with varying XDimension
- /// measured in millimeters and stores them in a dedicated output folder.
+ /// Entry point of the example. Generates the barcode images and writes the output folder path to the console.
///
static void Main()
{
- // Define the output folder for generated barcode images
- string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ // Define the output directory for generated barcode images.
+ string outputDir = "Barcodes";
- // Ensure the output directory exists
- if (!Directory.Exists(outputFolder))
+ // Ensure the output directory exists.
+ if (!Directory.Exists(outputDir))
{
- Directory.CreateDirectory(outputFolder);
+ Directory.CreateDirectory(outputDir);
}
- // Number of barcodes to generate (batch size)
- int sampleCount = 100; // change to desired batch size
-
- // Loop through the batch, creating each barcode with a unique XDimension
- for (int i = 1; i <= sampleCount; i++)
+ // Loop to generate 100 barcodes with incremental XDimension (0.1 mm steps).
+ for (int i = 1; i <= 100; i++)
{
- // Initialize a new BarcodeGenerator for Code128 symbology
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128))
- {
- // Set the text to encode (e.g., Sample001, Sample002, ...)
- generator.CodeText = $"Sample{i:D3}";
+ // Create a unique code text for each barcode (e.g., CODE001, CODE002, ...).
+ string codeText = $"CODE{i:D3}";
- // Vary XDimension in millimeters (0.5mm increments per barcode)
- generator.Parameters.Barcode.XDimension.Millimeters = i * 0.5f;
+ // Initialize the barcode generator for Code128 symbology.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ {
+ // Set the XDimension in millimeters (0.1 mm, 0.2 mm, ..., 10.0 mm).
+ float xDimensionMm = i * 0.1f;
+ generator.Parameters.Barcode.XDimension.Millimeters = xDimensionMm;
- // Use interpolation mode to automatically adjust image size if needed
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ // Optional: increase resolution for higher quality output (300 DPI).
+ generator.Parameters.Resolution = 300;
- // Construct the full file path for the TIFF image
- string filePath = Path.Combine(outputFolder, $"barcode_{i:D3}.tiff");
+ // Build the full file path for the TIFF image.
+ string filePath = Path.Combine(outputDir, $"barcode_{i:D3}.tiff");
- // Save the generated barcode as a TIFF file
+ // Save the generated barcode as a TIFF file.
generator.Save(filePath, BarCodeImageFormat.Tiff);
}
}
- // Output completion message to the console
- Console.WriteLine($"Generated {sampleCount} barcode images in '{outputFolder}'.");
+ // Inform the user where the barcode images have been saved.
+ Console.WriteLine($"Generated 100 barcode images in: {Path.GetFullPath(outputDir)}");
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/implement-error-handling-for-unsupported-unit-values-when-setting-barcodewidth-throwing-descriptive-exception.cs b/barcode-size-and-resolution/implement-error-handling-for-unsupported-unit-values-when-setting-barcodewidth-throwing-descriptive-exception.cs
index 9dc8d88..343998d 100644
--- a/barcode-size-and-resolution/implement-error-handling-for-unsupported-unit-values-when-setting-barcodewidth-throwing-descriptive-exception.cs
+++ b/barcode-size-and-resolution/implement-error-handling-for-unsupported-unit-values-when-setting-barcodewidth-throwing-descriptive-exception.cs
@@ -1,73 +1,76 @@
-// Title: Barcode width validation with error handling
-// Description: Demonstrates setting barcode width using Aspose.BarCode while validating input and handling unsupported values.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode dimensions using the BarcodeGenerator class. It covers AutoSizeMode, ImageWidth, and error handling for invalid width values, which developers commonly need when creating barcodes for print or digital media.
+// Title: Set barcode image width with validation
+// Description: Demonstrates setting the barcode image width using Aspose.BarCode and validates the width value.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure image dimensions via the AutoSizeMode and ImageWidth properties. It shows typical usage of BarcodeGenerator, Parameters, and AutoSizeMode classes for developers needing precise control over barcode size in generated images.
// Prompt: Implement error handling for unsupported unit values when setting BarCodeWidth, throwing descriptive exception.
-// Tags: barcode, symbology, width, validation, error-handling, aspnet, aspose.barcode, generation
+// Tags: barcode, code128, width, validation, aspose.barcode, generation
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Demonstrates barcode generation with width validation and error handling using Aspose.BarCode.
+/// Demonstrates setting barcode width with validation using Aspose.BarCode.
///
class Program
{
///
- /// Validates the width value and applies it to the generator.
- /// Throws if the value is not positive.
+ /// Sets the barcode image width after validating the supplied value.
+ /// Throws if the value is not supported.
///
/// The instance to configure.
- /// Desired barcode width in points (1/72 inch).
- static void SetBarCodeWidth(BarcodeGenerator generator, float widthInPoints)
+ /// Desired barcode width in points (must be greater than zero).
+ static void SetBarCodeWidth(BarcodeGenerator generator, float width)
{
- // Ensure the width is a positive number.
- if (widthInPoints <= 0f)
+ // Validate that the width is a positive number.
+ if (width <= 0f)
{
throw new ArgumentOutOfRangeException(
- nameof(widthInPoints),
- "BarCodeWidth must be a positive value. Received: " + widthInPoints);
+ nameof(width),
+ width,
+ "BarCodeWidth must be a positive value greater than zero.");
}
- // Use Interpolation mode so that ImageWidth controls the barcode size.
+ // When AutoSizeMode is Interpolation, ImageWidth controls the barcode width.
generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- generator.Parameters.ImageWidth.Point = widthInPoints;
+ generator.Parameters.ImageWidth.Point = width;
}
///
- /// Entry point that creates a barcode, applies validated width, and saves the image.
+ /// Entry point demonstrating valid and invalid width handling.
///
static void Main()
{
- // Sample barcode generation with width validation.
+ // Example 1: generate a barcode with a valid width.
try
{
- // Initialize the generator with a specific symbology and data.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
{
- // Attempt to set an invalid width (uncomment to test exception).
- // SetBarCodeWidth(generator, -50f);
-
- // Set a valid width (200 points ≈ 2.78 inches).
- SetBarCodeWidth(generator, 200f);
-
- // Optional: set height for completeness.
- generator.Parameters.ImageHeight.Point = 100f;
+ SetBarCodeWidth(generator, 250f); // valid width in points
+ generator.Save("valid_barcode.png");
+ Console.WriteLine("Barcode generated with width 250pt: valid_barcode.png");
+ }
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Error generating barcode with valid width: {ex.Message}");
+ }
- // Save the barcode image to a file.
- generator.Save("barcode.png");
- Console.WriteLine("Barcode generated successfully.");
+ // Example 2: attempt to generate a barcode with an invalid (negative) width.
+ try
+ {
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "ABCDEF"))
+ {
+ SetBarCodeWidth(generator, -50f); // invalid width triggers exception
+ generator.Save("invalid_barcode.png");
}
}
catch (ArgumentOutOfRangeException ex)
{
- // Handle validation errors for barcode dimensions.
- Console.WriteLine("Error: " + ex.Message);
+ Console.WriteLine($"Caught expected exception for unsupported width: {ex.Message}");
}
catch (Exception ex)
{
- // Handle any unexpected errors.
- Console.WriteLine("Unexpected error: " + ex.Message);
+ Console.WriteLine($"Unexpected error: {ex.Message}");
}
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/implement-feature-exporting-generated-barcode-images-to-pdf-while-preserving-configured-size-and-resolution.cs b/barcode-size-and-resolution/implement-feature-exporting-generated-barcode-images-to-pdf-while-preserving-configured-size-and-resolution.cs
index 0fd84b0..f1f89d4 100644
--- a/barcode-size-and-resolution/implement-feature-exporting-generated-barcode-images-to-pdf-while-preserving-configured-size-and-resolution.cs
+++ b/barcode-size-and-resolution/implement-feature-exporting-generated-barcode-images-to-pdf-while-preserving-configured-size-and-resolution.cs
@@ -1,8 +1,8 @@
// Title: Export Barcode Image to PDF with Preserved Size and Resolution
-// Description: Generates a Code128 barcode, configures its dimensions and DPI, and embeds the image into a PDF while maintaining the exact size.
-// Category-Description: This example belongs to the Aspose.BarCode generation and Aspose.Pdf export category. It demonstrates how to use BarcodeGenerator (Aspose.BarCode.Generation) to create a barcode, adjust its AutoSizeMode, image dimensions, and resolution, then embed the resulting image into a PDF document (Aspose.Pdf) using Image objects. Developers often need to produce printable barcodes with precise sizing for labels, invoices, or reports, and this pattern shows the typical workflow for such scenarios.
+// Description: Demonstrates generating a Code128 barcode, configuring its dimensions and DPI, and exporting it as a PNG embedded in a PDF while keeping the specified size.
+// Category-Description: This example belongs to the Aspose.BarCode image generation and PDF integration category. It shows how to use BarcodeGenerator to set image size and resolution, save the barcode to a stream, and embed it into an Aspose.Pdf Document. Developers often need to create barcodes for reports, invoices, or shipping labels and export them to PDF with exact dimensions.
// Prompt: Implement feature exporting generated barcode images to PDF while preserving configured size and resolution.
-// Tags: code128, barcode generation, pdf export, image size, resolution, aspose.barcode, aspose.pdf
+// Tags: barcode, code128, pdf, image export, size, resolution, aspose.barcode, aspose.pdf
using System;
using System.IO;
@@ -11,44 +11,53 @@
using Aspose.Pdf;
///
-/// Demonstrates exporting a generated barcode image to a PDF file while preserving the configured size and resolution.
+/// Demonstrates generating a barcode, configuring its size and resolution,
+/// and exporting it to a PDF document while preserving those settings.
///
class Program
{
///
- /// Entry point of the example. Generates a barcode, configures its dimensions and DPI, and saves it inside a PDF.
+ /// Entry point of the example. Generates a Code128 barcode, embeds it in a PDF,
+ /// and saves the result to the output folder.
///
static void Main()
{
- // Define the output PDF file name.
- const string pdfPath = "barcode.pdf";
+ // Prepare the output directory where the PDF will be saved.
+ string outputDir = "output";
+ if (!Directory.Exists(outputDir))
+ {
+ Directory.CreateDirectory(outputDir);
+ }
- // Create a barcode generator for Code128 with sample text.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ // Define the full path for the resulting PDF file.
+ string pdfPath = Path.Combine(outputDir, "barcode.pdf");
+
+ // Create a barcode generator for Code128 symbology with the desired text.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Preserve size and resolution.
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- generator.Parameters.ImageWidth.Point = 300f; // Width in points (1 point = 1/72 inch).
- generator.Parameters.ImageHeight.Point = 150f; // Height in points.
- generator.Parameters.Resolution = 300; // DPI (dots per inch).
+ // Set the barcode image dimensions in points (1 point = 1/72 inch).
+ generator.Parameters.ImageWidth.Point = 300f;
+ generator.Parameters.ImageHeight.Point = 150f;
+
+ // Set the image resolution in DPI to ensure high-quality rendering.
+ generator.Parameters.Resolution = 300f;
- // Save the barcode image to a memory stream in PNG format.
- using (var imageStream = new MemoryStream())
+ // Save the generated barcode to a memory stream in PNG format.
+ using (var ms = new MemoryStream())
{
- generator.Save(imageStream, BarCodeImageFormat.Png);
- imageStream.Position = 0; // Reset stream position for reading.
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0; // Reset stream position for reading.
- // Create a PDF document and add the barcode image.
- using (var pdfDocument = new Document())
+ // Create a new PDF document and add a page to host the barcode image.
+ using (var pdfDoc = new Document())
{
- // Add a new page to the PDF.
- var page = pdfDocument.Pages.Add();
+ var page = pdfDoc.Pages.Add();
- // Create an Aspose.Pdf.Image object that reads from the memory stream.
+ // Create an Aspose.Pdf.Image object linked to the barcode stream.
var pdfImage = new Aspose.Pdf.Image
{
- ImageStream = imageStream,
- // Set image size to match the barcode dimensions.
+ ImageStream = ms,
+ // Preserve the configured width and height in the PDF.
FixWidth = generator.Parameters.ImageWidth.Point,
FixHeight = generator.Parameters.ImageHeight.Point
};
@@ -57,12 +66,12 @@ static void Main()
page.Paragraphs.Add(pdfImage);
// Save the PDF document to the specified path.
- pdfDocument.Save(pdfPath);
+ pdfDoc.Save(pdfPath);
}
}
}
- // Output the full path of the generated PDF for verification.
- Console.WriteLine($"Barcode exported to PDF: {Path.GetFullPath(pdfPath)}");
+ // Inform the user where the PDF has been saved.
+ Console.WriteLine($"Barcode PDF saved to: {pdfPath}");
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/implement-method-to-retrieve-actual-pixel-dimensions-of-generated-barcode-based-on-unit-and-resolution.cs b/barcode-size-and-resolution/implement-method-to-retrieve-actual-pixel-dimensions-of-generated-barcode-based-on-unit-and-resolution.cs
index 8b6168e..f373dfc 100644
--- a/barcode-size-and-resolution/implement-method-to-retrieve-actual-pixel-dimensions-of-generated-barcode-based-on-unit-and-resolution.cs
+++ b/barcode-size-and-resolution/implement-method-to-retrieve-actual-pixel-dimensions-of-generated-barcode-based-on-unit-and-resolution.cs
@@ -1,8 +1,8 @@
-// Title: Retrieve pixel dimensions of a generated barcode image
-// Description: Demonstrates how to obtain the actual width and height in pixels of a barcode generated with Aspose.BarCode, considering unit settings and resolution.
-// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, AutoSizeMode, and resolution settings to control barcode size. Developers often need to know the exact pixel dimensions for layout, printing, or further image processing, making this a common requirement in barcode rendering scenarios.
+// Title: Retrieve barcode pixel dimensions based on unit and resolution
+// Description: Demonstrates how to obtain the actual pixel width and height of a generated barcode image using Aspose.BarCode, taking into account the specified resolution and size units.
+// Category-Description: This example belongs to the Aspose.BarCode image generation and measurement category. It shows how to configure barcode parameters such as resolution, auto‑size mode, and unit‑based dimensions, then retrieve the resulting pixel dimensions via the generated bitmap. Developers working with barcode rendering often need to know the exact pixel size for layout, printing, or further image processing, and typically use classes like BarcodeGenerator, BarcodeParameters, and System.Drawing.Bitmap.
// Prompt: Implement method to retrieve actual pixel dimensions of generated barcode based on unit and resolution.
-// Tags: barcode symbology, image generation, pixel dimensions, resolution, autosizemode, aspose.barcode
+// Tags: barcode, code128, pixel-dimensions, resolution, autosizemode, aspnet, aspose.barcode, image-generation
using System;
using Aspose.BarCode;
@@ -10,48 +10,53 @@
using Aspose.Drawing;
///
-/// Example program that generates a Code128 barcode, configures its size and resolution,
-/// and retrieves the actual pixel dimensions of the resulting image.
+/// Provides an example of generating a barcode, configuring its size and resolution,
+/// and retrieving the actual pixel dimensions of the resulting image.
///
class Program
{
///
- /// Retrieves the actual pixel dimensions of the generated barcode image.
+ /// Generates the barcode image and returns its pixel width and height.
///
- /// The configured instance.
- /// A tuple containing the width and height in pixels.
+ /// Configured instance.
+ /// Tuple containing the image width and height in pixels.
static (int Width, int Height) GetBarcodePixelDimensions(BarcodeGenerator generator)
{
- // Generate the barcode image and obtain its pixel size.
+ // Generate the barcode image as a bitmap.
using (Bitmap bitmap = generator.GenerateBarCodeImage())
{
+ // Width and Height properties are expressed in pixels.
return (bitmap.Width, bitmap.Height);
}
}
///
- /// Entry point of the example. Configures barcode generation parameters,
- /// obtains pixel dimensions, and optionally saves the image to disk.
+ /// Entry point of the example. Configures barcode parameters, obtains pixel dimensions,
+ /// writes them to the console, and saves the image to a file.
///
static void Main()
{
- // Create a barcode generator for Code128 with sample text.
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
+ // Initialize a barcode generator for Code128 with sample text.
+ using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
- // Set resolution (dpi) – this influences unit-to-pixel conversion.
- generator.Parameters.Resolution = 300f; // 300 dpi
+ // Set a custom resolution (dots per inch) to influence pixel size.
+ generator.Parameters.Resolution = 300f; // 300 DPI
- // Use interpolation mode to control image size via ImageWidth/ImageHeight.
+ // Use interpolation mode to control size via ImageWidth/ImageHeight.
generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- generator.Parameters.ImageWidth.Point = 200f; // 200 points width
- generator.Parameters.ImageHeight.Point = 80f; // 80 points height
+ generator.Parameters.ImageWidth.Point = 200f; // Desired width in points.
+ generator.Parameters.ImageHeight.Point = 80f; // Desired height in points.
- // Retrieve actual pixel dimensions after generation.
- var (width, height) = GetBarcodePixelDimensions(generator);
+ // Optionally set XDimension (module size) in pixels.
+ generator.Parameters.Barcode.XDimension.Pixels = 3f;
+ // Retrieve the actual pixel dimensions after generation.
+ (int width, int height) = GetBarcodePixelDimensions(generator);
+
+ // Output the dimensions to the console.
Console.WriteLine($"Generated barcode pixel dimensions: Width = {width}px, Height = {height}px");
- // Optionally save the barcode image.
+ // Save the barcode image for visual verification (optional).
generator.Save("barcode.png");
}
}
diff --git a/barcode-size-and-resolution/instantiate-barcodegenerator-set-unit-to-inches-specify-width-and-height-and-generate-png-image.cs b/barcode-size-and-resolution/instantiate-barcodegenerator-set-unit-to-inches-specify-width-and-height-and-generate-png-image.cs
index 7ceccf7..7c729c6 100644
--- a/barcode-size-and-resolution/instantiate-barcodegenerator-set-unit-to-inches-specify-width-and-height-and-generate-png-image.cs
+++ b/barcode-size-and-resolution/instantiate-barcodegenerator-set-unit-to-inches-specify-width-and-height-and-generate-png-image.cs
@@ -1,37 +1,41 @@
// Title: Generate Code128 Barcode Image with Specified Size in Inches
-// Description: Demonstrates how to create a Code128 barcode, set its dimensions in inches, and save it as a PNG file.
-// Category-Description: Shows basic usage of Aspose.BarCode for barcode generation, covering the BarcodeGenerator class, EncodeTypes enumeration, and image parameter settings. Typical scenarios include creating printable barcodes with precise physical dimensions for labels, packaging, or inventory systems. Developers often need to control unit measurement, size, and output format when integrating barcode creation into .NET applications.
+// Description: Demonstrates creating a Code128 barcode, setting its dimensions in inches, and saving it as a PNG file.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator, set image size units, and export to common image formats. Developers often need to create barcodes with precise physical dimensions for printing on labels, packaging, or documents. The key API classes include BarcodeGenerator, EncodeTypes, and the Parameters.ImageWidth/Height properties.
// Prompt: Instantiate BarcodeGenerator, set unit to Inches, specify width and height, and generate a PNG image.
-// Tags: code128, barcode generation, inches, image size, png, aspose.barcode, barcodegenerator, encode types
+// Tags: code128, barcode generation, png output, inches, aspose.barcode, aspose.drawing
using System;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing.Imaging; // retained for completeness, though not required for the Save overload
+using Aspose.Drawing;
-///
-/// Example program that generates a Code128 barcode with specific dimensions in inches
-/// and saves it as a PNG image using Aspose.BarCode.
-///
-class Program
+namespace BarcodeExample
{
///
- /// Entry point of the example. Creates a barcode, configures size in inches, and writes a PNG file.
+ /// Provides an entry point that generates a Code128 barcode image with dimensions defined in inches.
///
- static void Main()
+ class Program
{
- // Initialize the barcode generator for Code128 symbology
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128))
+ ///
+ /// Creates a BarcodeGenerator, configures size in inches, and saves the barcode as a PNG file.
+ ///
+ static void Main()
{
- // Set the text that will be encoded into the barcode
- generator.CodeText = "123456";
+ // Initialize the barcode generator for Code128 symbology
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128))
+ {
+ // Set the data to be encoded in the barcode
+ generator.CodeText = "1234567890";
- // Define the image dimensions using inches (2 inches wide, 1 inch tall)
- generator.Parameters.ImageWidth.Inches = 2f; // width in inches
- generator.Parameters.ImageHeight.Inches = 1f; // height in inches
+ // Define the image width and height using inches as the unit
+ generator.Parameters.ImageWidth.Inches = 3f; // 3 inches wide
+ generator.Parameters.ImageHeight.Inches = 1f; // 1 inch tall
- // Save the generated barcode as a PNG file in the current directory
- generator.Save("barcode.png");
+ // Save the generated barcode to a PNG file
+ generator.Save("barcode.png");
+ }
+
+ // Inform the user that the image has been created
+ Console.WriteLine("Barcode image generated: barcode.png");
}
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/integrate-barcode-generation-into-aspnet-mvc-view-letting-users-select-measurement-unit-and-resolution-before-rendering.cs b/barcode-size-and-resolution/integrate-barcode-generation-into-aspnet-mvc-view-letting-users-select-measurement-unit-and-resolution-before-rendering.cs
index 466e111..cb3cfbf 100644
--- a/barcode-size-and-resolution/integrate-barcode-generation-into-aspnet-mvc-view-letting-users-select-measurement-unit-and-resolution-before-rendering.cs
+++ b/barcode-size-and-resolution/integrate-barcode-generation-into-aspnet-mvc-view-letting-users-select-measurement-unit-and-resolution-before-rendering.cs
@@ -1,69 +1,63 @@
-// Title: Barcode generation with selectable measurement unit and resolution
-// Description: Demonstrates how to generate a barcode image while allowing users to choose the measurement unit and DPI resolution before rendering.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and image parameter settings. Developers often need to customize barcode size and resolution for web applications, print media, or UI integration, and this snippet shows typical API usage for those scenarios.
+// Title: Barcode generation with selectable unit and resolution for ASP.NET MVC
+// Description: Demonstrates creating a barcode image where the measurement unit and DPI resolution are configurable, suitable for rendering in an MVC view.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator, set resolution, measurement units (points, pixels, millimeters), and image dimensions. Developers often need to generate barcodes dynamically in web applications, customize size, and serve the image from a view. The snippet shows typical API usage for such scenarios.
// Prompt: Integrate barcode generation into ASP.NET MVC view, letting users select measurement unit and resolution before rendering.
-// Tags: barcode, generation, measurement unit, resolution, aspnet mvc, code128, png
+// Tags: barcode generation, aspnet mvc, measurement unit, resolution, code128, png, aspose.barcode
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
+using Aspose.Drawing;
///
-/// Demonstrates core barcode generation logic that can be used behind an ASP.NET MVC view.
+/// Demonstrates core barcode generation logic that can be integrated into an ASP.NET MVC view.
+/// The example shows how to configure measurement units, resolution, and image dimensions before saving the barcode image.
///
class Program
{
///
- /// Entry point that simulates user selections, configures the barcode generator, and saves the image.
+ /// Entry point of the console application.
+ /// In a real MVC scenario, the same logic would be invoked from a controller action and the image streamed to the view.
///
static void Main()
{
- // Simulated user inputs: measurement unit and DPI resolution
- string selectedUnit = "Pixel"; // Options: "Point", "Pixel", "Inch", "Millimeter"
- float selectedResolution = 300f; // DPI
-
- // Barcode content and symbology type
+ // Sample input parameters (in a real MVC app these would be bound from user input)
string codeText = "Sample123";
- BaseEncodeType encodeType = EncodeTypes.Code128;
+ BaseEncodeType encodeType = EncodeTypes.Code128; // 1D barcode symbology
+ float resolutionDpi = 300f; // User‑selected DPI resolution
+
+ // Measurement unit selection: Points (could also be Pixels or Millimeters)
+ // All size‑related properties are set using the .Point member.
- // Create the barcode generator with the chosen type and content
+ // Initialize the barcode generator with the chosen symbology and data
using (var generator = new BarcodeGenerator(encodeType, codeText))
{
- // Apply the selected resolution (dots per inch)
- generator.Parameters.Resolution = selectedResolution;
-
- // Set image size using the chosen measurement unit
- // Example size: 300 x 150 in the selected unit
- switch (selectedUnit)
- {
- case "Point":
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 150f;
- break;
- case "Pixel":
- generator.Parameters.ImageWidth.Pixels = 300f;
- generator.Parameters.ImageHeight.Pixels = 150f;
- break;
- case "Inch":
- generator.Parameters.ImageWidth.Inches = 3f;
- generator.Parameters.ImageHeight.Inches = 1.5f;
- break;
- case "Millimeter":
- generator.Parameters.ImageWidth.Millimeters = 76.2f; // 3 inches
- generator.Parameters.ImageHeight.Millimeters = 38.1f; // 1.5 inches
- break;
- default:
- throw new ArgumentException($"Unsupported unit: {selectedUnit}");
- }
+ // Apply the user‑selected resolution (DPI)
+ generator.Parameters.Resolution = resolutionDpi;
- // Optional: set auto-size mode to interpolation to respect ImageWidth/Height settings
+ // Use interpolation mode to ensure the image size matches the specified dimensions exactly
generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- // Save the generated barcode image to a file
+ // Define the output image size in points
+ generator.Parameters.ImageWidth.Point = 300f; // Width in points
+ generator.Parameters.ImageHeight.Point = 150f; // Height in points
+
+ // Configure barcode-specific dimensions in points
+ generator.Parameters.Barcode.XDimension.Point = 2f; // Module (X) width
+ generator.Parameters.Barcode.BarHeight.Point = 40f; // Bar height for 1D barcode
+
+ // Optional: set foreground (bars) and background colors
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
+ generator.Parameters.BackColor = Aspose.Drawing.Color.White;
+
+ // Save the generated barcode image to a file (could be streamed instead in MVC)
string outputPath = "barcode.png";
- generator.Save(outputPath);
+ generator.Save(outputPath, BarCodeImageFormat.Png);
- Console.WriteLine($"Barcode saved to '{outputPath}' using unit '{selectedUnit}' and resolution {selectedResolution} DPI.");
+ // Informational output for debugging or logging purposes
+ Console.WriteLine($"Barcode generated and saved to '{outputPath}'.");
+ Console.WriteLine($"Resolution: {generator.Parameters.Resolution} DPI");
+ Console.WriteLine($"Image size: {generator.Parameters.ImageWidth.Point}pt x {generator.Parameters.ImageHeight.Point}pt");
}
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/programmatically-switch-measurement-unit-from-millimeters-to-pixels-between-two-barcode-generations-in-one-run.cs b/barcode-size-and-resolution/programmatically-switch-measurement-unit-from-millimeters-to-pixels-between-two-barcode-generations-in-one-run.cs
index 9647f30..1134864 100644
--- a/barcode-size-and-resolution/programmatically-switch-measurement-unit-from-millimeters-to-pixels-between-two-barcode-generations-in-one-run.cs
+++ b/barcode-size-and-resolution/programmatically-switch-measurement-unit-from-millimeters-to-pixels-between-two-barcode-generations-in-one-run.cs
@@ -1,52 +1,61 @@
-// Title: Switch measurement unit between millimeters and pixels for barcode generation
-// Description: Demonstrates generating two barcodes in one run, first using millimeters for bar height then switching to pixels.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to control measurement units (millimeters, pixels) via the BarcodeGenerator.Parameters.Barcode.BarHeight properties. Developers often need to switch units to meet layout requirements for different output media, such as print (mm) versus screen (px). The key API classes used are BarcodeGenerator, EncodeTypes, and AutoSizeMode.
+// Title: Switch Measurement Unit Between Millimeters and Pixels for Barcode Generation
+// Description: Demonstrates generating two barcodes in one execution, first using millimeters and then pixels as measurement units.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure measurement units via the Parameters.Barcode properties. It showcases the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes, common in scenarios where precise sizing is required for different output media. Developers often need to switch between physical (mm) and screen (pixel) units when creating barcodes for print and digital displays.
// Prompt: Programmatically switch measurement unit from Millimeters to Pixels between two barcode generations in one run.
-// Tags: code128, measurement unit, millimeters, pixels, barcode generation, aspose.barcode
+// Tags: code128, measurement-unit, generation, png, aspose.barcode
using System;
+using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Example program that generates two Code128 barcodes, first using millimeters for bar height
-/// and then switching to pixels, demonstrating unit conversion within a single execution.
+/// Example program that generates two Code128 barcodes, first using millimeter units
+/// and then using pixel units, demonstrating how to switch measurement units at runtime.
///
class Program
{
///
- /// Entry point of the application. Generates two barcode images with different measurement units.
+ /// Entry point of the application. Creates an output folder, generates two barcodes
+ /// with different measurement units, and saves them as PNG files.
///
static void Main()
{
+ // Ensure the output directory exists
+ string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ if (!Directory.Exists(outputDir))
+ {
+ Directory.CreateDirectory(outputDir);
+ }
+
// ------------------------------------------------------------
- // First barcode: use millimeters for bar height
+ // First barcode: measurement unit set to millimeters
// ------------------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ using (var generatorMm = new BarcodeGenerator(EncodeTypes.Code128, "FirstMM"))
{
- // Disable automatic sizing to allow explicit height setting
- generator.Parameters.AutoSizeMode = AutoSizeMode.None;
+ // Configure X-dimension and bar height in millimeters
+ generatorMm.Parameters.Barcode.XDimension.Millimeters = 0.5f;
+ generatorMm.Parameters.Barcode.BarHeight.Millimeters = 10f;
- // Set bar height explicitly in millimeters (10 mm)
- generator.Parameters.Barcode.BarHeight.Millimeters = 10f;
-
- // Save the generated barcode image to a PNG file
- generator.Save("barcode_mm.png");
+ // Save the barcode image as PNG
+ string filePathMm = Path.Combine(outputDir, "barcode_mm.png");
+ generatorMm.Save(filePathMm, BarCodeImageFormat.Png);
+ Console.WriteLine($"Saved barcode with millimeter units to: {filePathMm}");
}
// ------------------------------------------------------------
- // Second barcode: switch to pixels for bar height
+ // Second barcode: measurement unit set to pixels
// ------------------------------------------------------------
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ using (var generatorPx = new BarcodeGenerator(EncodeTypes.Code128, "SecondPx"))
{
- // Disable automatic sizing to allow explicit height setting
- generator.Parameters.AutoSizeMode = AutoSizeMode.None;
-
- // Set bar height explicitly in pixels (40 px)
- generator.Parameters.Barcode.BarHeight.Pixels = 40f;
+ // Configure X-dimension and bar height in pixels
+ generatorPx.Parameters.Barcode.XDimension.Pixels = 2f;
+ generatorPx.Parameters.Barcode.BarHeight.Pixels = 40f;
- // Save the generated barcode image to a PNG file
- generator.Save("barcode_px.png");
+ // Save the barcode image as PNG
+ string filePathPx = Path.Combine(outputDir, "barcode_px.png");
+ generatorPx.Save(filePathPx, BarCodeImageFormat.Png);
+ Console.WriteLine($"Saved barcode with pixel units to: {filePathPx}");
}
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/read-barcode-size-parameters-from-json-apply-to-barcodegenerator-and-output-png-images-to-folder.cs b/barcode-size-and-resolution/read-barcode-size-parameters-from-json-apply-to-barcodegenerator-and-output-png-images-to-folder.cs
index af58456..00a79a3 100644
--- a/barcode-size-and-resolution/read-barcode-size-parameters-from-json-apply-to-barcodegenerator-and-output-png-images-to-folder.cs
+++ b/barcode-size-and-resolution/read-barcode-size-parameters-from-json-apply-to-barcodegenerator-and-output-png-images-to-folder.cs
@@ -1,14 +1,14 @@
-// Title: Batch Barcode Generation from JSON Configuration
-// Description: Demonstrates reading barcode size parameters from a JSON file, applying them to Aspose.BarCode's BarcodeGenerator, and saving PNG images to a folder.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to programmatically create barcodes using the BarcodeGenerator class. It covers typical use cases such as configuring image dimensions, X‑dimension, and bar height based on external data sources like JSON. Developers often need to batch‑process barcode creation with varying parameters, and this snippet illustrates a reusable pattern for such scenarios.
+// Title: Batch Barcode Generation from JSON Parameters
+// Description: Reads barcode size and content settings from a JSON file, generates corresponding barcodes, and saves them as PNG images.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, demonstrating how to use BarcodeGenerator with dynamic parameters. It covers resolving symbology via EncodeTypes, applying image dimensions, and exporting PNG files—common tasks for developers creating bulk barcodes in automated workflows.
// Prompt: Read barcode size parameters from JSON, apply to BarcodeGenerator, and output PNG images to a folder.
-// Tags: barcode, symbology, generation, json, png, aspose.barcode, size-parameters
+// Tags: barcode, generation, json, png, aspose.barcode, batch, size parameters
using System;
using System.Collections.Generic;
using System.IO;
+using System.Reflection;
using System.Text.Json;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
@@ -16,9 +16,9 @@
namespace BarcodeBatchGenerator
{
///
- /// Represents a single barcode configuration read from JSON.
+ /// Represents the size and content parameters for a single barcode.
///
- public class BarcodeConfig
+ public class BarcodeParams
{
public string Symbology { get; set; }
public string CodeText { get; set; }
@@ -26,96 +26,126 @@ public class BarcodeConfig
public float? ImageHeight { get; set; }
public float? XDimension { get; set; }
public float? BarHeight { get; set; }
- public string OutputFileName { get; set; }
}
///
- /// Entry point for the batch barcode generation example.
+ /// Demonstrates reading barcode configuration from a JSON file, generating barcodes with Aspose.BarCode,
+ /// and saving them as PNG images to a specified folder.
///
class Program
{
///
- /// Reads barcode configurations from a JSON file, generates each barcode with the specified size parameters,
- /// and saves the resulting PNG images to the output folder.
+ /// Entry point of the application. Handles JSON deserialization, barcode generation, and file output.
///
static void Main()
{
- // Path to the JSON file containing barcode size parameters.
- const string jsonPath = "barcodeConfig.json";
+ const string jsonFileName = "barcodeParams.json";
+ const string outputFolder = "Barcodes";
- // Verify that the configuration file exists before proceeding.
- if (!File.Exists(jsonPath))
+ // Ensure the output directory exists.
+ if (!Directory.Exists(outputFolder))
+ Directory.CreateDirectory(outputFolder);
+
+ // If the JSON configuration file is missing, create a sample file and exit.
+ if (!File.Exists(jsonFileName))
{
- Console.WriteLine($"Configuration file not found: {jsonPath}");
+ var sample = new List
+ {
+ new BarcodeParams
+ {
+ Symbology = "Code128",
+ CodeText = "Sample123",
+ ImageWidth = 300f,
+ ImageHeight = 150f,
+ XDimension = 2f,
+ BarHeight = 50f
+ },
+ new BarcodeParams
+ {
+ Symbology = "QR",
+ CodeText = "https://example.com",
+ ImageWidth = 250f,
+ ImageHeight = 250f,
+ XDimension = 3f
+ }
+ };
+ var sampleJson = JsonSerializer.Serialize(sample, new JsonSerializerOptions { WriteIndented = true });
+ File.WriteAllText(jsonFileName, sampleJson);
+ Console.WriteLine($"Sample JSON created at '{jsonFileName}'. Edit it as needed and rerun the program.");
return;
}
- // Read and deserialize the JSON configuration into a list of BarcodeConfig objects.
- List configs;
- using (FileStream jsonStream = new FileStream(jsonPath, FileMode.Open, FileAccess.Read))
+ // Read and deserialize the JSON file into a list of BarcodeParams objects.
+ string jsonContent = File.ReadAllText(jsonFileName);
+ List items;
+ try
{
- configs = JsonSerializer.Deserialize>(jsonStream);
+ items = JsonSerializer.Deserialize>(jsonContent);
+ if (items == null)
+ throw new Exception("Deserialized list is null.");
}
-
- // Ensure that at least one configuration was loaded.
- if (configs == null || configs.Count == 0)
+ catch (Exception ex)
{
- Console.WriteLine("No barcode configurations found in the JSON file.");
+ Console.WriteLine($"Failed to parse JSON: {ex.Message}");
return;
}
- // Ensure the output directory exists; create it if necessary.
- const string outputFolder = "GeneratedBarcodes";
- if (!Directory.Exists(outputFolder))
+ int index = 0;
+ foreach (var item in items)
{
- Directory.CreateDirectory(outputFolder);
- }
+ index++;
- // Process each barcode configuration.
- foreach (var cfg in configs)
- {
- // Resolve the symbology name to the corresponding EncodeTypes field via reflection.
- var field = typeof(EncodeTypes).GetField(cfg.Symbology);
+ // Validate that a symbology name is provided.
+ if (string.IsNullOrWhiteSpace(item.Symbology))
+ {
+ Console.WriteLine($"Item {index}: Symbology is missing. Skipping.");
+ continue;
+ }
+
+ // Resolve the symbology string to a BaseEncodeType using reflection.
+ var field = typeof(EncodeTypes).GetField(item.Symbology);
if (field == null)
{
- Console.WriteLine($"Unknown symbology: {cfg.Symbology}. Skipping entry.");
+ Console.WriteLine($"Item {index}: Unknown symbology '{item.Symbology}'. Skipping.");
continue;
}
var encodeType = (BaseEncodeType)field.GetValue(null);
- // Create the barcode generator with the resolved symbology and provided code text.
- using (var generator = new BarcodeGenerator(encodeType, cfg.CodeText))
+ // Create a BarcodeGenerator with the resolved type and provided code text.
+ using (BarcodeGenerator generator = new BarcodeGenerator(encodeType, item.CodeText ?? string.Empty))
{
- // Apply optional size parameters if they are specified in the configuration.
- if (cfg.ImageWidth.HasValue)
- generator.Parameters.ImageWidth.Point = cfg.ImageWidth.Value;
- if (cfg.ImageHeight.HasValue)
- generator.Parameters.ImageHeight.Point = cfg.ImageHeight.Value;
- if (cfg.XDimension.HasValue)
- generator.Parameters.Barcode.XDimension.Point = cfg.XDimension.Value;
- if (cfg.BarHeight.HasValue)
- generator.Parameters.Barcode.BarHeight.Point = cfg.BarHeight.Value;
-
- // Enable interpolation mode when explicit image dimensions are set.
- if (cfg.ImageWidth.HasValue || cfg.ImageHeight.HasValue)
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ // Apply optional size parameters if they are specified.
+ if (item.ImageWidth.HasValue)
+ generator.Parameters.ImageWidth.Point = item.ImageWidth.Value;
+ if (item.ImageHeight.HasValue)
+ generator.Parameters.ImageHeight.Point = item.ImageHeight.Value;
+ if (item.XDimension.HasValue)
+ generator.Parameters.Barcode.XDimension.Point = item.XDimension.Value;
+ if (item.BarHeight.HasValue)
+ generator.Parameters.Barcode.BarHeight.Point = item.BarHeight.Value;
- // Determine the output file name; generate a GUID if none is provided.
- string fileName = string.IsNullOrWhiteSpace(cfg.OutputFileName)
- ? $"{Guid.NewGuid()}.png"
- : cfg.OutputFileName;
+ // Set a default foreground color (optional).
+ generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black;
- // Combine the output folder path with the file name.
- string outputPath = Path.Combine(outputFolder, fileName);
+ // Build a safe output file name.
+ string safeSymbology = item.Symbology.Replace("/", "_");
+ string outputPath = Path.Combine(outputFolder, $"{safeSymbology}_{index}.png");
- // Save the generated barcode as a PNG image.
- generator.Save(outputPath, BarCodeImageFormat.Png);
- Console.WriteLine($"Saved barcode to: {outputPath}");
+ // Save the generated barcode as a PNG file.
+ try
+ {
+ generator.Save(outputPath);
+ Console.WriteLine($"Item {index}: Barcode saved to '{outputPath}'.");
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Item {index}: Failed to save barcode - {ex.Message}");
+ }
}
}
- Console.WriteLine("Barcode generation completed.");
+ Console.WriteLine("Processing completed.");
}
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/set-barcodegenerator-resolution-to-300-dpi-generate-qr-code-and-write-bitmap-to-memory-stream.cs b/barcode-size-and-resolution/set-barcodegenerator-resolution-to-300-dpi-generate-qr-code-and-write-bitmap-to-memory-stream.cs
index 7b0b393..fb41e28 100644
--- a/barcode-size-and-resolution/set-barcodegenerator-resolution-to-300-dpi-generate-qr-code-and-write-bitmap-to-memory-stream.cs
+++ b/barcode-size-and-resolution/set-barcodegenerator-resolution-to-300-dpi-generate-qr-code-and-write-bitmap-to-memory-stream.cs
@@ -1,43 +1,45 @@
-// Title: Generate QR code bitmap with 300 dpi resolution and write to memory stream
-// Description: Demonstrates how to configure Aspose.BarCode's BarcodeGenerator to produce a QR code at 300 dpi, render it as a bitmap, and store the image in a memory stream.
-// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating the use of BarcodeGenerator, its Parameters, and the GenerateBarCodeImage method to create high‑resolution barcode images. Typical scenarios include generating QR codes for web links, product information, or authentication tokens, where developers need to control image quality and output to streams for further processing or transmission.
+// Title: Generate QR Code with 300 DPI Resolution and Save to Memory Stream
+// Description: Demonstrates setting the BarcodeGenerator resolution to 300 dpi, creating a QR code, and writing the resulting bitmap to a memory stream in PNG format.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure image resolution, encode data using QR symbology, and output the barcode as a bitmap via the BarcodeGenerator and Bitmap classes. Developers commonly use these APIs to produce high‑resolution barcodes for printing, digital display, or further image processing in .NET applications.
// Prompt: Set BarcodeGenerator resolution to 300 dpi, generate QR code, and write bitmap to memory stream.
-// Tags: qr code, resolution, bitmap, memory stream, aspose.barcode, image generation
+// Tags: qr code, resolution, bitmap, memory stream, aspose.barcode, generation, png
using System;
using System.IO;
-using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
using Aspose.Drawing.Imaging;
///
-/// Example program that generates a QR code bitmap at 300 dpi and writes it to a memory stream.
+/// Example program that generates a QR code at 300 dpi and writes the image to a memory stream.
///
class Program
{
///
- /// Entry point. Configures the barcode generator, creates a QR code bitmap, and saves it to a memory stream.
+ /// Entry point. Configures the barcode generator, creates a QR code, and saves it as PNG in a memory stream.
///
static void Main()
{
- // Initialize a QR code generator with the desired text (a sample URL)
- using (var generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"))
+ // Initialize a QR code generator with the QR symbology
+ using (var generator = new BarcodeGenerator(EncodeTypes.QR))
{
- // Set the image resolution to 300 dpi for higher quality output
+ // Set the output image resolution to 300 dots per inch
generator.Parameters.Resolution = 300f;
- // Generate the barcode as a bitmap image
+ // Define the data to encode in the QR code
+ generator.CodeText = "Hello World";
+
+ // Generate the barcode image as a Bitmap object
using (Bitmap bitmap = generator.GenerateBarCodeImage())
{
- // Create a memory stream to hold the PNG-encoded bitmap
+ // Prepare a memory stream to hold the PNG-encoded image
using (var memoryStream = new MemoryStream())
{
// Save the bitmap into the stream using PNG format
bitmap.Save(memoryStream, ImageFormat.Png);
- // Output the size of the generated image stream for verification
- Console.WriteLine($"QR code image generated, stream length: {memoryStream.Length} bytes");
+ // Output the size of the generated image (for demonstration purposes)
+ Console.WriteLine($"QR code image generated. Stream length: {memoryStream.Length} bytes");
}
}
}
diff --git a/barcode-size-and-resolution/set-barcodegenerator-resolution-to-600-dpi-generate-pdf417-barcode-and-verify-pixel-dimensions-match-expected-size.cs b/barcode-size-and-resolution/set-barcodegenerator-resolution-to-600-dpi-generate-pdf417-barcode-and-verify-pixel-dimensions-match-expected-size.cs
index 83a4e61..6b2a95f 100644
--- a/barcode-size-and-resolution/set-barcodegenerator-resolution-to-600-dpi-generate-pdf417-barcode-and-verify-pixel-dimensions-match-expected-size.cs
+++ b/barcode-size-and-resolution/set-barcodegenerator-resolution-to-600-dpi-generate-pdf417-barcode-and-verify-pixel-dimensions-match-expected-size.cs
@@ -1,61 +1,75 @@
-// Title: Generate PDF417 Barcode at 600 DPI and Verify Image Size
-// Description: This example creates a PDF417 barcode with a resolution of 600 dpi, sets its physical dimensions, and checks that the resulting bitmap matches the expected pixel size.
-// Category-Description: Demonstrates Aspose.BarCode barcode generation with high‑resolution settings. It showcases the use of BarcodeGenerator, EncodeTypes, and AutoSizeMode to control image size in inches, a common requirement for printing and scanning applications. Developers often need to set resolution, define physical dimensions, and validate pixel output when integrating barcodes into documents or labels.
+// Title: Generate PDF417 barcode at 600 dpi and validate image size
+// Description: Demonstrates setting the BarcodeGenerator resolution to 600 dpi, creating a PDF417 barcode, saving it as PNG, and confirming the resulting pixel dimensions.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to configure barcode resolution and image size using the BarcodeGenerator and related parameter classes. Typical use cases include high‑resolution printing, precise layout calculations, and verification of generated barcode dimensions. Developers often need to adjust DPI, image width/height, and validate output for compliance with printing standards.
// Prompt: Set BarcodeGenerator resolution to 600 dpi, generate PDF417 barcode, and verify pixel dimensions match expected size.
-// Tags: pdf417, resolution, barcode generation, image size, aspose.barcode, aspose.drawing
+// Tags: pdf417, barcode generation, resolution, png, aspose.barcode, aspose.drawing
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
/// Example program that generates a PDF417 barcode at 600 dpi,
-/// defines its physical size, and validates the resulting pixel dimensions.
+/// saves it as a PNG file, and verifies the resulting image dimensions.
///
class Program
{
///
- /// Entry point of the example. Performs barcode generation, size verification, and saves the image.
+ /// Entry point of the example. Performs barcode generation,
+ /// saves the image, and validates DPI and pixel size.
///
static void Main()
{
- // Define the expected physical size of the barcode in inches.
- const float expectedWidthInches = 2f;
- const float expectedHeightInches = 1f;
- const float resolutionDpi = 600f;
+ // Define the output file path for the generated barcode image.
+ string outputPath = "pdf417.png";
- // Calculate the expected pixel dimensions based on the resolution.
- int expectedPixelWidth = (int)(expectedWidthInches * resolutionDpi);
- int expectedPixelHeight = (int)(expectedHeightInches * resolutionDpi);
-
- // Initialize the PDF417 barcode generator with sample text.
+ // Create a PDF417 barcode generator with sample text.
using (var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Sample PDF417 Text"))
{
// Set the image resolution to 600 dpi.
- generator.Parameters.Resolution = resolutionDpi;
-
- // Configure auto‑size mode to use interpolation and set the image size in inches.
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- generator.Parameters.ImageWidth.Inches = expectedWidthInches;
- generator.Parameters.ImageHeight.Inches = expectedHeightInches;
-
- // Generate the barcode image as a bitmap.
- using (Bitmap bitmap = generator.GenerateBarCodeImage())
- {
- // Verify that the bitmap dimensions match the expected pixel size.
- bool widthMatches = bitmap.Width == expectedPixelWidth;
- bool heightMatches = bitmap.Height == expectedPixelHeight;
-
- Console.WriteLine($"Generated image size: {bitmap.Width}x{bitmap.Height} pixels");
- Console.WriteLine($"Expected image size: {expectedPixelWidth}x{expectedPixelHeight} pixels");
- Console.WriteLine($"Width match: {widthMatches}");
- Console.WriteLine($"Height match: {heightMatches}");
-
- // Save the generated barcode image to a PNG file.
- bitmap.Save("pdf417.png", ImageFormat.Png);
- }
+ generator.Parameters.Resolution = 600f;
+
+ // Define the desired image size in points (1 point = 1/72 inch).
+ generator.Parameters.ImageWidth.Point = 200f;
+ generator.Parameters.ImageHeight.Point = 100f;
+
+ // Save the generated barcode as a PNG file.
+ generator.Save(outputPath, BarCodeImageFormat.Png);
+ }
+
+ // Load the saved image to verify its DPI and pixel dimensions.
+ using (var image = Image.FromFile(outputPath))
+ {
+ // Retrieve actual DPI values from the image.
+ float horizontalDpi = image.HorizontalResolution;
+ float verticalDpi = image.VerticalResolution;
+
+ // Retrieve actual pixel dimensions.
+ int actualWidth = image.Width;
+ int actualHeight = image.Height;
+
+ // Calculate expected pixel dimensions based on points and resolution.
+ // pixels = points * (dpi / 72)
+ int expectedWidth = (int)Math.Round(200f * 600f / 72f);
+ int expectedHeight = (int)Math.Round(100f * 600f / 72f);
+
+ // Output diagnostic information.
+ Console.WriteLine($"Resolution: {horizontalDpi} dpi (H), {verticalDpi} dpi (V)");
+ Console.WriteLine($"Actual size: {actualWidth}×{actualHeight} px");
+ Console.WriteLine($"Expected size: {expectedWidth}×{expectedHeight} px");
+
+ // Verify that the image DPI matches the requested 600 dpi.
+ if (Math.Abs(horizontalDpi - 600f) > 0.1f || Math.Abs(verticalDpi - 600f) > 0.1f)
+ Console.WriteLine("Resolution mismatch!");
+ else
+ Console.WriteLine("Resolution matches the expected 600 dpi.");
+
+ // Verify that the pixel dimensions match the calculated expectations.
+ if (actualWidth == expectedWidth && actualHeight == expectedHeight)
+ Console.WriteLine("Pixel dimensions match the expected size.");
+ else
+ Console.WriteLine("Pixel dimensions do NOT match the expected size.");
}
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/set-barcodegenerator-resolution-to-72-dpi-test-barcode-generation-meets-low-resolution-display-requirements.cs b/barcode-size-and-resolution/set-barcodegenerator-resolution-to-72-dpi-test-barcode-generation-meets-low-resolution-display-requirements.cs
index ca03fc9..01e326b 100644
--- a/barcode-size-and-resolution/set-barcodegenerator-resolution-to-72-dpi-test-barcode-generation-meets-low-resolution-display-requirements.cs
+++ b/barcode-size-and-resolution/set-barcodegenerator-resolution-to-72-dpi-test-barcode-generation-meets-low-resolution-display-requirements.cs
@@ -1,52 +1,45 @@
-// Title: Generate low‑resolution Code128 barcode image
-// Description: Demonstrates setting the BarcodeGenerator resolution to 72 dpi and verifies the output image meets low‑resolution display requirements.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode rendering parameters such as resolution. It uses BarcodeGenerator and its Parameters property to produce PNG images, a common task for developers needing barcodes for low‑resolution screens or printers. Typical use cases include embedding barcodes in web pages, mobile apps, or low‑dpi print media.
+// Title: Generate low‑resolution barcode image (72 dpi) using Aspose.BarCode
+// Description: Demonstrates setting the BarcodeGenerator resolution to 72 dpi and saving the barcode as a PNG file, useful for low‑resolution display scenarios.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure image resolution with the BarcodeGenerator class. Developers often need to adjust DPI for screen or printer constraints, and this snippet shows typical usage of EncodeTypes, generator.Parameters, and saving the output. Ideal for quick reference in search results.
// Prompt: Set BarcodeGenerator resolution to 72 dpi, test barcode generation meets low‑resolution display requirements.
-// Tags: code128, barcode generation, low resolution, png, aspose.barcode, resolution
+// Tags: barcode, code128, resolution, 72dpi, png, generation, aspose.barcode
using System;
using System.IO;
+using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
///
-/// Demonstrates generating a Code128 barcode at 72 dpi and verifying the image resolution.
+/// Demonstrates generating a Code128 barcode at 72 dpi resolution and saving it as a PNG file.
///
class Program
{
///
- /// Entry point. Creates a barcode image with low resolution, saves it, and prints the actual DPI.
+ /// Entry point of the example. Creates a barcode, sets low‑resolution DPI, saves the image, and reports success.
///
static void Main()
{
// Define the output file path for the generated barcode image
- string outputPath = "barcode.png";
+ string outputPath = "barcode_72dpi.png";
- // Create a BarcodeGenerator for Code128 symbology with the desired text
- using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
+ // Initialize the barcode generator with Code128 symbology and sample data
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Set the resolution to 72 dpi to meet low‑resolution display requirements
+ // Configure the generator to use a low‑resolution of 72 dpi (suitable for low‑res displays)
generator.Parameters.Resolution = 72f;
- // Save the generated barcode as a PNG file
+ // Save the generated barcode image to the specified path (default format is PNG)
generator.Save(outputPath);
}
- // Verify that the barcode image file was created successfully
- if (!File.Exists(outputPath))
+ // Check whether the barcode image file was successfully created
+ if (File.Exists(outputPath))
{
- Console.WriteLine("Failed to create barcode image.");
- return;
+ Console.WriteLine($"Barcode generated successfully at {outputPath} with 72 dpi resolution.");
}
-
- // Load the saved image to read its actual DPI values
- using (var image = Image.FromFile(outputPath))
+ else
{
- float horizDpi = image.HorizontalResolution;
- float vertDpi = image.VerticalResolution;
-
- // Output the horizontal and vertical DPI of the generated image
- Console.WriteLine($"Barcode image resolution: {horizDpi} dpi (horizontal), {vertDpi} dpi (vertical)");
+ Console.WriteLine("Failed to generate the barcode image.");
}
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/set-fontunit-to-document-define-caption-font-size-and-produce-datamatrix-barcode-saved-as-bmp-file.cs b/barcode-size-and-resolution/set-fontunit-to-document-define-caption-font-size-and-produce-datamatrix-barcode-saved-as-bmp-file.cs
index 9a1adf9..303d88a 100644
--- a/barcode-size-and-resolution/set-fontunit-to-document-define-caption-font-size-and-produce-datamatrix-barcode-saved-as-bmp-file.cs
+++ b/barcode-size-and-resolution/set-fontunit-to-document-define-caption-font-size-and-produce-datamatrix-barcode-saved-as-bmp-file.cs
@@ -1,8 +1,8 @@
// Title: Generate DataMatrix barcode with caption and save as BMP
-// Description: Creates a DataMatrix barcode, adds a caption above it, and saves the image as a BMP file.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, demonstrating how to configure barcode parameters such as caption text, font settings, and specific DataMatrix version. It showcases the use of BarcodeGenerator, EncodeTypes, and related parameter classes to produce a printable barcode image. Developers often need to customize captions, fonts, and output formats when integrating barcodes into documents or labels.
+// Description: Demonstrates setting the caption font unit to Document, defining its size, and creating a DataMatrix barcode saved as a BMP image.
+// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, focusing on customizing caption appearance using the FontUnit property and saving the result in bitmap format. It showcases the BarcodeGenerator class, EncodeTypes enumeration, and drawing output options, which developers commonly use to embed barcodes with readable captions in documents, reports, or UI elements.
// Prompt: Set FontUnit to Document, define caption font size, and produce DataMatrix barcode saved as BMP file.
-// Tags: datamatrix, barcode, caption, bmp, aspose.barcode, generation, fontunit
+// Tags: datamatrix, caption, fontunit, bmp, aspose.barcode, barcode-generation
using System;
using Aspose.BarCode;
@@ -10,31 +10,30 @@
using Aspose.Drawing;
///
-/// Demonstrates creating a DataMatrix barcode with a caption and saving it as a BMP image.
+/// Example program that creates a DataMatrix barcode with a caption,
+/// configures the caption font using Document units, and saves the result as a BMP file.
///
class Program
{
///
- /// Entry point of the example. Generates the barcode, configures caption and font, and writes the BMP file.
+ /// Entry point of the example. Generates the barcode and writes it to disk.
///
static void Main()
{
- // Initialize a DataMatrix barcode generator with the desired text.
- using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "Sample123"))
+ // Initialize a BarcodeGenerator for DataMatrix with the desired data string.
+ using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "Sample DataMatrix"))
{
- // Set the font unit to Document (if supported by the API). This line is kept as a comment per the task requirement.
- // generator.Parameters.FontUnit = FontUnit.Document;
-
// Configure the caption that appears above the barcode.
- generator.Parameters.CaptionAbove.Text = "DataMatrix Example";
- generator.Parameters.CaptionAbove.Font.FamilyName = "Arial";
- generator.Parameters.CaptionAbove.Font.Size.Point = 12f; // Set caption font size to 12 points.
- generator.Parameters.CaptionAbove.Alignment = TextAlignment.Center;
+ // Set the font family to Helvetica.
+ generator.Parameters.CaptionAbove.Font.FamilyName = "Helvetica";
+
+ // Define the font size in points (FontUnit is handled internally by the API).
+ generator.Parameters.CaptionAbove.Font.Size.Point = 12f;
- // Optionally specify a DataMatrix version (choose a valid square size).
- generator.Parameters.Barcode.DataMatrix.DataMatrixVersion = DataMatrixVersion.ECC200_20x20;
+ // Assign the caption text to be displayed.
+ generator.Parameters.CaptionAbove.Text = "DataMatrix Barcode";
- // Save the generated barcode as a BMP file.
+ // Save the generated barcode as a BMP image file.
generator.Save("datamatrix.bmp");
}
}
diff --git a/barcode-size-and-resolution/use-unitdocument-for-fontunit-of-barcode-caption-then-produce-high-resolution-600-dpi-png-output.cs b/barcode-size-and-resolution/use-unitdocument-for-fontunit-of-barcode-caption-then-produce-high-resolution-600-dpi-png-output.cs
index 699b59c..84082d8 100644
--- a/barcode-size-and-resolution/use-unitdocument-for-fontunit-of-barcode-caption-then-produce-high-resolution-600-dpi-png-output.cs
+++ b/barcode-size-and-resolution/use-unitdocument-for-fontunit-of-barcode-caption-then-produce-high-resolution-600-dpi-png-output.cs
@@ -1,8 +1,8 @@
-// Title: Generate Code128 barcode with caption and 600 dpi PNG output
-// Description: This example creates a Code128 barcode, adds a caption using Document font units, and saves a high‑resolution 600 dpi PNG image.
-// Category-Description: Demonstrates Aspose.BarCode barcode generation with advanced rendering options. Shows how to configure resolution, image size, and caption properties using the BarcodeGenerator, Parameters, and related classes. Ideal for developers needing high‑quality barcode images for print or digital media.
+// Title: Generate Code128 barcode with caption using Document unit and 600 dpi PNG output
+// Description: Demonstrates creating a Code128 barcode, adding a caption with FontUnit.Document, and saving it as a high‑resolution 600 dpi PNG image.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode parameters such as resolution, caption placement, and font units. It showcases the use of BarcodeGenerator, EncodeTypes, and FontUnit classes, which are commonly needed when developers need precise control over barcode appearance and high‑quality image output for printing or digital media.
// Prompt: Use Unit.Document for FontUnit of barcode caption, then produce high‑resolution 600 dpi PNG output.
-// Tags: code128, caption, resolution, png, aspose.barcode, barcodegenerator, parameters, highresolution
+// Tags: code128, barcode, caption, png, high-resolution, 600dpi, aspose.barcodes, fontunit, document-unit
using System;
using Aspose.BarCode;
@@ -10,35 +10,34 @@
using Aspose.Drawing;
///
-/// Example program that generates a Code128 barcode with a caption and saves it as a 600 dpi PNG image.
+/// Example program that creates a Code128 barcode with a caption,
+/// sets the caption font size using FontUnit.Document,
+/// and saves the result as a 600 dpi PNG image.
///
class Program
{
///
- /// Entry point of the application.
+ /// Entry point of the example. Generates the barcode and writes the PNG file.
///
static void Main()
{
- // Initialize a barcode generator for Code128 with the sample text "1234567890"
+ // Initialize a barcode generator for Code128 symbology with sample data.
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
- // Set the output resolution to 600 dpi for high‑quality rendering
+ // Set the output resolution to 600 DPI for high‑quality rendering.
generator.Parameters.Resolution = 600f;
- // Enable interpolation mode for smoother scaling and define image dimensions in points
- generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- generator.Parameters.ImageWidth.Point = 300f;
- generator.Parameters.ImageHeight.Point = 150f;
-
- // Configure a caption to appear above the barcode
+ // Configure a caption that appears above the barcode.
generator.Parameters.CaptionAbove.Text = "Sample Caption";
- generator.Parameters.CaptionAbove.Font.FamilyName = "Arial";
- // Use Document units for the font size (12 points in Document units)
+
+ // Specify the caption font size using Document units (points).
generator.Parameters.CaptionAbove.Font.Size.Document = 12f;
- generator.Parameters.CaptionAbove.Alignment = TextAlignment.Center;
- // Save the generated barcode as a high‑resolution PNG file
- generator.Save("barcode.png");
+ // Choose a widely available font family for the caption.
+ generator.Parameters.CaptionAbove.Font.FamilyName = "Helvetica";
+
+ // Save the generated barcode as a PNG file with the specified resolution.
+ generator.Save("barcode_600dpi.png");
}
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/use-unitpoint-for-fontunit-of-human-readable-text-then-generate-ean13-barcode-saved-as-png.cs b/barcode-size-and-resolution/use-unitpoint-for-fontunit-of-human-readable-text-then-generate-ean13-barcode-saved-as-png.cs
index a6b633b..fc141f5 100644
--- a/barcode-size-and-resolution/use-unitpoint-for-fontunit-of-human-readable-text-then-generate-ean13-barcode-saved-as-png.cs
+++ b/barcode-size-and-resolution/use-unitpoint-for-fontunit-of-human-readable-text-then-generate-ean13-barcode-saved-as-png.cs
@@ -1,54 +1,39 @@
-// Title: Generate EAN13 barcode with Point font size and save as PNG
-// Description: Demonstrates setting human‑readable text font size using Unit.Point and creating an EAN13 barcode saved as a PNG image.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to configure text appearance with FontUnit, set colors, and output common image formats. It uses BarcodeGenerator, EncodeTypes, and related parameter classes, which developers frequently employ to embed barcodes in documents, labels, or web pages.
+// Title: Generate EAN13 barcode with point-sized human‑readable text
+// Description: Demonstrates creating an EAN13 barcode, setting the human‑readable font size using Unit.Point, and saving it as a PNG image.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode parameters such as CodeText and FontUnit. It uses the BarcodeGenerator and related parameter classes to produce barcodes for retail and inventory applications. Developers often need to customize human‑readable text appearance and export barcodes in common image formats.
// Prompt: Use Unit.Point for FontUnit of human‑readable text, then generate EAN13 barcode saved as PNG.
-// Tags: ean13, barcode generation, png, aspose.barcode, aspose.drawing, fontunit, point
+// Tags: ean13, barcode, generation, png, fontunit, point, aspose.barcode
using System;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
-using Aspose.Drawing;
///
-/// Demonstrates generating an EAN13 barcode with human‑readable text sized in points and saving it as a PNG file.
+/// Example program that generates an EAN13 barcode,
+/// sets the human‑readable text font size using Point units,
+/// and saves the result as a PNG file.
///
class Program
{
///
- /// Entry point. Configures the barcode generator, sets font size using Point units, and saves the image.
+ /// Entry point of the application.
///
static void Main()
{
- // Initialize a barcode generator for the EAN13 symbology with a 12‑digit value.
- // The checksum digit is calculated automatically.
- using (var generator = new BarcodeGenerator(EncodeTypes.EAN13, "123456789012"))
+ // Initialize a barcode generator for the EAN13 symbology.
+ using (var generator = new BarcodeGenerator(EncodeTypes.EAN13))
{
- // ----- Configure human‑readable text -----
- // Set the font family for the code text.
- generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Arial";
+ // Assign a 12‑digit code; the checksum digit is calculated automatically.
+ generator.CodeText = "123456789012";
- // Use Point units to define the font size (12 points).
+ // Set the human‑readable text font size to 12 points.
generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 12f;
- // Center the text horizontally relative to the barcode.
- generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center;
-
- // Position the text below the barcode bars.
- generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below;
-
- // ----- Optional visual styling -----
- // Set the barcode (bars) color to black.
- generator.Parameters.Barcode.BarColor = Color.Black;
-
- // Set the background color of the image to white.
- generator.Parameters.BackColor = Color.White;
-
- // ----- Save the barcode image -----
- // The image is saved in PNG format with the specified file name.
+ // Save the generated barcode image as a PNG file.
generator.Save("ean13.png");
}
- // Inform the user that the operation completed successfully.
+ // Inform the user that the barcode has been created.
Console.WriteLine("EAN13 barcode generated and saved as ean13.png");
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/validate-barcode-generated-at-96-dpi-matches-expected-pixel-dimensions-for-20-mm-width.cs b/barcode-size-and-resolution/validate-barcode-generated-at-96-dpi-matches-expected-pixel-dimensions-for-20-mm-width.cs
index d676488..b857ffa 100644
--- a/barcode-size-and-resolution/validate-barcode-generated-at-96-dpi-matches-expected-pixel-dimensions-for-20-mm-width.cs
+++ b/barcode-size-and-resolution/validate-barcode-generated-at-96-dpi-matches-expected-pixel-dimensions-for-20-mm-width.cs
@@ -1,78 +1,73 @@
-// Title: Validate barcode pixel width at 96 dpi for 20 mm barcode
-// Description: Generates a Code128 barcode at 96 dpi with a width of 20 mm, saves it as PNG, and verifies that the resulting image width matches the expected pixel count.
-// Category-Description: This example belongs to the Aspose.BarCode image generation and validation category. It demonstrates how to configure barcode dimensions using the BarcodeGenerator, set resolution via Parameters.Resolution, and validate the output image size using Aspose.Drawing.Image. Developers often need to ensure that generated barcodes meet exact physical size requirements for printing and scanning, making pixel‑to‑millimeter calculations essential.
-// Prompt: Validate barcode generated at 96 dpi matches expected pixel dimensions for 20 mm width.
-// Tags: code128, barcode generation, image validation, resolution, dimensions, aspose.barcode, aspose.drawing, png
+// Title: Validate barcode pixel dimensions at 96 dpi
+// Description: Demonstrates generating a Code128 barcode at 96 dpi and verifying its pixel width matches a 20 mm physical size.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to control image resolution, canvas size, and auto‑size mode using BarcodeGenerator, ImageWidth, and Resolution properties. Typical use cases include creating barcodes for print layouts where exact physical dimensions are required. Developers often need to validate that generated images meet size specifications for downstream processing or compliance.
+/// Prompt: Validate barcode generated at 96 dpi matches expected pixel dimensions for 20 mm width.
+// Tags: code128, generation, png, resolution, autosizemode, imagewidth, aspose.barcode, aspose.drawing
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Demonstrates how to generate a barcode with a specific physical width,
-/// save it as an image, and validate that the image dimensions correspond to the expected pixel size.
+/// Generates a Code128 barcode at a specific DPI and validates that its pixel width matches the expected size for a 20 mm physical width.
///
class Program
{
///
- /// Entry point of the example. Generates a Code128 barcode, saves it as PNG,
- /// and checks that its pixel width matches the calculated value for 20 mm at 96 dpi.
+ /// Main entry point. Creates the barcode, saves it to a memory stream, and checks the image width against the expected pixel count.
///
static void Main()
{
- // Define the desired barcode width in millimeters and the target resolution.
- const float millimeters = 20f;
+ // Desired physical width in millimeters.
+ const float targetWidthMm = 20f;
+ // Target DPI resolution.
const float dpi = 96f;
- // Convert millimeters to inches (1 inch = 25.4 mm) and calculate expected pixel width.
- float inches = millimeters / 25.4f;
+ // Convert millimeters to inches (1 inch = 25.4 mm).
+ double inches = targetWidthMm / 25.4;
+ // Calculate expected pixel width (rounded to nearest integer).
int expectedPixels = (int)Math.Round(inches * dpi);
- // Output file path for the generated barcode image.
- string outputPath = "barcode.png";
+ // Use a short Code128 text to ensure it fits the target width.
+ const string codeText = "12";
- // Ensure a clean start by deleting any existing file with the same name.
- if (File.Exists(outputPath))
+ // Initialize the barcode generator with Code128 symbology.
+ using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
{
- File.Delete(outputPath);
- }
-
- // Create and configure the barcode generator.
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
- {
- // Set the image resolution (dots per inch).
+ // Set the image resolution.
generator.Parameters.Resolution = dpi;
+ // Force the canvas size using interpolation mode.
+ generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
+ // Set the canvas width to the expected pixel count.
+ generator.Parameters.ImageWidth.Point = expectedPixels;
+ // Height can be arbitrary; let the generator decide (set to 100 pixels here).
+ generator.Parameters.ImageHeight.Point = 100f;
- // Disable automatic size adjustment; we will set dimensions manually.
- generator.Parameters.AutoSizeMode = AutoSizeMode.None;
-
- // Specify the barcode width and a reasonable height in millimeters.
- generator.Parameters.ImageWidth.Millimeters = millimeters;
- generator.Parameters.ImageHeight.Millimeters = 10f;
-
- // Save the barcode as a PNG image.
- generator.Save(outputPath, BarCodeImageFormat.Png);
- }
+ // Save the generated barcode to a memory stream in PNG format.
+ using (var ms = new MemoryStream())
+ {
+ generator.Save(ms, BarCodeImageFormat.Png);
+ ms.Position = 0; // Reset stream position for reading.
- // Load the saved image to verify its actual pixel width.
- using (Image image = Image.FromFile(outputPath))
- {
- int actualWidth = image.Width;
+ // Load the image from the memory stream.
+ using (var image = Image.FromStream(ms))
+ {
+ int actualWidth = image.Width; // Pixel width of the generated image.
- // Output the expected and actual widths for comparison.
- Console.WriteLine($"Expected width: {expectedPixels} pixels");
- Console.WriteLine($"Actual width : {actualWidth} pixels");
+ // Allow a tolerance of ±2 pixels due to rounding/rendering differences.
+ int tolerance = 2;
+ bool matches = Math.Abs(actualWidth - expectedPixels) <= tolerance;
- // Report validation result.
- if (actualWidth == expectedPixels)
- {
- Console.WriteLine("Validation succeeded: barcode width matches expected dimensions.");
- }
- else
- {
- Console.WriteLine("Validation failed: barcode width does not match expected dimensions.");
+ // Output the validation results.
+ Console.WriteLine($"Target width: {targetWidthMm} mm ({expectedPixels} px at {dpi} DPI)");
+ Console.WriteLine($"Actual image width: {actualWidth} px");
+ Console.WriteLine(matches
+ ? "The generated barcode matches the expected pixel dimensions."
+ : "The generated barcode does NOT match the expected pixel dimensions.");
+ }
}
}
}
diff --git a/barcode-size-and-resolution/write-code-generating-barcode-with-barcodeheight-zero-barcodewidth-40-mm-and-verify-auto-height-behavior.cs b/barcode-size-and-resolution/write-code-generating-barcode-with-barcodeheight-zero-barcodewidth-40-mm-and-verify-auto-height-behavior.cs
index db3dd7d..4c256b9 100644
--- a/barcode-size-and-resolution/write-code-generating-barcode-with-barcodeheight-zero-barcodewidth-40-mm-and-verify-auto-height-behavior.cs
+++ b/barcode-size-and-resolution/write-code-generating-barcode-with-barcodeheight-zero-barcodewidth-40-mm-and-verify-auto-height-behavior.cs
@@ -1,61 +1,60 @@
// Title: Generate barcode with auto‑height and fixed width
-// Description: Demonstrates creating a Code128 barcode with a fixed width of 40 mm while letting the height be calculated automatically.
-// Category-Description: This example belongs to the Aspose.BarCode barcode generation category, illustrating how to control image dimensions using the AutoSizeMode, ImageWidth, and BarHeight properties. Developers often need to generate barcodes with specific width constraints while allowing the library to determine optimal height for readability. The code uses BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes to produce PNG output.
+// Description: Creates a Code128 barcode image with a width of 40 mm while allowing the height to be calculated automatically.
+// Category-Description: Demonstrates Aspose.BarCode image generation using the AutoSizeMode feature. This example shows how to set a fixed barcode width in millimeters, leave the height unset, and let the library compute the optimal height. It uses BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes, which are commonly used for creating barcode images in various formats for printing or display.
// Prompt: Write code generating barcode with BarCodeHeight zero, BarCodeWidth 40 mm, and verify auto‑height behavior.
-// Tags: code128, barcode, auto-size, width, height, png, aspose.barcode, generation
+// Tags: barcode, code128, autosize, width, height, png, aspose.barcode, image generation
using System;
-using Aspose.BarCode;
+using System.IO;
using Aspose.BarCode.Generation;
+using Aspose.BarCode;
using Aspose.Drawing;
+using Aspose.Drawing.Imaging;
///
-/// Example program that creates a Code128 barcode with a fixed width of 40 mm,
-/// lets the library automatically determine the height, saves the image,
-/// and then verifies the resulting height.
+/// Example program that generates a Code128 barcode with a fixed width of 40 mm
+/// and automatically calculated height, then outputs the image dimensions.
///
class Program
{
///
/// Entry point of the example. Generates the barcode, saves it as PNG,
- /// and prints the image dimensions and calculated height in millimeters.
+ /// and prints the resulting image size in pixels and millimeters.
///
static void Main()
{
- // Output file path for the generated barcode image
- const string outputPath = "barcode.png";
+ // Define the output file path for the generated barcode image.
+ string outputPath = "barcode.png";
- // Create a barcode generator for Code128 with sample text "123456"
+ // Create a BarcodeGenerator for Code128 with the sample text "123456".
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
{
- // Enable auto‑size mode based on interpolation to let height adjust automatically
+ // Enable auto‑size mode so the barcode height is calculated automatically.
generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
- // Set the desired barcode width to 40 mm (height will be auto‑calculated)
+ // Set the desired barcode width to 40 mm.
generator.Parameters.ImageWidth.Millimeters = 40f;
- // Do NOT set BarHeight; the auto‑height behavior will be applied
-
- // Save the generated barcode image in PNG format
+ // Do NOT set BarHeight (leaving it at default) to allow auto‑height.
+ // Save the barcode image as a PNG file.
generator.Save(outputPath, BarCodeImageFormat.Png);
}
- // Load the saved image to verify the resulting height
- using (var image = (Image)Image.FromFile(outputPath))
+ // Load the generated image to verify its actual dimensions.
+ using (var bitmap = new Bitmap(outputPath))
{
- // Image dimensions in pixels
- int widthPx = image.Width;
- int heightPx = image.Height;
-
- // Resolution (dpi) used during generation (default is 96)
- const float resolutionDpi = 96f; // same as generator.Parameters.Resolution default
-
- // Convert height from pixels to millimeters: (pixels / dpi) * 25.4
- float heightMm = heightPx / resolutionDpi * 25.4f;
-
- // Output the image size and calculated barcode height
- Console.WriteLine($"Barcode image size: {widthPx}x{heightPx} pixels");
- Console.WriteLine($"Calculated barcode height: {heightMm:F2} mm (auto‑height)");
+ int widthPx = bitmap.Width;
+ int heightPx = bitmap.Height;
+
+ // Use the generator's default resolution (96 dpi) for conversion to millimeters.
+ float dpi = 96f;
+ float widthMm = widthPx * 25.4f / dpi;
+ float heightMm = heightPx * 25.4f / dpi;
+
+ // Output the image size in both pixels and millimeters.
+ Console.WriteLine($"Generated barcode image size: {widthPx} px × {heightPx} px");
+ Console.WriteLine($"Width: {widthMm:F2} mm (expected 40 mm)");
+ Console.WriteLine($"Height: {heightMm:F2} mm (auto‑calculated)");
}
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/write-script-generating-barcodes-at-96-150-and-300-dpi-and-comparing-output-file-sizes.cs b/barcode-size-and-resolution/write-script-generating-barcodes-at-96-150-and-300-dpi-and-comparing-output-file-sizes.cs
index 6163c49..01a0122 100644
--- a/barcode-size-and-resolution/write-script-generating-barcodes-at-96-150-and-300-dpi-and-comparing-output-file-sizes.cs
+++ b/barcode-size-and-resolution/write-script-generating-barcodes-at-96-150-and-300-dpi-and-comparing-output-file-sizes.cs
@@ -1,96 +1,94 @@
-// Title: Barcode generation at multiple DPI settings with file size comparison
-// Description: Demonstrates creating Code128 barcodes at 96, 150, and 300 dpi, saving as PNG, and comparing the resulting file sizes.
-// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure the Resolution property of BarcodeGenerator, save images, and analyze output size. Developers working with barcode image rendering often need to balance image quality against file size, and this snippet shows typical usage of EncodeTypes, BarcodeGenerator, and file I/O for such assessments.
+// Title: Generate barcodes at multiple DPI settings and compare file sizes
+// Description: Demonstrates creating Code128 barcodes at 96, 150, and 300 dpi, saving them as PNG, and reporting the resulting file sizes.
+// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to configure the Resolution property of BarcodeGenerator, save images in various formats, and analyze output size. Developers working with barcode rendering, DPI optimization, or storage considerations can use these patterns to balance quality and file size.
// Prompt: Write script generating barcodes at 96, 150, and 300 dpi and comparing output file sizes.
-// Tags: code128, barcode generation, png, resolution, file size, aspose.barcode, barcodegenerator
+// Tags: barcode, code128, resolution, dpi, png, file-size, aspose.barcode, generation
using System;
+using System.Collections.Generic;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
///
-/// Demonstrates generating Code128 barcodes at various DPI settings and comparing the resulting file sizes.
+/// Demonstrates generating Code128 barcodes at different DPI settings and comparing the resulting PNG file sizes.
///
class Program
{
///
- /// Entry point. Generates barcodes at 96, 150, and 300 dpi, saves them as PNG files, and reports file size statistics.
+ /// Entry point of the example. Generates barcodes, saves them, and prints size comparisons.
///
static void Main()
{
- // Sample barcode data to encode
- const string codeText = "1234567890";
+ // Barcode content and symbology
+ string codeText = "1234567890";
+ BaseEncodeType encodeType = EncodeTypes.Code128;
// Resolutions (dots per inch) to test
- float[] resolutions = new float[] { 96f, 150f, 300f };
+ float[] resolutions = { 96f, 150f, 300f };
- // Array to store generated file sizes for each resolution
- long[] fileSizes = new long[resolutions.Length];
+ // Dictionary to store file size for each DPI
+ Dictionary fileSizes = new Dictionary();
- // Loop through each resolution, generate barcode, and record file size
- for (int i = 0; i < resolutions.Length; i++)
+ // Iterate over each resolution, generate and save the barcode
+ foreach (float dpi in resolutions)
{
- // Build output file name based on current DPI
- string fileName = $"barcode_{(int)resolutions[i]}dpi.png";
+ string fileName = $"barcode_{dpi}.png";
- // Create and configure the barcode generator
- using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
+ // Create a generator instance and configure it
+ using (BarcodeGenerator generator = new BarcodeGenerator(encodeType, codeText))
{
- // Set the desired image resolution
- generator.Parameters.Resolution = resolutions[i];
+ // Apply the desired DPI resolution
+ generator.Parameters.Resolution = dpi;
- // Save the generated barcode as a PNG image
- generator.Save(fileName);
+ // Save the barcode as a PNG image
+ generator.Save(fileName, BarCodeImageFormat.Png);
}
- // Verify that the file was created and capture its size
+ // Record the size of the generated file
if (File.Exists(fileName))
{
- fileSizes[i] = new FileInfo(fileName).Length;
- Console.WriteLine($"Generated {fileName}: {fileSizes[i]} bytes (Resolution: {resolutions[i]} dpi)");
+ FileInfo info = new FileInfo(fileName);
+ fileSizes[dpi] = info.Length;
+ Console.WriteLine($"Resolution {dpi} dpi: file size = {info.Length} bytes");
}
else
{
- Console.WriteLine($"Failed to generate {fileName}");
- fileSizes[i] = -1;
+ Console.WriteLine($"Failed to create file for resolution {dpi} dpi.");
}
}
- // Output a simple comparison of file sizes across resolutions
+ // Output a summary of all recorded sizes
Console.WriteLine();
- Console.WriteLine("File size comparison:");
- for (int i = 0; i < resolutions.Length; i++)
+ Console.WriteLine("Size comparison:");
+ foreach (var kvp in fileSizes)
{
- Console.WriteLine($"{(int)resolutions[i]} dpi -> {fileSizes[i]} bytes");
+ Console.WriteLine($"{kvp.Key} dpi -> {kvp.Value} bytes");
}
- // Determine which resolution produced the smallest and largest files
- long minSize = long.MaxValue;
- long maxSize = long.MinValue;
- int minIndex = -1;
- int maxIndex = -1;
-
- for (int i = 0; i < fileSizes.Length; i++)
+ // Determine and display the smallest and largest files
+ if (fileSizes.Count > 0)
{
- if (fileSizes[i] >= 0 && fileSizes[i] < minSize)
- {
- minSize = fileSizes[i];
- minIndex = i;
- }
- if (fileSizes[i] > maxSize)
+ float minDpi = 0f, maxDpi = 0f;
+ long minSize = long.MaxValue, maxSize = long.MinValue;
+
+ foreach (var kvp in fileSizes)
{
- maxSize = fileSizes[i];
- maxIndex = i;
+ if (kvp.Value < minSize)
+ {
+ minSize = kvp.Value;
+ minDpi = kvp.Key;
+ }
+ if (kvp.Value > maxSize)
+ {
+ maxSize = kvp.Value;
+ maxDpi = kvp.Key;
+ }
}
- }
- // Report the resolutions with the smallest and largest file sizes
- if (minIndex >= 0 && maxIndex >= 0)
- {
Console.WriteLine();
- Console.WriteLine($"Smallest file: {resolutions[minIndex]} dpi ({minSize} bytes)");
- Console.WriteLine($"Largest file: {resolutions[maxIndex]} dpi ({maxSize} bytes)");
+ Console.WriteLine($"Smallest file: {minDpi} dpi ({minSize} bytes)");
+ Console.WriteLine($"Largest file: {maxDpi} dpi ({maxSize} bytes)");
}
}
}
\ No newline at end of file
diff --git a/barcode-size-and-resolution/write-script-generating-barcodes-with-incremental-barcodeheight-values-saving-each-as-jpeg-and-logging-dimensions.cs b/barcode-size-and-resolution/write-script-generating-barcodes-with-incremental-barcodeheight-values-saving-each-as-jpeg-and-logging-dimensions.cs
index 678bfc7..c6188a6 100644
--- a/barcode-size-and-resolution/write-script-generating-barcodes-with-incremental-barcodeheight-values-saving-each-as-jpeg-and-logging-dimensions.cs
+++ b/barcode-size-and-resolution/write-script-generating-barcodes-with-incremental-barcodeheight-values-saving-each-as-jpeg-and-logging-dimensions.cs
@@ -1,67 +1,66 @@
-// Title: Generating Barcodes with Incremental BarHeight and Saving as JPEG
-// Description: The example creates a series of Code128 barcodes, each with a different BarHeight, saves them as JPEG files, and logs their pixel dimensions.
-// Category-Description: This sample belongs to the Aspose.BarCode generation category, demonstrating how to control barcode dimensions using the BarcodeGenerator class and its Parameters.Barcode properties. Typical use cases include creating barcodes with custom visual appearance for packaging, labeling, or printing workflows. Developers often need to adjust BarHeight, AutoSizeMode, and output formats, making this example a useful reference for similar tasks.
+// Title: Generating Code128 barcodes with varying heights
+// Description: Demonstrates creating Code128 barcodes with incremental BarCodeHeight values, saving each as a JPEG, and logging the resulting image dimensions.
+// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to control barcode size using the BarHeight property via the BarcodeGenerator and its Parameters. Typical use cases include producing barcodes of different visual sizes for printing or UI display. Developers often need to adjust dimensions, set AutoSizeMode, and export to common image formats using classes like BarcodeGenerator, EncodeTypes, BarCodeImageFormat, and Aspose.Drawing.Image.
// Prompt: Write script generating barcodes with incremental BarCodeHeight values, saving each as JPEG and logging dimensions.
-// Tags: barcode, code128, barheight, jpeg, generation, aspose.barcode, aspose.drawing
+// Tags: barcode symbology, generation, jpeg, barheight, aspose.barcode, aspose.drawing
using System;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
-using Aspose.Drawing.Imaging;
///
-/// Demonstrates generating multiple Code128 barcodes with varying BarHeight values,
-/// saving each image as a JPEG file, and outputting the resulting dimensions.
+/// Program that generates Code128 barcodes with varying heights, saves them as JPEG files,
+/// and outputs the image dimensions to the console.
///
class Program
{
///
- /// Entry point of the application. Creates an output directory, generates barcodes,
- /// saves them, and writes dimension information to the console.
+ /// Entry point. Creates output folder, iterates over predefined heights, generates barcodes,
+ /// saves them, and logs their pixel dimensions.
///
static void Main()
{
- // Determine the directory where barcode images will be stored
- string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
+ // Define the output directory for generated barcode images
+ string outputDir = "Barcodes";
+
+ // Ensure the output directory exists
if (!Directory.Exists(outputDir))
{
- // Create the directory if it does not already exist
Directory.CreateDirectory(outputDir);
}
- // Generate 5 barcodes, each with an increased BarHeight
- for (int i = 0; i < 5; i++)
- {
- // Calculate BarHeight: start at 20 points and increase by 10 points per iteration
- float barHeight = 20f + i * 10f;
+ // Define incremental BarCodeHeight values (in points)
+ float[] heights = new float[] { 20f, 40f, 60f, 80f, 100f };
- // Initialize a barcode generator for the Code128 symbology
+ // Process each height value
+ foreach (float height in heights)
+ {
+ // Create a barcode generator for Code128 symbology
using (var generator = new BarcodeGenerator(EncodeTypes.Code128))
{
- // Assign the text to be encoded in the barcode
- generator.CodeText = $"Sample{i + 1}";
+ // Assign a simple codetext that includes the height value
+ generator.CodeText = $"Sample{height}";
- // Disable automatic sizing so we can set BarHeight manually
+ // Disable automatic sizing to allow manual BarHeight setting
generator.Parameters.AutoSizeMode = AutoSizeMode.None;
- // Apply the calculated BarHeight using the Point unit
- generator.Parameters.Barcode.BarHeight.Point = barHeight;
+ // Set the barcode's bar height (in points)
+ generator.Parameters.Barcode.BarHeight.Point = height;
- // Generate the barcode image as a Bitmap
- using (Bitmap bitmap = generator.GenerateBarCodeImage())
- {
- // Construct a descriptive file name that includes the index and BarHeight
- string fileName = $"barcode_{i + 1}_{barHeight}pt.jpg";
- string filePath = Path.Combine(outputDir, fileName);
+ // Build the file path for the JPEG image
+ string filePath = Path.Combine(outputDir, $"barcode_{height}.jpeg");
- // Save the bitmap as a JPEG file using Aspose.Drawing.Imaging.ImageFormat
- bitmap.Save(filePath, ImageFormat.Jpeg);
+ // Save the generated barcode as a JPEG file
+ generator.Save(filePath, BarCodeImageFormat.Jpeg);
+ }
- // Output the saved file name and its pixel dimensions to the console
- Console.WriteLine($"Saved {fileName}: {bitmap.Width}x{bitmap.Height} pixels (BarHeight={barHeight}pt)");
- }
+ // Load the saved JPEG to retrieve its pixel dimensions
+ using (var image = Image.FromFile(Path.Combine(outputDir, $"barcode_{height}.jpeg")))
+ {
+ // Log the file name and its width/height in pixels
+ Console.WriteLine($"Saved barcode_{height}.jpeg - Width: {image.Width}px, Height: {image.Height}px");
}
}
}