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,50 +1,74 @@
// Title: Adjust .NET ThreadPool settings for barcode reading
// Description: Demonstrates how to set ThreadPool minimum and maximum threads before generating and reading a barcode image using Aspose.BarCode.
// Category-Description: This example belongs to the Aspose.BarCode .NET barcode generation and recognition category. It showcases the use of BarcodeGenerator for creating a Code128 barcode and BarCodeReader for decoding it, while configuring ThreadPool limits to optimize multithreaded performance. Developers often need to adjust thread pool settings when processing many images concurrently in high‑throughput applications.
// Prompt: Adjust .NET ThreadPool minimum threads to 2 and maximum threads to 8 before creating BarCodeReader instances.
// Tags: barcode symbology, generation, recognition, code128, threadpool, aspnet, aspose.barcode

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

/// <summary>
/// Demonstrates generating a barcode, storing it in memory, and reading it back using Aspose.BarCode.
/// Demonstrates adjusting .NET ThreadPool settings and using Aspose.BarCode to generate and read a Code128 barcode.
/// </summary>
class Program
{
/// <summary>
/// Entry point of the application.
/// Configures thread pool, creates a barcode image in memory, and reads it back.
/// Entry point of the example. Configures ThreadPool limits, creates a barcode image, reads it, and cleans up.
/// </summary>
static void Main()
{
// Configure the thread pool to have a minimum of 2 worker and I/O threads,
// and a maximum of 8 worker and I/O threads.
ThreadPool.SetMinThreads(2, 2);
ThreadPool.SetMaxThreads(8, 8);
// --------------------------------------------------------------------
// Adjust ThreadPool settings before any barcode operations are performed
// --------------------------------------------------------------------
ThreadPool.GetMinThreads(out int minWorker, out int minIOC);
ThreadPool.SetMinThreads(2, minIOC); // Set minimum worker threads to 2
ThreadPool.GetMaxThreads(out int maxWorker, out int maxIOC);
ThreadPool.SetMaxThreads(8, maxIOC); // Set maximum worker threads to 8

// Use a memory stream to hold the generated barcode image.
using (var ms = new MemoryStream())
// -------------------------------------------------
// Generate a sample barcode image using Code128 symbology
// -------------------------------------------------
string imagePath = "sample_barcode.png";
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123"))
{
// Create a barcode generator for Code128 with the data "123456".
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456"))
{
// Save the generated barcode as a PNG image into the memory stream.
generator.Save(ms, BarCodeImageFormat.Png);
}
generator.Save(imagePath, BarCodeImageFormat.Png);
}

// Reset the stream position to the beginning before reading.
ms.Position = 0;
// -------------------------------------------------
// Verify that the barcode image was successfully created
// -------------------------------------------------
if (!File.Exists(imagePath))
{
Console.WriteLine("Failed to create barcode image.");
return;
}

// Initialize a barcode reader that can decode all supported barcode types,
// using the memory stream that contains the PNG image.
using (var reader = new BarCodeReader(ms, DecodeType.AllSupportedTypes))
// -------------------------------------------------
// Read the barcode from the generated image using BarCodeReader
// -------------------------------------------------
using (var reader = new BarCodeReader(imagePath, DecodeType.Code128))
{
foreach (var result in reader.ReadBarCodes())
{
// Iterate through all detected barcodes and output their type and text.
foreach (var result in reader.ReadBarCodes())
{
Console.WriteLine($"Type: {result.CodeTypeName}, Text: {result.CodeText}");
}
Console.WriteLine($"Detected Type: {result.CodeTypeName}");
Console.WriteLine($"Detected Text: {result.CodeText}");
}
}

// -------------------------------------------------
// Clean up the sample image file (optional)
// -------------------------------------------------
try
{
File.Delete(imagePath);
}
catch
{
// Ignore any cleanup errors
}
}
}
Original file line number Diff line number Diff line change
@@ -1,54 +1,51 @@
// Title: Barcode Recognition Using All CPU Cores
// Description: Demonstrates how to enable multi‑core processing for barcode recognition with Aspose.BarCode and reads a generated Code128 barcode.
// Category-Description: This example belongs to the Aspose.BarCode barcode recognition category, illustrating the use of BarCodeReader and its ProcessorSettings to leverage all available CPU cores for faster decoding. Typical use cases include high‑throughput scanning applications where performance is critical. Developers often need to configure ProcessorSettings, select DecodeType, and retrieve barcode metadata such as type, text, and region.
// Prompt: Configure ProcessorSettings.UseAllCores true to allocate all CPU cores automatically for barcode recognition.
// Tags: barcode, recognition, multithreading, useallcores, code128, aspnet, aspnetcore, aspose.barcode, image processing

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

/// <summary>
/// Demonstrates generating a Code128 barcode, reading it back, and cleaning up the temporary file.
/// Demonstrates configuring Aspose.BarCode to use all CPU cores for barcode recognition and reading a Code128 barcode.
/// </summary>
class Program
{
/// <summary>
/// Entry point of the application.
/// Generates a barcode image, reads it, displays the results, and deletes the temporary file.
/// Entry point that generates a sample barcode if missing, enables multi‑core processing, and reads the barcode information.
/// </summary>
static void Main()
{
// Define a temporary file path for the generated barcode image.
string tempImagePath = Path.Combine(Path.GetTempPath(), "sample_barcode.png");

// Generate a simple Code128 barcode and save it to the temporary file.
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890"))
{
generator.Save(tempImagePath, BarCodeImageFormat.Png);
}

// Configure the barcode reader to utilize all CPU cores for faster recognition.
// Enable utilization of all CPU cores for barcode recognition
BarCodeReader.ProcessorSettings.UseAllCores = true;

// Read the barcode from the generated image file.
using (var reader = new BarCodeReader(tempImagePath, DecodeType.AllSupportedTypes))
// Path to the barcode image file
string imagePath = "barcode.png";

// Generate a sample Code128 barcode image if it does not already exist
if (!File.Exists(imagePath))
{
// Iterate through all detected barcodes and output their type and text.
foreach (var result in reader.ReadBarCodes())
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789"))
{
Console.WriteLine($"Detected Type: {result.CodeTypeName}");
Console.WriteLine($"Detected Text: {result.CodeText}");
generator.Save(imagePath, BarCodeImageFormat.Png);
}
}

// Clean up the temporary image file if it still exists.
if (File.Exists(tempImagePath))
// Initialize the reader to decode all supported barcode types from the image
using (var reader = new BarCodeReader(imagePath, DecodeType.AllSupportedTypes))
{
try
{
File.Delete(tempImagePath);
}
catch
// Iterate through all detected barcodes and output their details
foreach (var result in reader.ReadBarCodes())
{
// If deletion fails, ignore – the OS will eventually remove the file.
Console.WriteLine($"Barcode Type: {result.CodeTypeName}");
Console.WriteLine($"Barcode Text: {result.CodeText}");

var bounds = result.Region.Rectangle;
Console.WriteLine($"Region - X:{bounds.X}, Y:{bounds.Y}, Width:{bounds.Width}, Height:{bounds.Height}");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,103 +1,88 @@
// Title: Background Worker Barcode Reader from Video Stream
// Description: Demonstrates reading barcodes from simulated video frames using a BackgroundWorker and ProcessorSettings to control core usage.
// Category-Description: This example belongs to the Aspose.BarCode generation and recognition category, showcasing how to generate barcodes, process them in a background thread, and fine‑tune multi‑core utilization via ProcessorSettings. Developers often need to handle high‑throughput image streams (e.g., video) and require optimal CPU usage while recognizing multiple symbologies using BarCodeReader, BarcodeGenerator, and QualitySettings.
// Prompt: Create a background worker that reads barcodes from a video stream using ProcessorSettings for optimal core usage.
// Tags: code128, read, console, barcodegenerator, barcodereader, processorsettings, qualitysettings

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
using Aspose.BarCode.Generation;
using Aspose.BarCode.BarCodeRecognition;
using Aspose.Drawing;
using Aspose.Drawing.Imaging;

/// <summary>
/// Demonstrates generating barcode images, treating them as video frames,
/// and processing each frame to recognize barcodes using Aspose.BarCode.
/// Example program that generates barcode images, simulates video frames,
/// and reads them in a background worker using Aspose.BarCode APIs.
/// </summary>
class Program
{
/// <summary>
/// Entry point of the application.
/// Configures processor settings, generates sample frames, and processes them asynchronously.
/// Entry point. Generates sample frames, configures processor settings,
/// and processes frames asynchronously.
/// </summary>
static void Main()
{
// Use all available CPU cores for barcode processing (optimal performance)
BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Environment.ProcessorCount;

// Generate a small collection of barcode images that simulate video frames
List<MemoryStream> frameStreams = GenerateSampleFrames(5);

// Run the frame processing on a background task (simulating a background worker)
Task processingTask = Task.Run(() => ProcessFrames(frameStreams));

// Wait for the background task to complete before exiting the program
processingTask.Wait();
}

/// <summary>
/// Generates the specified number of barcode images and returns them as memory streams.
/// </summary>
/// <param name="count">Number of barcode frames to generate.</param>
/// <returns>List of memory streams containing PNG barcode images.</returns>
private static List<MemoryStream> GenerateSampleFrames(int count)
{
var frames = new List<MemoryStream>();

for (int i = 0; i < count; i++)
// Generate a few barcode images to simulate video frames
var frames = new List<byte[]>();
for (int i = 0; i < 3; i++)
{
// Create a unique code text for each frame (e.g., FRAME01, FRAME02, ...)
string codeText = $"FRAME{i + 1:D2}";

// Initialize a barcode generator for Code128 with the specified text
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText))
// Create a barcode generator for Code128 with unique text
using (var generator = new BarcodeGenerator(EncodeTypes.Code128, $"Sample{i + 1}"))
{
// Set a consistent image size for all generated barcodes
generator.Parameters.ImageWidth.Point = 300f;
generator.Parameters.ImageHeight.Point = 150f;

// Save the generated barcode image to a memory stream in PNG format
var ms = new MemoryStream();
generator.Save(ms, BarCodeImageFormat.Png);
ms.Position = 0; // Reset stream position for subsequent reading

// Add the memory stream to the collection of frames
frames.Add(ms);
// Set a simple visual dimension
generator.Parameters.Barcode.XDimension.Point = 2f;
// Render the barcode to a bitmap
using (var bitmap = generator.GenerateBarCodeImage())
{
// Save bitmap to memory stream as PNG
using (var ms = new MemoryStream())
{
bitmap.Save(ms, ImageFormat.Png);
frames.Add(ms.ToArray());
}
}
}
}

return frames;
}
// Synchronization primitive to wait for background work completion
var doneEvent = new ManualResetEventSlim(false);

/// <summary>
/// Processes each barcode frame, reads any barcodes present, and writes the results to the console.
/// </summary>
/// <param name="frameStreams">List of memory streams representing barcode frames.</param>
private static void ProcessFrames(List<MemoryStream> frameStreams)
{
int frameIndex = 0;

// Iterate over each frame stream
foreach (var stream in frameStreams)
// BackgroundWorker that processes the simulated video frames
var worker = new BackgroundWorker();
worker.DoWork += (sender, args) =>
{
frameIndex++;
// Configure processor settings for optimal core usage
BarCodeReader.ProcessorSettings.UseAllCores = false;
BarCodeReader.ProcessorSettings.UseOnlyThisCoresCount = Math.Max(1, Environment.ProcessorCount / 2);

// Load the image from the memory stream
using (var bitmap = new Bitmap(stream))
// Iterate over each simulated frame
foreach (var frameData in frames)
{
// Initialize a barcode reader that supports all barcode types
using (var reader = new BarCodeReader(bitmap, DecodeType.AllSupportedTypes))
// Create a memory stream from the frame bytes
using (var stream = new MemoryStream(frameData))
// Initialize the barcode reader for all supported symbologies
using (var reader = new BarCodeReader(stream, DecodeType.AllSupportedTypes))
{
// Apply a high-performance quality preset for faster processing
// Apply a highperformance quality preset
reader.QualitySettings = QualitySettings.HighPerformance;

// Read all barcodes found in the current frame
// Read and output all detected barcodes
foreach (var result in reader.ReadBarCodes())
{
// Output the detected barcode type and its text value
Console.WriteLine($"Frame {frameIndex}: Detected {result.CodeTypeName} - Text: {result.CodeText}");
Console.WriteLine($"Detected: {result.CodeTypeName} - {result.CodeText}");
}
}
}
};
// Signal completion when background work finishes
worker.RunWorkerCompleted += (s, e) => doneEvent.Set();

// Release the memory stream resources after processing the frame
stream.Dispose();
}
// Start processing and wait until it finishes
worker.RunWorkerAsync();
doneEvent.Wait();
}
}
Loading
Loading