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,81 +1,99 @@
// 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.
// 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

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

/// <summary>
/// Demonstrates performance measurement of Aspose.BarCode ExportToXml using file path and stream overloads.
/// 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>.
/// </summary>
class Program
{
/// <summary>
/// Entry point of the application. Generates a set of barcode samples and measures the time taken
/// to export them to XML via file path and memory stream overloads.
/// 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.
/// </summary>
/// <param name="args">Command‑line arguments (not used).</param>
static void Main(string[] args)
static void Main()
{
// Number of barcode samples (small safe size for the runner)
const int sampleCount = 5;

// Temporary directory for XML files
string tempDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodeExport");
Directory.CreateDirectory(tempDir);

// ------------------------------------------------------------
// Measure ExportToXml using the file‑path overload
// ------------------------------------------------------------
Stopwatch fileTimer = Stopwatch.StartNew();
for (int i = 0; i < sampleCount; i++)
// Prepare a temporary directory for XML files
string tempDir = Path.Combine(Path.GetTempPath(), "AsposeBarcodeExportDemo");
if (!Directory.Exists(tempDir))
{
// Create a barcode generator for each sample.
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i}"))
{
// Build the full path for the XML file
string xmlPath = Path.Combine(tempDir, $"barcode{i}.xml");
// Export the barcode definition to the specified file
generator.ExportToXml(xmlPath);
}
Directory.CreateDirectory(tempDir);
}
fileTimer.Stop();

// ------------------------------------------------------------
// Measure ExportToXml using the stream overload
// ------------------------------------------------------------
Stopwatch streamTimer = Stopwatch.StartNew();
for (int i = 0; i < sampleCount; i++)
// Sample barcode texts (small batch for safe execution)
List<string> sampleTexts = new List<string>
{
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i}"))
"ABC123456",
"9876543210",
"TestCode128",
"12345ABCDE",
"ZXCVBNM123"
};

// 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++)
{
string codeText = sampleTexts[i];

// Create a BarcodeGenerator instance for the current text
using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
{
// Export to a memory stream (no file system I/O)
using (var ms = new MemoryStream())
// 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);

// Export to XML stream and measure time
using (MemoryStream ms = new MemoryStream())
{
generator.ExportToXml(ms);
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}.");
}
}
}
streamTimer.Stop();

// Output timing results
Console.WriteLine($"Export to file path total time: {fileTimer.ElapsedMilliseconds} ms");
Console.WriteLine($"Export to stream total time: {streamTimer.ElapsedMilliseconds} ms");
// Output timing comparison
Console.WriteLine("Performance comparison of ExportToXml (file path vs stream):");
for (int i = 0; i < sampleTexts.Count; i++)
{
Console.WriteLine($"Item {i + 1}: File = {fileTimes[i].TotalMilliseconds} ms, Stream = {streamTimes[i].TotalMilliseconds} ms");
}

// ------------------------------------------------------------
// Cleanup temporary files and directory
// ------------------------------------------------------------
// Clean up temporary XML files
try
{
// Delete each generated XML file
foreach (var file in Directory.GetFiles(tempDir, "*.xml"))
foreach (string file in Directory.GetFiles(tempDir, "*.xml"))
{
File.Delete(file);

// Remove the temporary directory itself
}
Directory.Delete(tempDir);
}
catch
{
// Ignored - cleanup is best effort.
// If cleanup fails, ignore – not critical for the demo
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,93 +1,82 @@
// 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.
// 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

using System;
using System.Globalization;
using System.IO;
using System.Xml;
using Aspose.BarCode;
using Aspose.BarCode.BarCodeRecognition;

/// <summary>
/// Demonstrates reading barcodes from images and exporting the results to XML files.
/// 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.
/// </summary>
class Program
{
/// <summary>
/// Entry point of the application. Processes a set of sample images,
/// extracts barcode information, and writes the data to XML files.
/// 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.
/// </summary>
static void Main()
{
// Define sample image file paths (replace with actual paths as needed)
string[] imagePaths = new string[]
// Define the list of image files to be processed.
// Adjust the file paths as needed for your environment.
string[] imageFiles = new string[]
{
"sample1.png",
"sample2.png",
"sample3.png"
"image1.png",
"image2.png",
"image3.png",
"image4.png",
"image5.png"
};

// Ensure the output directory exists; create it if it does not
string outputDir = "output";
if (!Directory.Exists(outputDir))
{
Directory.CreateDirectory(outputDir);
}

// Process each image file individually
foreach (string imagePath in imagePaths)
// Process each image file in the list.
foreach (string imagePath in imageFiles)
{
// Skip processing if the file cannot be found
// 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, supporting all barcode types
// Initialize a barcode reader for the current image,
// configured to detect all supported barcode types.
using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
// Read all barcodes present in the image
var results = reader.ReadBarCodes();
int barcodeIndex = 0; // Counter for naming XML files uniquely per image.

// Determine the XML output file name based on the image name
string xmlFileName = Path.GetFileNameWithoutExtension(imagePath) + ".xml";
string xmlPath = Path.Combine(outputDir, xmlFileName);

// Write the barcode data to an XML file with indentation for readability
using (var writer = XmlWriter.Create(xmlPath, new XmlWriterSettings { Indent = true }))
// Iterate over all detected barcodes in the image.
foreach (var result in reader.ReadBarCodes())
{
writer.WriteStartDocument(); // XML declaration
writer.WriteStartElement("Barcodes"); // Root element
writer.WriteAttributeString("SourceImage", Path.GetFileName(imagePath));
// Construct the XML file name using the image name and barcode index.
string xmlFileName = $"{Path.GetFileNameWithoutExtension(imagePath)}_{barcodeIndex}.xml";

// Iterate over each detected barcode and write its details
foreach (var result in results)
// Create an XML writer with indentation for readability.
using (var writer = XmlWriter.Create(xmlFileName, new XmlWriterSettings { Indent = true }))
{
writer.WriteStartDocument();
writer.WriteStartElement("BarCode");

// Write barcode type and text elements, handling possible null values.
writer.WriteElementString("Type", result.CodeTypeName ?? string.Empty);
writer.WriteElementString("CodeText", result.CodeText ?? string.Empty);
writer.WriteElementString("Confidence", result.Confidence.ToString());
writer.WriteElementString(
"ReadingQuality",
result.ReadingQuality.ToString(CultureInfo.InvariantCulture));

// Write the region (bounding rectangle) of the barcode
var rect = result.Region.Rectangle;
writer.WriteStartElement("Region");
writer.WriteElementString("X", rect.X.ToString(CultureInfo.InvariantCulture));
writer.WriteElementString("Y", rect.Y.ToString(CultureInfo.InvariantCulture));
writer.WriteElementString("Width", rect.Width.ToString(CultureInfo.InvariantCulture));
writer.WriteElementString("Height", rect.Height.ToString(CultureInfo.InvariantCulture));
writer.WriteEndElement(); // </Region>

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

writer.WriteEndElement(); // </Barcodes>
writer.WriteEndDocument(); // End of XML document
Console.WriteLine($"Processed barcode {barcodeIndex} from '{imagePath}' -> '{xmlFileName}'");
barcodeIndex++;
}

// Inform the user that processing for the current image is complete
Console.WriteLine($"Processed '{imagePath}' -> '{xmlPath}'");
// If no barcodes were detected, inform the user.
if (barcodeIndex == 0)
{
Console.WriteLine($"No barcodes detected in '{imagePath}'.");
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,61 +1,83 @@
// Title: Barcode Detection and XML Export
// Description: Detects all barcodes in an image file and writes their type and text to an XML document.
// Prompt: Create a console app that accepts an image path, detects barcodes, and writes state to an XML file.
// Tags: barcode, detection, xml, console, aspose.barcoderecognition

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

/// <summary>
/// Reads barcodes from an image file and writes the detection results to an XML document.
/// Demonstrates how to read barcodes from an image and export the results to an XML file.
/// </summary>
class Program
{
/// <summary>
/// Application entry point.
/// Entry point of the console application.
/// Accepts an optional image path argument, detects barcodes, and writes the results to an XML file.
/// </summary>
/// <param name="args">Command‑line arguments; the first argument may specify the image file path.</param>
/// <param name="args">Command‑line arguments; the first argument may be the image file path.</param>
static void Main(string[] args)
{
// Determine the image path: use the first command‑line argument if supplied,
// otherwise fall back to a default sample image.
// Determine image path from command‑line or use a default sample.
string imagePath = args.Length > 0 ? args[0] : "sample.png";

// Verify that the specified image file exists before proceeding.
// Verify that the image file exists before proceeding.
if (!File.Exists(imagePath))
{
Console.WriteLine($"File not found: {imagePath}");
Console.WriteLine($"Image file not found: {imagePath}");
return;
}

// Define the output XML file path where barcode information will be saved.
string xmlPath = "Barcodes.xml";
// Prepare the output XML file path by changing the image extension to .xml.
string xmlPath = Path.ChangeExtension(imagePath, ".xml");

// Create a BarCodeReader that attempts to decode all supported barcode types.
using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
// Configure the XML writer to produce indented, human‑readable output.
XmlWriterSettings settings = new XmlWriterSettings
{
// Perform the barcode recognition and obtain an array of results.
BarCodeResult[] results = reader.ReadBarCodes();
Indent = true,
IndentChars = " "
};

// Write the detection results to an XML file with indentation for readability.
using (var writer = XmlWriter.Create(xmlPath, new XmlWriterSettings { Indent = true }))
{
writer.WriteStartDocument(); // Begin the XML document.
writer.WriteStartElement("Barcodes"); // Root element.
// Open the XML writer within a using block to ensure proper disposal.
using (XmlWriter writer = XmlWriter.Create(xmlPath, settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("Barcodes");

// Iterate over each detected barcode and write its details as an element.
foreach (var result in results)
// Initialize the barcode reader to detect all supported barcode types.
using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
// Iterate through each detected barcode in the image.
foreach (var result in reader.ReadBarCodes())
{
writer.WriteStartElement("BarCode");
writer.WriteAttributeString("Type", result.CodeTypeName ?? string.Empty);
writer.WriteAttributeString("CodeText", result.CodeText ?? string.Empty);

// Write the barcode type name (e.g., QR, Code128).
writer.WriteElementString("Type", result.CodeTypeName ?? string.Empty);

// Write the decoded text/value of the barcode.
writer.WriteElementString("CodeText", result.CodeText ?? string.Empty);

// Optional: write the region bounds of the barcode if needed.
// var rect = result.Region.Rectangle;
// writer.WriteStartElement("Region");
// writer.WriteElementString("X", rect.X.ToString());
// writer.WriteElementString("Y", rect.Y.ToString());
// writer.WriteElementString("Width", rect.Width.ToString());
// writer.WriteElementString("Height", rect.Height.ToString());
// writer.WriteEndElement(); // Region

writer.WriteEndElement(); // BarCode
}

writer.WriteEndElement(); // Barcodes
writer.WriteEndDocument(); // End of XML document.
}

// Inform the user about the number of barcodes detected and the output location.
Console.WriteLine($"Detected {results.Length} barcode(s). Results written to {xmlPath}.");
writer.WriteEndElement(); // Barcodes
writer.WriteEndDocument();
}

// Inform the user that processing is complete and provide the XML file location.
Console.WriteLine($"Barcode detection completed. Results saved to: {xmlPath}");
}
}
Loading
Loading