Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
class Program
{
/// <summary>
/// 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.
/// </summary>
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);
}
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
class Program
{
Expand All @@ -18,17 +19,23 @@ class Program
/// </summary>
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");
}
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
class Program
{
/// <summary>
/// Entry point of the application.
/// Entry point of the example. Sets barcode parameters in pixels, obtains point values, and saves the barcode as PNG.
/// </summary>
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");
}
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// Console utility that reads barcode data from a CSV file (or uses sample data) and generates PNG images with specified dimensions.
/// </summary>
class Program
{
/// <summary>
/// Entry point. Accepts optional CSV file path argument, processes each line, and saves generated barcodes.
/// </summary>
/// <param name="args">Command‑line arguments; first argument may be the CSV file path.</param>
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.");
}
}
Loading
Loading