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,90 +1,95 @@
// Title: Batch Code39 SVG Barcode Generator
// Description: Reads a list of values from a CSV file (or uses a default list) and creates a Code39 barcode SVG for each entry.
// Title: Batch generate Code39 barcodes from CSV to SVG files
// Description: Reads a CSV file, generates a Code39 barcode for each entry, and saves each barcode as an individual SVG file.
// Category-Description: This example demonstrates batch barcode generation using Aspose.BarCode. It showcases the BarcodeGenerator class with EncodeTypes.Code39 and BarCodeImageFormat.Svg to create SVG images. Typical scenarios include bulk creation of product labels, inventory tags, or any situation where a list of identifiers must be turned into barcodes. Developers working with Aspose.BarCode often need to read data sources, generate barcodes programmatically, and store them in various image formats.
// Prompt: Batch generate Code39 barcodes from a CSV list and save each as an individual SVG file.
// Tags: code39, barcode, batch, svg, csv, aspnet, aspose.barcode
// Tags: code39, barcode, generation, svg, csv, aspose.barcode, batch-processing

using System;
using System.Collections.Generic;
using System.IO;
using Aspose.BarCode;
using Aspose.BarCode.Generation;

/// <summary>
/// Demonstrates how to generate a batch of Code39 barcodes from a CSV file
/// Demonstrates how to read a CSV file, generate a Code39 barcode for each line,
/// and save each barcode as an individual SVG file using Aspose.BarCode.
/// </summary>
class Program
{
/// <summary>
/// Entry point of the application. Handles CSV loading, barcode generation,
/// and file output for each code text.
/// Entry point of the application. Processes command‑line arguments,
/// validates input, generates barcodes, and writes SVG files to the output folder.
/// </summary>
static void Main()
/// <param name="args">
/// Optional arguments:
/// args[0] – path to the input CSV file (default: "input.csv").
/// args[1] – path to the output folder for SVG files (default: "Barcodes").
/// </param>
static void Main(string[] args)
{
// Input CSV file path (optional). If the file does not exist, a default list is used.
const string csvPath = "input.csv";
// Default input CSV file and output directory
string csvPath = "input.csv";
string outputFolder = "Barcodes";

// Directory where SVG files will be saved.
const string outputDir = "Barcodes";

// Ensure the output directory exists.
if (!Directory.Exists(outputDir))
// Override defaults with command‑line arguments if provided
if (args.Length > 0 && !string.IsNullOrWhiteSpace(args[0]))
{
Directory.CreateDirectory(outputDir);
csvPath = args[0];
}

// Load code texts from CSV or use a fallback sample.
List<string> codeTexts = new List<string>();
if (File.Exists(csvPath))
if (args.Length > 1 && !string.IsNullOrWhiteSpace(args[1]))
{
// Simple CSV parsing: each line's first column is taken as the barcode value.
foreach (var line in File.ReadAllLines(csvPath))
{
if (string.IsNullOrWhiteSpace(line))
continue;

// Split by comma and trim whitespace.
var parts = line.Split(',');
if (parts.Length > 0)
{
var code = parts[0].Trim();
if (!string.IsNullOrEmpty(code))
codeTexts.Add(code);
}
}
outputFolder = args[1];
}
else

// Verify that the CSV file exists before proceeding
if (!File.Exists(csvPath))
{
// Fallback sample data (safe size for demonstration).
codeTexts.AddRange(new[]
{
"CODE39A",
"12345",
"HELLO-WORLD",
"ASP.NET",
"BARCODE"
});
Console.WriteLine($"CSV file not found: {csvPath}");
return;
}

// Generate a Code39 barcode for each code text and save as SVG.
foreach (var codeText in codeTexts)
// Ensure the output directory exists (creates it if necessary)
Directory.CreateDirectory(outputFolder);

// Read all lines from the CSV file
string[] lines = File.ReadAllLines(csvPath);
foreach (string line in lines)
{
// File name is sanitized to avoid invalid path characters.
var safeFileName = GetSafeFileName(codeText);
var outputPath = Path.Combine(outputDir, safeFileName + ".svg");
// Skip empty or whitespace‑only lines
if (string.IsNullOrWhiteSpace(line))
continue;

// Assume the first column contains the Code39 value
string[] parts = line.Split(',');
string codeText = parts[0].Trim();

// Skip lines where the first column is empty
if (string.IsNullOrEmpty(codeText))
continue;

// Build a safe file name for the SVG output
string safeFileName = GetSafeFileName(codeText) + ".svg";
string outputPath = Path.Combine(outputFolder, safeFileName);

// Create a barcode generator for Code39 with the current text.
// Generate the Code39 barcode and save it directly as SVG
using (var generator = new BarcodeGenerator(EncodeTypes.Code39, codeText))
{
// Save directly as SVG.
// Do not throw if the code text contains minor issues (e.g., unsupported characters)
generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false;

// Save the barcode image in SVG format
generator.Save(outputPath, BarCodeImageFormat.Svg);
}

Console.WriteLine($"Generated barcode for '{codeText}' -> {outputPath}");
Console.WriteLine($"Generated: {outputPath}");
}
}

// Replaces characters that are invalid in file names with an underscore.
/// <summary>
/// Replaces characters that are invalid in file names with an underscore,
/// ensuring the generated file name is safe for the file system.
/// </summary>
/// <param name="name">Original file name derived from the barcode text.</param>
/// <returns>A sanitized file name with invalid characters replaced.</returns>
private static string GetSafeFileName(string name)
{
foreach (char c in Path.GetInvalidFileNameChars())
Expand Down
Original file line number Diff line number Diff line change
@@ -1,97 +1,128 @@
// Title: Batch barcode overlay on images
// Description: Demonstrates loading up to five images, generating a Code128 barcode, overlaying it on each image, and saving the result as BMP files.
// Description: Demonstrates how to batch‑process image files, overlay each with a generated Code128 barcode derived from the file name, and save the result as BMP.
// Category-Description: This example belongs to the Aspose.BarCode image manipulation category, illustrating the use of BarcodeGenerator, BarCodeImageFormat, and Aspose.Drawing classes to create barcodes, render them to streams, and composite them onto existing images. Typical use cases include watermarking product photos with SKU barcodes or adding machine‑readable identifiers to documents. Developers often need to automate such batch operations for inventory, labeling, or archival workflows.
// Prompt: Batch process image files, overlay each with a generated barcode, and save the results as BMP.
// Tags: barcode, code128, overlay, batch, bmp, aspose.barcode, aspose.drawing
// Tags: barcode, code128, overlay, batch, bmp, aspose.barcode, aspose.drawing, image-processing

using System;
using System.IO;
using System.Linq;
using Aspose.BarCode;
using Aspose.BarCode.Generation;
using Aspose.Drawing;
using Aspose.Drawing.Imaging;

/// <summary>
/// Example program that processes a set of image files, adds a generated barcode to each,
/// and saves the combined image as a BMP file.
/// Example program that batch processes images, overlays each with a generated barcode,
/// and saves the combined result as a BMP file.
/// </summary>
class Program
{
/// <summary>
/// Entry point of the application. Performs batch processing of images with barcode overlay.
/// Entry point of the application. Performs folder setup, sample image creation,
/// barcode generation, image compositing, and output saving.
/// </summary>
static void Main()
{
// Define input and output directories (adjust paths as needed)
string inputDir = "input_images";
string outputDir = "output_images";
// Define input and output folders relative to the current directory
string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "input_images");
string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "output_images");

// Ensure the output directory exists; create it if it does not
if (!Directory.Exists(outputDir))
{
Directory.CreateDirectory(outputDir);
}
// Ensure the input and output directories exist
Directory.CreateDirectory(inputFolder);
Directory.CreateDirectory(outputFolder);

// Verify that the input directory exists before proceeding
if (!Directory.Exists(inputDir))
// Prepare sample images if the input folder is empty (self‑contained example)
string[] samplePatterns = new[] { "*.png", "*.jpg", "*.bmp" };
bool anyImageExists = false;
foreach (var pattern in samplePatterns)
{
Console.WriteLine($"Input directory not found: {inputDir}");
return;
if (Directory.GetFiles(inputFolder, pattern).Length > 0)
{
anyImageExists = true;
break;
}
}

// Retrieve up to five image files with supported extensions from the input directory
string[] files = Directory.GetFiles(inputDir, "*.*")
.Where(f => f.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase) ||
f.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) ||
f.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase) ||
f.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
f.EndsWith(".gif", StringComparison.OrdinalIgnoreCase))
.Take(5)
.ToArray();

// If no images were found, inform the user and exit
if (files.Length == 0)
if (!anyImageExists)
{
Console.WriteLine("No image files found to process.");
return;
// Create 5 simple placeholder images
for (int i = 1; i <= 5; i++)
{
string samplePath = Path.Combine(inputFolder, $"sample{i}.png");
using (var bmp = new Bitmap(300, 200))
{
using (var g = Graphics.FromImage(bmp))
{
g.Clear(Color.LightGray);
g.DrawString($"Sample {i}", new Font("Arial", 24f), new SolidBrush(Color.Black), new PointF(50f, 80f));
}
bmp.Save(samplePath, ImageFormat.Png);
}
}
}

// Process each image file individually
foreach (string filePath in files)
// Iterate over each supported image pattern
foreach (var pattern in samplePatterns)
{
// Derive the output file name by appending "_barcode" and changing the extension to BMP
string fileName = Path.GetFileNameWithoutExtension(filePath);
string outputPath = Path.Combine(outputDir, $"{fileName}_barcode.bmp");

// Load the original image from disk
using (Image baseImage = Image.FromFile(filePath))
// Process every file that matches the current pattern
foreach (var imagePath in Directory.GetFiles(inputFolder, pattern))
{
// Create a barcode generator for Code128 with sample text
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
try
{
// Optional: configure barcode size and scaling mode
generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation;
generator.Parameters.ImageWidth.Point = 200f; // Desired barcode width
generator.Parameters.ImageHeight.Point = 80f; // Desired barcode height

// Generate the barcode as a bitmap image
using (Bitmap barcodeBitmap = generator.GenerateBarCodeImage())
// Load the original image from disk
using (var original = (Bitmap)Image.FromFile(imagePath))
{
// Draw the barcode onto the base image using graphics context
using (Graphics graphics = Graphics.FromImage(baseImage))
// Use the file name (without extension) as the barcode text
string codeText = Path.GetFileNameWithoutExtension(imagePath);

// Create a Code128 barcode generator
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
{
// Position the barcode at the bottom‑right corner with a 10‑pixel margin
int x = baseImage.Width - barcodeBitmap.Width - 10;
int y = baseImage.Height - barcodeBitmap.Height - 10;
graphics.DrawImage(barcodeBitmap, x, y, barcodeBitmap.Width, barcodeBitmap.Height);
// Optional: adjust the module size for better readability
generator.Parameters.Barcode.XDimension.Point = 2f;

// Render the barcode to a memory stream in PNG format
using (var barcodeStream = new MemoryStream())
{
generator.Save(barcodeStream, BarCodeImageFormat.Png);
barcodeStream.Position = 0;

// Load the rendered barcode image from the stream
using (var barcodeImage = (Bitmap)Image.FromStream(barcodeStream))
{
// Calculate bottom‑right position with a 10‑pixel margin
int margin = 10;
int xPos = original.Width - barcodeImage.Width - margin;
int yPos = original.Height - barcodeImage.Height - margin;
if (xPos < 0) xPos = 0;
if (yPos < 0) yPos = 0;

// Draw the barcode onto the original image
using (var graphics = Graphics.FromImage(original))
{
graphics.DrawImage(barcodeImage, xPos, yPos, barcodeImage.Width, barcodeImage.Height);
}
}
}
}

// Save the combined image as a BMP file
baseImage.Save(outputPath, ImageFormat.Bmp);
// Build the output file name and path
string outputFileName = Path.GetFileNameWithoutExtension(imagePath) + "_with_barcode.bmp";
string outputPath = Path.Combine(outputFolder, outputFileName);

// Save the combined image as BMP
original.Save(outputPath, ImageFormat.Bmp);
Console.WriteLine($"Processed and saved: {outputPath}");
}
}
catch (Exception ex)
{
// Log any errors that occur during processing of a single file
Console.WriteLine($"Error processing '{imagePath}': {ex.Message}");
}
}
}

Console.WriteLine("Batch processing completed.");
}
}
Loading
Loading