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,7 +1,8 @@
// Title: PDF417 barcode generation and linked segment detection
// Description: Demonstrates generating a PDF417 barcode with the IsLinked flag and reading the flag via extended parameters.
// Title: Access PDF417 Extended Parameters to Determine Linkage
// Description: Demonstrates how to set and read the IsLinked property of a PDF417 barcode using Aspose.BarCode.
// Category-Description: This example belongs to the Aspose.BarCode PDF417 barcode manipulation category, showcasing the use of BarcodeGenerator, BarCodeReader, and extended PDF417 parameters. Developers often need to control and verify segment linking for multi‑segment PDF417 codes in document processing and scanning solutions.
// Prompt: Access PDF417 extended parameters to check if the barcode is linked to another segment.
// Tags: pdf417, barcode, generation, recognition, extended-parameters, islinked
// Tags: pdf417, extended-parameters, islinked, barcode-generation, barcode-recognition, aspnet, csharp

using System;
using System.IO;
Expand All @@ -10,49 +11,49 @@
using Aspose.BarCode.BarCodeRecognition;

/// <summary>
/// Example program that generates a PDF417 barcode with the IsLinked flag and reads the flag using extended parameters.
/// Example program that creates a PDF417 barcode with the IsLinked flag set,
/// saves it as an image, and then reads the barcode to verify the flag using
/// Aspose.BarCode's extended PDF417 parameters.
/// </summary>
class Program
{
/// <summary>
/// Entry point. Generates a PDF417 barcode, saves it, and reads back the IsLinked property.
/// Entry point of the example. Generates a PDF417 barcode, saves it,
/// and reads back the IsLinked property from the extended parameters.
/// </summary>
static void Main()
{
// Define the text to encode in the barcode
const string codeText = "Sample PDF417 Text";
// Define the output file path for the generated barcode image.
string outputPath = "pdf417.png";

// Determine the output file path for the generated barcode image
string outputPath = Path.Combine(Environment.CurrentDirectory, "pdf417.png");

// Generate a PDF417 barcode and set the IsLinked flag to true
using (var generator = new BarcodeGenerator(EncodeTypes.Pdf417, codeText))
// Create a PDF417 barcode generator with sample text.
using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Sample PDF417 Text"))
{
// Enable linked mode for PDF417
// Enable the IsLinked flag to indicate this barcode is linked to another segment.
generator.Parameters.Barcode.Pdf417.IsLinked = true;

// Save the generated barcode as a PNG image
// Save the generated barcode as a PNG image.
generator.Save(outputPath, BarCodeImageFormat.Png);
}

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

// Initialize a reader to decode the PDF417 barcode from the saved image
using (var reader = new BarCodeReader(outputPath, DecodeType.Pdf417))
// Initialize a barcode reader for PDF417 type to read the saved image.
using (BarCodeReader reader = new BarCodeReader(outputPath, DecodeType.Pdf417))
{
// Iterate through all detected barcode results
// Iterate through all detected barcode results.
foreach (BarCodeResult result in reader.ReadBarCodes())
{
// Output the decoded text
Console.WriteLine($"CodeText: {result.CodeText}");
// Retrieve the IsLinked flag from the extended PDF417 parameters.
bool isLinked = result.Extended.Pdf417.IsLinked;

// Output the IsLinked flag from the extended PDF417 parameters
Console.WriteLine($"IsLinked: {result.Extended.Pdf417.IsLinked}");
// Output the flag value to the console.
Console.WriteLine($"IsLinked: {isLinked}");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,66 +1,61 @@
// Title: Adjust DPI for Accurate Barcode Region Detection
// Description: Demonstrates generating a Code128 barcode, adjusting image DPI, and recognizing the barcode with region details.
// Title: Adjust DPI Settings for Accurate Barcode Detection
// Description: Demonstrates how to set and adjust DPI when generating and loading a barcode image to ensure correct region detection.
// Category-Description: This example belongs to the Aspose.BarCode image processing category, illustrating the use of BarcodeGenerator, Bitmap, and BarCodeReader classes. It shows typical scenarios where developers need to control image resolution for reliable barcode recognition, such as scanning high‑resolution documents or preparing images for OCR pipelines.
// Prompt: Adjust DPI settings when loading images to ensure accurate barcode region detection.
// Tags: barcode, code128, dpi, region detection, generation, recognition, aspose.barcode, aspose.drawing
// Tags: barcode, dpi, resolution, cod128, generation, recognition, aspose.barcode, aspose.drawing

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

/// <summary>
/// Example program that generates a barcode, adjusts image DPI, and reads the barcode region.
/// Demonstrates adjusting DPI settings when loading a barcode image to ensure accurate detection of barcode regions.
/// </summary>
class Program
{
/// <summary>
/// Entry point. Generates a barcode image, sets its DPI, and reads barcode information.
/// Entry point of the example. Generates a high‑resolution barcode, adjusts DPI on load, and reads the barcode.
/// </summary>
static void Main()
{
// Define the file path for the generated barcode image
string imagePath = "sample.png";

// ------------------------------------------------------------
// Generate a simple Code128 barcode and save it to disk
// ------------------------------------------------------------
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
{
// Optional: set generation resolution (DPI) if needed
generator.Parameters.Resolution = 96;
generator.Save(imagePath);
}

// Verify that the image file was created successfully
if (!File.Exists(imagePath))
{
Console.WriteLine($"Error: File not found - {imagePath}");
return;
}

// ------------------------------------------------------------
// Load the image, adjust its DPI, and perform barcode recognition
// ------------------------------------------------------------
using (var bitmap = new Bitmap(imagePath))
// Generate a sample barcode image with a high resolution (300 DPI)
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
// Adjust DPI to 300x300 for more accurate region detection
bitmap.SetResolution(300f, 300f);
// Set the generation resolution (DPI)
generator.Parameters.Resolution = 300;

// Initialize the reader to detect all supported barcode types
using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
// Save the generated barcode to a memory stream in PNG format
using (var ms = new MemoryStream())
{
// Iterate through all detected barcodes
foreach (var result in reader.ReadBarCodes())
generator.Save(ms, BarCodeImageFormat.Png);
ms.Position = 0; // Reset stream position for reading

// Load the image from the memory stream into a Bitmap
using (var bitmap = new Bitmap(ms))
{
// Retrieve the detected barcode region (rectangle)
var region = result.Region.Rectangle;
// Adjust DPI after loading to match the generation DPI
bitmap.SetResolution(300f, 300f);

// Initialize the barcode reader
using (var reader = new BarCodeReader())
{
// Provide the bitmap to the reader
reader.SetBarCodeImage(bitmap);

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

// Output barcode details and region coordinates
Console.WriteLine($"Detected Barcode:");
Console.WriteLine($" Type: {result.CodeTypeName}");
Console.WriteLine($" Text: {result.CodeText}");
Console.WriteLine($" Region - X: {region.X}, Y: {region.Y}, Width: {region.Width}, Height: {region.Height}");
// Output the location and size of the detected barcode region
var rect = result.Region.Rectangle;
Console.WriteLine($"Region - X:{rect.X}, Y:{rect.Y}, Width:{rect.Width}, Height:{rect.Height}");
}
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,111 +1,134 @@
// Title: Batch Barcode Extraction to CSV
// Description: Processes all images in a folder, reads any barcodes present, and writes their metadata to a CSV file.
// Title: Batch barcode extraction from images to CSV
// Description: Demonstrates how to scan a folder of image files, read all supported barcodes, and write their metadata to a CSV file.
// Category-Description: This example belongs to the Aspose.BarCode batch processing category, illustrating the use of BarCodeReader for bulk barcode recognition, BarcodeGenerator for creating sample images, and standard .NET I/O for result export. Developers often need to automate barcode scanning across multiple files and store results in a structured format such as CSV for reporting or downstream processing.
// Prompt: Batch process a folder of images to extract barcode metadata and write results to CSV.
// Tags: barcode, extraction, csv, batch, aspose.barcode, aspose.drawing
// Tags: barcode symbology, batch processing, csv output, aspose.barcode, barcodereader, barcodegenerator

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

/// <summary>
/// Demonstrates how to batch‑process a directory of images, extract barcode information,
/// and export the results to a CSV file using Aspose.BarCode.
/// Demonstrates batch processing of image files to extract barcode metadata and export results to a CSV file.
/// </summary>
class Program
{
/// <summary>
/// Entry point of the application.
/// Accepts an optional folder path argument; otherwise defaults to a folder named "Images".
/// Scans supported image files, reads any barcodes, and writes details to a CSV file.
/// Entry point of the example. Generates sample barcodes, scans each image, and writes detection details to a CSV file.
/// </summary>
/// <param name="args">Command‑line arguments; first argument may specify the folder to process.</param>
static void Main(string[] args)
static void Main()
{
// Determine the folder to process. Use argument if provided, otherwise default to "Images".
string folderPath = args.Length > 0 ? args[0] : "Images";
// Define working directories and CSV output path
string baseDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes");
string csvPath = Path.Combine(Directory.GetCurrentDirectory(), "barcode_results.csv");

// Verify that the target folder exists.
if (!Directory.Exists(folderPath))
// Ensure the barcode folder exists
if (!Directory.Exists(baseDir))
{
Console.WriteLine($"Folder not found: {folderPath}");
return;
Directory.CreateDirectory(baseDir);
}

// Prepare CSV output file path inside the target folder.
string csvPath = Path.Combine(folderPath, "barcode_results.csv");

// Open a StreamWriter for the CSV file (UTF‑8 encoding, overwrite if exists).
using (var csvWriter = new StreamWriter(csvPath, false, Encoding.UTF8))
// Remove any existing CSV file to start fresh
if (File.Exists(csvPath))
{
// Write CSV header line.
csvWriter.WriteLine("FileName,CodeType,CodeText,Confidence,ReadingQuality,RegionX,RegionY,RegionWidth,RegionHeight");
File.Delete(csvPath);
}

// Define supported image file extensions.
string[] extensions = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff" };
// Generate a few sample barcode images (self‑contained example)
GenerateSampleBarcodes(baseDir);

// Retrieve all files in the folder (filtering later by extension).
var imageFiles = Directory.GetFiles(folderPath);
// Write CSV header line
using (var writer = new StreamWriter(csvPath, false, Encoding.UTF8))
{
writer.WriteLine("FileName,CodeType,CodeText,RegionX,RegionY,RegionWidth,RegionHeight");
}

// Iterate over each file in the directory.
foreach (var file in imageFiles)
{
// Skip files that do not have a supported image extension.
if (Array.IndexOf(extensions, Path.GetExtension(file).ToLowerInvariant()) < 0)
continue;
// Define file patterns to search for supported image types
string[] patterns = new[] { "*.png", "*.jpg", "*.bmp" };

// Ensure the file still exists before processing.
if (!File.Exists(file))
// Iterate over each pattern and process matching files
foreach (string pattern in patterns)
{
foreach (string filePath in Directory.GetFiles(baseDir, pattern))
{
// Verify the file still exists before processing
if (!File.Exists(filePath))
{
Console.WriteLine($"File not found (skipped): {file}");
Console.WriteLine($"File not found: {filePath}");
continue;
}

// Load the image using Aspose.Drawing.Bitmap.
using (var bitmap = new Bitmap(file))
// Use BarCodeReader to detect all supported barcode types in the image
using (BarCodeReader reader = new BarCodeReader(filePath, DecodeType.AllSupportedTypes))
{
// Initialize a barcode reader that attempts to decode all supported types.
using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
foreach (var result in reader.ReadBarCodes())
{
// Read all barcodes found in the current image.
foreach (var result in reader.ReadBarCodes())
{
// Extract the bounding rectangle of the detected barcode region.
var rect = result.Region.Rectangle;

// Build a CSV line with the required fields.
var line = new StringBuilder();
line.Append(Path.GetFileName(file));
line.Append(',');
line.Append(result.CodeTypeName);
line.Append(',');
// Replace commas in the code text to avoid CSV column misalignment.
line.Append(result.CodeText?.Replace(",", " "));
line.Append(',');
line.Append(result.Confidence);
line.Append(',');
line.Append(result.ReadingQuality);
line.Append(',');
line.Append(rect.X);
line.Append(',');
line.Append(rect.Y);
line.Append(',');
line.Append(rect.Width);
line.Append(',');
line.Append(rect.Height);

// Write the constructed line to the CSV file.
csvWriter.WriteLine(line.ToString());
}
// Extract the bounding rectangle of the detected barcode region
var rect = result.Region.Rectangle;

// Build a CSV line with escaped text fields
string line = string.Format(
"{0},{1},{2},{3},{4},{5},{6}",
Path.GetFileName(filePath),
result.CodeType,
EscapeCsv(result.CodeText),
rect.X,
rect.Y,
rect.Width,
rect.Height);

// Append the line to the CSV file
File.AppendAllText(csvPath, line + Environment.NewLine, Encoding.UTF8);
}
}
}
}

// Inform the user that processing is complete and provide the CSV location.
Console.WriteLine($"Barcode extraction completed. Results saved to: {csvPath}");
}

// Generates a small set of sample barcode images for demonstration purposes
private static void GenerateSampleBarcodes(string folder)
{
// Sample data for different symbologies
var samples = new (BaseEncodeType type, string text, string fileName)[]
{
(EncodeTypes.Code128, "Sample123", "code128.png"),
(EncodeTypes.QR, "https://example.com", "qr.png"),
(EncodeTypes.DataMatrix, "DM12345", "datamatrix.png"),
(EncodeTypes.Pdf417, "PDF417 Sample Text", "pdf417.png"),
(EncodeTypes.Aztec, "AztecCode", "aztec.png")
};

// Create each barcode image and save it as PNG
foreach (var (type, text, fileName) in samples)
{
string filePath = Path.Combine(folder, fileName);
using (BarcodeGenerator generator = new BarcodeGenerator(type, text))
{
// Optional: set common visual parameters
generator.Parameters.Barcode.XDimension.Point = 2f;
generator.Parameters.Barcode.FilledBars = true;
generator.Save(filePath, BarCodeImageFormat.Png);
}
}
}

// Escapes CSV fields that may contain commas, quotes, or line breaks
private static string EscapeCsv(string field)
{
if (field == null)
return string.Empty;

if (field.Contains(",") || field.Contains("\"") || field.Contains("\n"))
{
string escaped = field.Replace("\"", "\"\"");
return $"\"{escaped}\"";
}

return field;
}
}
Loading
Loading