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,78 +1,88 @@
// Title: DataMatrix ReadingQuality extraction and CSV storage
// Description: Demonstrates how to read the ReadingQuality property of each DataMatrix barcode and store the values in a CSV file (as a placeholder for a database).
// Title: Access DataMatrix ReadingQuality and store results
// Description: Demonstrates generating DataMatrix barcodes, reading their ReadingQuality property, and persisting the values.
// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showing how to use BarcodeGenerator, BarCodeReader, and BarCodeResult to evaluate barcode quality. Typical use cases include quality assessment for scanning devices, database logging, and automated testing. Developers often need to extract metrics like ReadingQuality for each barcode and store them for analysis.
// Prompt: Access BarCodeResult.ReadingQuality for each DataMatrix barcode and store the numeric value in a database.
// Tags: datamatrix, readingquality, csv, aspose.barcode, barcode, data extraction, database
// Tags: datamatrix, readingquality, barcode, generation, recognition, csv, database

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

/// <summary>
/// Demonstrates extracting ReadingQuality from DataMatrix barcodes and persisting the values.
/// Generates sample DataMatrix barcodes, reads their <c>ReadingQuality</c> values,
/// and writes the results to a CSV file (placeholder for database storage).
/// </summary>
class Program
{
/// <summary>
/// Generates a sample DataMatrix barcode, reads its ReadingQuality, and writes the results to a CSV file.
/// Entry point of the example. Executes barcode generation, quality extraction,
/// and result persistence.
/// </summary>
static void Main()
{
// Path for the temporary barcode image
const string imagePath = "datamatrix.png";
// Path for the CSV file that will store the reading quality values
const string csvPath = "reading_quality.csv";
// Define sample data for barcode generation.
var samples = new List<(string Text, string FileName)>
{
("Hello", "datamatrix1.png"),
("1234567890", "datamatrix2.png")
};

// Generate a sample DataMatrix barcode image
using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "SampleDataMatrix123"))
// --------------------------------------------------------------------
// Generate DataMatrix barcode images and save them as PNG files.
// --------------------------------------------------------------------
foreach (var sample in samples)
{
// Save the generated barcode to a PNG file
generator.Save(imagePath, BarCodeImageFormat.Png);
using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, sample.Text))
{
// Save the generated barcode image.
generator.Save(sample.FileName);
}
}

// List to hold reading quality information for each detected barcode
var qualities = new List<(int Index, string CodeText, double ReadingQuality)>();
// Prepare a collection to hold filename and reading quality pairs.
var results = new List<(string FileName, double ReadingQuality)>();

// Read the barcode(s) from the image using a DataMatrix decoder
using (var reader = new BarCodeReader(imagePath, DecodeType.DataMatrix))
// --------------------------------------------------------------------
// Read each generated image, decode DataMatrix barcodes, and capture
// the ReadingQuality metric from the BarCodeResult.
// --------------------------------------------------------------------
foreach (var sample in samples)
{
int index = 0;
foreach (var result in reader.ReadBarCodes())
if (!File.Exists(sample.FileName))
{
// Process only DataMatrix barcodes (additional safety check)
if (result.CodeTypeName.Equals("DataMatrix", StringComparison.OrdinalIgnoreCase))
Console.WriteLine($"File not found: {sample.FileName}");
continue;
}

using (var reader = new BarCodeReader(sample.FileName, DecodeType.DataMatrix))
{
foreach (var result in reader.ReadBarCodes())
{
// Retrieve the ReadingQuality value (double) from the result
double readingQuality = result.ReadingQuality;
// Store the index, decoded text, and quality in the list
qualities.Add((index, result.CodeText, readingQuality));
// Output the information to the console for verification
Console.WriteLine($"Detected DataMatrix #{index}: CodeText=\"{result.CodeText}\", ReadingQuality={readingQuality}");
index++;
// Verify that the detected barcode is a DataMatrix type.
if (result.CodeTypeName.Equals("DataMatrix", StringComparison.OrdinalIgnoreCase))
{
results.Add((sample.FileName, result.ReadingQuality));
}
}
}
}

// Store the results in a CSV file (as a stand‑in for a real database)
using (var writer = new StreamWriter(csvPath))
// --------------------------------------------------------------------
// Persist the collected reading quality data.
// In a production scenario, replace this CSV write with database insertion.
// --------------------------------------------------------------------
const string csvPath = "datamatrix_reading_quality.csv";
using (var writer = new StreamWriter(csvPath, false))
{
// Write CSV header
writer.WriteLine("Index,CodeText,ReadingQuality");
// Write each record
foreach (var item in qualities)
writer.WriteLine("FileName,ReadingQuality");
foreach (var entry in results)
{
writer.WriteLine($"{item.Index},\"{item.CodeText}\",{item.ReadingQuality}");
writer.WriteLine($"{entry.FileName},{entry.ReadingQuality}");
}
}

Console.WriteLine($"Reading quality data saved to \"{csvPath}\".");

// NOTE:
// In a production scenario you would insert the values into a database
// (e.g., using ADO.NET, Entity Framework, Dapper, etc.). The database
// code is omitted here because the required NuGet packages are not
// available in the snippet runner environment.
Console.WriteLine($"Reading quality data saved to '{csvPath}'.");
}
}
Original file line number Diff line number Diff line change
@@ -1,81 +1,84 @@
// Title: Barcode Generation, Recognition, and Position Reporting
// Description: Generates a Code128 barcode image, reads it back, counts unique barcodes, and prints their positions.
// Title: Count Unique Barcodes and Display Their Positions
// Description: Generates a Code128 barcode image, recognizes all barcodes in the image, counts unique entries, and prints each barcode's text with its location.
// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category. It demonstrates how to use BarcodeGenerator to create barcodes and BarCodeReader to detect them, covering typical use cases such as inventory scanning, document processing, and quality control where developers need to extract barcode data and spatial information from images.
// Prompt: Access FoundBarCodes collection after recognition to count unique barcodes and display their positions.
// Tags: code128, barcode generation, barcode recognition, unique count, position output, aspose.barcode
// Tags: code128, barcode recognition, console output, barcodelibrary, barcodelgeneration, barcoderecognition

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

/// <summary>
/// Demonstrates how to generate a barcode, recognize it, count unique values,
/// and display the position of each detected barcode using Aspose.BarCode.
/// Demonstrates barcode generation, recognition, unique count, and position reporting using Aspose.BarCode.
/// </summary>
class Program
{
/// <summary>
/// Entry point of the example. Generates a barcode image, reads it,
/// and outputs detection details to the console.
/// Entry point. Generates a barcode, reads it, counts unique codes, and prints their positions.
/// </summary>
static void Main()
{
// ------------------------------------------------------------
// Step 1: Generate a sample barcode image (Code128, text "ABC123")
// ------------------------------------------------------------
// Define a temporary file path for the generated barcode image.
string imagePath = "sample_barcode.png";

// Generate a Code128 barcode image with the text "ABC123".
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "ABC123"))
{
// Save the generated barcode as a PNG file
generator.Save(imagePath, BarCodeImageFormat.Png);
generator.Save(imagePath);
}

// ------------------------------------------------------------
// Step 2: Verify that the image file was created successfully
// ------------------------------------------------------------
// Verify that the image file was successfully created.
if (!File.Exists(imagePath))
{
Console.WriteLine("Failed to create barcode image.");
return;
}

// ------------------------------------------------------------
// Step 3: Read barcodes from the generated image
// ------------------------------------------------------------
// Initialize a barcode reader to detect all supported barcode types in the image.
using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
// Perform recognition of all supported barcode types
// Perform the recognition process.
reader.ReadBarCodes();

// --------------------------------------------------------
// Step 4: Access the FoundBarCodes collection
// --------------------------------------------------------
BarCodeResult[] results = reader.FoundBarCodes;
int totalCount = results.Length;
Console.WriteLine($"Total barcodes detected: {totalCount}");
// Retrieve the collection of detected barcodes.
var foundBarCodes = reader.FoundBarCodes;
int totalDetected = foundBarCodes?.Length ?? 0;
Console.WriteLine($"Total barcodes detected: {totalDetected}");

// --------------------------------------------------------
// Step 5: Count unique barcodes based on their CodeText
// --------------------------------------------------------
var uniqueSet = new HashSet<string>();
foreach (var result in results)
// Exit early if no barcodes were found.
if (totalDetected == 0)
{
uniqueSet.Add(result.CodeText);
return;
}
Console.WriteLine($"Unique barcodes count: {uniqueSet.Count}");

// --------------------------------------------------------
// Step 6: Display positions (region) of each detected barcode
// --------------------------------------------------------
for (int i = 0; i < totalCount; i++)
// Determine the number of unique barcodes based on their CodeText values.
var uniqueBarCodes = foundBarCodes
.GroupBy(r => r.CodeText)
.Select(g => g.First())
.ToArray();

Console.WriteLine($"Unique barcodes count: {uniqueBarCodes.Length}");

// Iterate through all detected barcodes and display their text and bounding rectangle.
foreach (var result in foundBarCodes)
{
var result = results[i];
var rect = result.Region.Rectangle;
Console.WriteLine(
$"Barcode {i + 1}: Text = '{result.CodeText}', Position = (X={rect.X}, Y={rect.Y}, Width={rect.Width}, Height={rect.Height})");
Console.WriteLine($"CodeText: {result.CodeText}");
Console.WriteLine($"Position - X:{rect.X}, Y:{rect.Y}, Width:{rect.Width}, Height:{rect.Height}");
Console.WriteLine();
}
}

// Clean up the temporary image file.
try
{
File.Delete(imagePath);
}
catch
{
// Suppress any exceptions that occur during cleanup.
}
}
}
Original file line number Diff line number Diff line change
@@ -1,96 +1,58 @@
// Title: Demonstrate checksum validation on mixed-symbology barcode image
// Description: Generates Code128 and EAN13 barcodes, combines them, and reads them using default checksum validation.
// Title: Enforce default checksum validation when reading mixed‑symbology barcodes
// Description: Demonstrates generating Code128 and EAN13 barcodes, then reading them with ChecksumValidation.Default to ensure proper checksum handling.
// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, showcasing how to configure checksum validation using the BarCodeReader and BarcodeSettings classes. Developers often need to read mixed‑symbology images while applying default checksum rules to filter out invalid codes. Typical use cases include inventory systems, point‑of‑sale scanners, and batch processing of barcode images.
// Prompt: Apply ChecksumValidation.Default to enforce default checksum handling when reading mixed‑symbology images.
// Tags: barcode symbology, checksum validation, mixed symbology, aspnet barcoderecognition, aspnet barcodelibrary
// Tags: barcode, checksumvalidation, default, mixed-symbology, generation, recognition, aspose.barcode, csharp

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

/// <summary>
/// Example program that generates barcodes, combines them, and reads them with default checksum validation.
/// Provides an example of generating barcodes and reading them with default checksum validation.
/// </summary>
class Program
{
/// <summary>
/// Entry point. Generates barcode images, merges them, and reads the combined image while applying default checksum validation.
/// Entry point that creates sample barcodes, saves them, and reads them applying default checksum validation.
/// </summary>
static void Main()
{
// Define output directory and ensure it exists
string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "output");
// Prepare the output directory for generated barcode images
string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
Directory.CreateDirectory(outputDir);

// Paths for individual and combined barcode images
string code128Path = Path.Combine(outputDir, "code128.png");
string ean13Path = Path.Combine(outputDir, "ean13.png");
string mixedPath = Path.Combine(outputDir, "mixed.png");

// Generate a Code128 barcode and save it as PNG
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "ABC123456"))
string code128Path = Path.Combine(outputDir, "code128.png");
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
generator.Save(code128Path, BarCodeImageFormat.Png);
generator.Save(code128Path);
}

// Generate an EAN13 barcode with a valid checksum and save it as PNG
// Generate an EAN13 barcode (including checksum digit) and save it as PNG
string ean13Path = Path.Combine(outputDir, "ean13.png");
using (var generator = new BarcodeGenerator(EncodeTypes.EAN13, "1234567890128"))
{
generator.Save(ean13Path, BarCodeImageFormat.Png);
generator.Save(ean13Path);
}

// Combine the two barcode images into a single image with spacing
using (var img1 = (Bitmap)Image.FromFile(code128Path))
using (var img2 = (Bitmap)Image.FromFile(ean13Path))
// Iterate over all generated PNG files and read them with default checksum validation
foreach (string filePath in Directory.GetFiles(outputDir, "*.png"))
{
int width = Math.Max(img1.Width, img2.Width);
int height = img1.Height + img2.Height + 20; // extra spacing between images

using (var combined = new Bitmap(width, height))
using (var reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
{
using (var graphics = Graphics.FromImage(combined))
{
// Fill background with white
graphics.Clear(Aspose.Drawing.Color.White);
// Draw the first barcode at the top
graphics.DrawImage(img1, 0, 0);
// Draw the second barcode below the first, with spacing
graphics.DrawImage(img2, 0, img1.Height + 20);
}
// Enforce default checksum handling for each read operation
reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.Default;

// Save the combined image
combined.Save(mixedPath, ImageFormat.Png);
}
}

// Verify that the combined image was created successfully
if (!File.Exists(mixedPath))
{
Console.WriteLine("Combined image not found.");
return;
}

// Read all supported barcodes from the combined image using default checksum validation
using (var reader = new BarCodeReader(mixedPath, DecodeType.AllSupportedTypes))
{
// Apply default checksum handling
reader.BarcodeSettings.ChecksumValidation = ChecksumValidation.Default;

// Iterate through detected barcodes and output details
foreach (var result in reader.ReadBarCodes())
{
Console.WriteLine($"Detected Type: {result.CodeTypeName}");
Console.WriteLine($"CodeText: {result.CodeText}");

// For 1D barcodes, display the checksum if it is available
if (result.Extended?.OneD?.CheckSum != null)
// Output each detected barcode's type and text
foreach (var result in reader.ReadBarCodes())
{
Console.WriteLine($"Checksum: {result.Extended.OneD.CheckSum}");
Console.WriteLine($"File: {Path.GetFileName(filePath)}");
Console.WriteLine($" Type: {result.CodeTypeName}");
Console.WriteLine($" CodeText: {result.CodeText}");
}

Console.WriteLine();
}
}
}
Expand Down
Loading
Loading