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,99 +1,80 @@
// Title: ExportToXml Performance Comparison: File Path vs Stream
// Description: Demonstrates measuring the execution time of Aspose.BarCode's ExportToXml method when writing to a file versus a memory stream for a batch of barcode images.
// Title: Compare ExportToXml performance: file path vs stream overload
// Description: Demonstrates measuring execution time of Aspose.BarCode ExportToXml using a file path and a stream for a batch of barcodes.
// Category-Description: This example belongs to the Aspose.BarCode generation and serialization category, showcasing how to serialize generated barcodes to XML using the ExportToXml API. It highlights key classes such as BarcodeGenerator, EncodeTypes, and the ExportToXml overloads, which developers commonly use when persisting barcode data for later processing or integration with other systems.
// Prompt: Compare performance of ExportToXml using file path versus stream overload for large barcode image batches.
// Tags: code128, export, xml, performance, aspose.barcode, stream, file
// Tags: barcode, export, xml, performance, file-path, stream, aspose.barcode, code128, generation

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

/// <summary>
/// Provides a simple benchmark that compares the time required to export barcode data to XML
/// using the file‑path overload versus the stream overload of <c>BarcodeGenerator.ExportToXml</c>.
/// Demonstrates performance comparison between ExportToXml overloads (file path vs stream) for a batch of Code128 barcodes.
/// </summary>
class Program
{
/// <summary>
/// Entry point of the demo. Generates a small set of barcodes, exports each to XML
/// using both overloads, records the elapsed time, and prints a side‑by‑side comparison.
/// Entry point. Generates a set of barcodes, exports each to XML using both overloads, and reports elapsed time.
/// </summary>
static void Main()
{
// Prepare a temporary directory for XML files
string tempDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodeExportDemo");
if (!Directory.Exists(tempDir))
{
Directory.CreateDirectory(tempDir);
}
const int batchSize = 5; // safe sample size for demonstration

// Sample barcode texts (small batch for safe execution)
List<string> sampleTexts = new List<string>
{
"ABC123456",
"9876543210",
"TestCode128",
"12345ABCDE",
"ZXCVBNM123"
};
// Prepare output directory for generated XML files
string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "ExportXmlDemo");
Directory.CreateDirectory(outputDir);

// Store timing results for each overload
List<TimeSpan> fileTimes = new List<TimeSpan>();
List<TimeSpan> streamTimes = new List<TimeSpan>();

// Iterate over each barcode text
for (int i = 0; i < sampleTexts.Count; i++)
// ------------------------------------------------------------
// Measure performance of ExportToXml(string) overload
// ------------------------------------------------------------
var swPath = Stopwatch.StartNew();
for (int i = 1; i <= batchSize; i++)
{
string codeText = sampleTexts[i];

// Create a BarcodeGenerator instance for the current text
using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
// Create a barcode generator for Code128 with a unique value
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i:D4}"))
{
// Export to XML file and measure time
string xmlFilePath = Path.Combine(tempDir, $"barcode_{i}.xml");
Stopwatch swFile = Stopwatch.StartNew();
bool fileResult = generator.ExportToXml(xmlFilePath);
swFile.Stop();
fileTimes.Add(swFile.Elapsed);
// Define XML file path for this barcode
string xmlPath = Path.Combine(outputDir, $"barcode_path_{i}.xml");

// Export to XML stream and measure time
using (MemoryStream ms = new MemoryStream())
// Export barcode to XML file; check success
bool success = generator.ExportToXml(xmlPath);
if (!success)
{
Stopwatch swStream = Stopwatch.StartNew();
bool streamResult = generator.ExportToXml(ms);
swStream.Stop();
streamTimes.Add(swStream.Elapsed);
}

// Optional: verify export success (not required for timing)
if (!fileResult)
{
Console.WriteLine($"Export to file failed for index {i}.");
Console.WriteLine($"Export to file failed for item {i}");
}
}
}
swPath.Stop();

// Output timing comparison
Console.WriteLine("Performance comparison of ExportToXml (file path vs stream):");
for (int i = 0; i < sampleTexts.Count; i++)
// ------------------------------------------------------------
// Measure performance of ExportToXml(Stream) overload
// ------------------------------------------------------------
var swStream = Stopwatch.StartNew();
for (int i = 1; i <= batchSize; i++)
{
Console.WriteLine($"Item {i + 1}: File = {fileTimes[i].TotalMilliseconds} ms, Stream = {streamTimes[i].TotalMilliseconds} ms");
}

// Clean up temporary XML files
try
{
foreach (string file in Directory.GetFiles(tempDir, "*.xml"))
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i:D4}"))
{
File.Delete(file);
// Define XML file path for this barcode
string xmlPath = Path.Combine(outputDir, $"barcode_stream_{i}.xml");

// Open a file stream for writing the XML
using (var fileStream = new FileStream(xmlPath, FileMode.Create, FileAccess.Write))
{
// Export barcode to the provided stream; check success
bool success = generator.ExportToXml(fileStream);
if (!success)
{
Console.WriteLine($"Export to stream failed for item {i}");
}
}
}
Directory.Delete(tempDir);
}
catch
{
// If cleanup fails, ignore – not critical for the demo
}
swStream.Stop();

// Output timing results for both overloads
Console.WriteLine($"ExportToXml(string) total time for {batchSize} items: {swPath.ElapsedMilliseconds} ms");
Console.WriteLine($"ExportToXml(Stream) total time for {batchSize} items: {swStream.ElapsedMilliseconds} ms");
}
}
Original file line number Diff line number Diff line change
@@ -1,82 +1,108 @@
// Title: Batch barcode extraction to XML
// Description: Demonstrates reading multiple image files, extracting any barcodes found, and writing each barcode's details to a separate XML file.
// Description: Demonstrates reading multiple images, extracting all supported barcodes, and saving each result to an XML file per image.
// Category-Description: This example belongs to the Aspose.BarCode recognition category, showing how to use BarCodeReader with DecodeType.AllSupportedTypes, XmlWriter, and BarcodeGenerator for sample data. Developers often need to process batches of images, extract barcode information, and store results in structured formats such as XML for downstream systems.
// Prompt: Create a batch process that reads multiple images, extracts barcodes, and writes each state to separate XML files.
// Tags: barcode, batch, xml, aspose.barcode, barcodereader
// Tags: barcode recognition, batch processing, xml output, decodeall, aspose.barcode, csharp

using System;
using System.IO;
using System.Xml;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;

/// <summary>
/// Example program that processes a collection of image files,
/// extracts all detected barcodes, and writes each barcode's
/// type and text to an individual XML file.
/// Demonstrates batch processing of barcode images: generating sample barcodes, reading them, and writing results to XML files.
/// </summary>
class Program
{
/// <summary>
/// Entry point of the application. Iterates over a predefined list of image paths,
/// reads barcodes using Aspose.BarCode, and generates XML files for each barcode found.
/// Entry point. Generates sample barcodes, processes each image, extracts barcodes, and writes XML output.
/// </summary>
static void Main()
{
// Define the list of image files to be processed.
// Adjust the file paths as needed for your environment.
string[] imageFiles = new string[]
// Define working folder for generated and processed files
string workFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
if (!Directory.Exists(workFolder))
{
"image1.png",
"image2.png",
"image3.png",
"image4.png",
"image5.png"
};
Directory.CreateDirectory(workFolder);
}

// -----------------------------------------------------------------
// Step 1: Generate a few sample barcode images (self‑contained demo)
// -----------------------------------------------------------------
GenerateSampleBarcodes(workFolder);

// Process each image file in the list.
// -----------------------------------------------------------------
// Step 2: Process each image, extract barcodes and write XML files
// -----------------------------------------------------------------
string[] imageFiles = Directory.GetFiles(workFolder, "*.png");
foreach (string imagePath in imageFiles)
{
// Verify that the file exists before attempting to read it.
if (!File.Exists(imagePath))
{
Console.WriteLine($"File not found: {imagePath}");
continue;
}

// Initialize a barcode reader for the current image,
// configured to detect all supported barcode types.
using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
// Prepare XML writer for the output file (same name, .xml extension)
string xmlPath = Path.ChangeExtension(imagePath, ".xml");
using (XmlWriter writer = XmlWriter.Create(xmlPath, new XmlWriterSettings { Indent = true }))
{
int barcodeIndex = 0; // Counter for naming XML files uniquely per image.
writer.WriteStartDocument();
writer.WriteStartElement("Barcodes");

// Iterate over all detected barcodes in the image.
foreach (var result in reader.ReadBarCodes())
// Read all supported barcodes from the current image
using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
// Construct the XML file name using the image name and barcode index.
string xmlFileName = $"{Path.GetFileNameWithoutExtension(imagePath)}_{barcodeIndex}.xml";

// Create an XML writer with indentation for readability.
using (var writer = XmlWriter.Create(xmlFileName, new XmlWriterSettings { Indent = true }))
foreach (var result in reader.ReadBarCodes())
{
writer.WriteStartDocument();
writer.WriteStartElement("BarCode");
writer.WriteAttributeString("Type", result.CodeTypeName);
writer.WriteAttributeString("CodeText", result.CodeText ?? string.Empty);

// Write barcode type and text elements, handling possible null values.
writer.WriteElementString("Type", result.CodeTypeName ?? string.Empty);
writer.WriteElementString("CodeText", result.CodeText ?? string.Empty);
// Include region information if available
if (result.Region != null)
{
var rect = result.Region.Rectangle;
writer.WriteAttributeString("X", rect.X.ToString());
writer.WriteAttributeString("Y", rect.Y.ToString());
writer.WriteAttributeString("Width", rect.Width.ToString());
writer.WriteAttributeString("Height", rect.Height.ToString());
}

writer.WriteEndElement(); // </BarCode>
writer.WriteEndDocument();
writer.WriteEndElement(); // BarCode
}

Console.WriteLine($"Processed barcode {barcodeIndex} from '{imagePath}' -> '{xmlFileName}'");
barcodeIndex++;
}

// If no barcodes were detected, inform the user.
if (barcodeIndex == 0)
{
Console.WriteLine($"No barcodes detected in '{imagePath}'.");
}
writer.WriteEndElement(); // Barcodes
writer.WriteEndDocument();
}

Console.WriteLine($"Processed '{Path.GetFileName(imagePath)}' -> '{Path.GetFileName(xmlPath)}'");
}

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

// Generates a small set of sample barcode images in the specified folder.
private static void GenerateSampleBarcodes(string folder)
{
// Sample data: (symbology, text, file name)
var samples = new (BaseEncodeType encode, string text, string file)[]
{
(EncodeTypes.Code128, "Sample123", "code128.png"),
(EncodeTypes.QR, "https://example.com", "qr.png"),
(EncodeTypes.DataMatrix, "DM12345", "datamatrix.png")
};

foreach (var (encode, text, file) in samples)
{
string path = Path.Combine(folder, file);
using (var generator = new BarcodeGenerator(encode, text))
{
// Simple settings – default size and colors are fine for the demo
generator.Save(path, BarCodeImageFormat.Png);
}
}
}
Expand Down
Loading
Loading