From d2663459309d4256d07445ccd7e355a294f34dc2 Mon Sep 17 00:00:00 2001 From: agent-aspose-barcode-examples Date: Tue, 4 Aug 2026 02:07:25 +0500 Subject: [PATCH] =?UTF-8?q?feat(barcode-saving-and-export):=20Add=2030=20A?= =?UTF-8?q?spose.BarCode=20.NET=20C#=20examples=20for=20Barcode=20Saving?= =?UTF-8?q?=20And=20Export=20=E2=80=94=20Aspose.BarCode=20for=20.NET=2026.?= =?UTF-8?q?7.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...st-and-save-each-as-individual-svg-file.cs | 113 +++++++------- ...nerated-barcode-and-save-results-as-bmp.cs | 145 +++++++++++------- ...-cmyk-color-space-for-print-ready-files.cs | 43 +++--- ...-export-as-png-for-crisp-screen-display.cs | 44 +++--- ...e-it-with-systemdrawing-then-save-image.cs | 70 ++++----- ...-and-export-it-as-gif-image-for-web-use.cs | 47 +++--- ...export-it-as-svg-for-scalable-rendering.cs | 57 ++++--- ...mg-tag-using-data-uri-from-memorystream.cs | 45 +++--- ...ert-it-to-pdf-using-third-party-library.cs | 62 ++++---- ...-into-powerpoint-slide-programmatically.cs | 85 +++++----- ...stream-in-jpeg-format-for-http-response.cs | 44 +++--- ...stream-in-aspnet-for-immediate-download.cs | 52 ++++--- ...pply-grayscale-filter-then-save-as-jpeg.cs | 70 +++++---- ...ditional-text-with-gdi-then-save-as-png.cs | 61 ++++---- ...g-ensuring-viewbox-matches-barcode-size.cs | 65 +++++--- ...save-as-bmp-file-preserving-orientation.cs | 49 +++--- ...ly-to-filestream-using-asynchronous-i-o.cs | 36 ++--- ...-it-as-png-file-with-300-dpi-resolution.cs | 29 ++-- ...port-it-as-png-preserving-alpha-channel.cs | 34 ++-- ...t-to-80-to-balance-size-and-readability.cs | 51 +++--- ...compression-enabled-to-reduce-file-size.cs | 46 +++--- ...eam-and-convert-stream-to-base64-string.cs | 19 +-- ...to-permanent-directory-with-unique-name.cs | 41 +++-- ...-bmp-file-using-custom-foreground-color.cs | 49 +++--- ...-svg-files-in-loop-for-batch-processing.cs | 76 ++++----- ...or-file-and-embed-it-into-word-document.cs | 49 +++--- ...0-dpi-and-save-upc-barcode-as-tiff-file.cs | 23 +-- ...e-to-cloudblob-stream-for-azure-storage.cs | 83 +++++----- ...twork-stream-for-real-time-transmission.cs | 57 +++---- ...-to-filestream-with-async-await-pattern.cs | 42 +++-- 30 files changed, 890 insertions(+), 797 deletions(-) diff --git a/barcode-saving-and-export/batch-generate-code39-barcodes-from-csv-list-and-save-each-as-individual-svg-file.cs b/barcode-saving-and-export/batch-generate-code39-barcodes-from-csv-list-and-save-each-as-individual-svg-file.cs index 7336dad..faba977 100644 --- a/barcode-saving-and-export/batch-generate-code39-barcodes-from-csv-list-and-save-each-as-individual-svg-file.cs +++ b/barcode-saving-and-export/batch-generate-code39-barcodes-from-csv-list-and-save-each-as-individual-svg-file.cs @@ -1,90 +1,95 @@ -// Title: Batch Code39 SVG Barcode Generator -// Description: Reads a list of values from a CSV file (or uses a default list) and creates a Code39 barcode SVG for each entry. +// Title: Batch generate Code39 barcodes from CSV to SVG files +// Description: Reads a CSV file, generates a Code39 barcode for each entry, and saves each barcode as an individual SVG file. +// Category-Description: This example demonstrates batch barcode generation using Aspose.BarCode. It showcases the BarcodeGenerator class with EncodeTypes.Code39 and BarCodeImageFormat.Svg to create SVG images. Typical scenarios include bulk creation of product labels, inventory tags, or any situation where a list of identifiers must be turned into barcodes. Developers working with Aspose.BarCode often need to read data sources, generate barcodes programmatically, and store them in various image formats. // Prompt: Batch generate Code39 barcodes from a CSV list and save each as an individual SVG file. -// Tags: code39, barcode, batch, svg, csv, aspnet, aspose.barcode +// Tags: code39, barcode, generation, svg, csv, aspose.barcode, batch-processing using System; -using System.Collections.Generic; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Demonstrates how to generate a batch of Code39 barcodes from a CSV file +/// Demonstrates how to read a CSV file, generate a Code39 barcode for each line, /// and save each barcode as an individual SVG file using Aspose.BarCode. /// class Program { /// - /// Entry point of the application. Handles CSV loading, barcode generation, - /// and file output for each code text. + /// Entry point of the application. Processes command‑line arguments, + /// validates input, generates barcodes, and writes SVG files to the output folder. /// - static void Main() + /// + /// Optional arguments: + /// args[0] – path to the input CSV file (default: "input.csv"). + /// args[1] – path to the output folder for SVG files (default: "Barcodes"). + /// + static void Main(string[] args) { - // Input CSV file path (optional). If the file does not exist, a default list is used. - const string csvPath = "input.csv"; + // Default input CSV file and output directory + string csvPath = "input.csv"; + string outputFolder = "Barcodes"; - // Directory where SVG files will be saved. - const string outputDir = "Barcodes"; - - // Ensure the output directory exists. - if (!Directory.Exists(outputDir)) + // Override defaults with command‑line arguments if provided + if (args.Length > 0 && !string.IsNullOrWhiteSpace(args[0])) { - Directory.CreateDirectory(outputDir); + csvPath = args[0]; } - - // Load code texts from CSV or use a fallback sample. - List codeTexts = new List(); - if (File.Exists(csvPath)) + if (args.Length > 1 && !string.IsNullOrWhiteSpace(args[1])) { - // Simple CSV parsing: each line's first column is taken as the barcode value. - foreach (var line in File.ReadAllLines(csvPath)) - { - if (string.IsNullOrWhiteSpace(line)) - continue; - - // Split by comma and trim whitespace. - var parts = line.Split(','); - if (parts.Length > 0) - { - var code = parts[0].Trim(); - if (!string.IsNullOrEmpty(code)) - codeTexts.Add(code); - } - } + outputFolder = args[1]; } - else + + // Verify that the CSV file exists before proceeding + if (!File.Exists(csvPath)) { - // Fallback sample data (safe size for demonstration). - codeTexts.AddRange(new[] - { - "CODE39A", - "12345", - "HELLO-WORLD", - "ASP.NET", - "BARCODE" - }); + Console.WriteLine($"CSV file not found: {csvPath}"); + return; } - // Generate a Code39 barcode for each code text and save as SVG. - foreach (var codeText in codeTexts) + // Ensure the output directory exists (creates it if necessary) + Directory.CreateDirectory(outputFolder); + + // Read all lines from the CSV file + string[] lines = File.ReadAllLines(csvPath); + foreach (string line in lines) { - // File name is sanitized to avoid invalid path characters. - var safeFileName = GetSafeFileName(codeText); - var outputPath = Path.Combine(outputDir, safeFileName + ".svg"); + // Skip empty or whitespace‑only lines + if (string.IsNullOrWhiteSpace(line)) + continue; + + // Assume the first column contains the Code39 value + string[] parts = line.Split(','); + string codeText = parts[0].Trim(); + + // Skip lines where the first column is empty + if (string.IsNullOrEmpty(codeText)) + continue; + + // Build a safe file name for the SVG output + string safeFileName = GetSafeFileName(codeText) + ".svg"; + string outputPath = Path.Combine(outputFolder, safeFileName); - // Create a barcode generator for Code39 with the current text. + // Generate the Code39 barcode and save it directly as SVG using (var generator = new BarcodeGenerator(EncodeTypes.Code39, codeText)) { - // Save directly as SVG. + // Do not throw if the code text contains minor issues (e.g., unsupported characters) + generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false; + + // Save the barcode image in SVG format generator.Save(outputPath, BarCodeImageFormat.Svg); } - Console.WriteLine($"Generated barcode for '{codeText}' -> {outputPath}"); + Console.WriteLine($"Generated: {outputPath}"); } } - // Replaces characters that are invalid in file names with an underscore. + /// + /// Replaces characters that are invalid in file names with an underscore, + /// ensuring the generated file name is safe for the file system. + /// + /// Original file name derived from the barcode text. + /// A sanitized file name with invalid characters replaced. private static string GetSafeFileName(string name) { foreach (char c in Path.GetInvalidFileNameChars()) diff --git a/barcode-saving-and-export/batch-process-image-files-overlay-each-with-generated-barcode-and-save-results-as-bmp.cs b/barcode-saving-and-export/batch-process-image-files-overlay-each-with-generated-barcode-and-save-results-as-bmp.cs index 734720e..d6dcfc1 100644 --- a/barcode-saving-and-export/batch-process-image-files-overlay-each-with-generated-barcode-and-save-results-as-bmp.cs +++ b/barcode-saving-and-export/batch-process-image-files-overlay-each-with-generated-barcode-and-save-results-as-bmp.cs @@ -1,97 +1,128 @@ // Title: Batch barcode overlay on images -// Description: Demonstrates loading up to five images, generating a Code128 barcode, overlaying it on each image, and saving the result as BMP files. +// Description: Demonstrates how to batch‑process image files, overlay each with a generated Code128 barcode derived from the file name, and save the result as BMP. +// Category-Description: This example belongs to the Aspose.BarCode image manipulation category, illustrating the use of BarcodeGenerator, BarCodeImageFormat, and Aspose.Drawing classes to create barcodes, render them to streams, and composite them onto existing images. Typical use cases include watermarking product photos with SKU barcodes or adding machine‑readable identifiers to documents. Developers often need to automate such batch operations for inventory, labeling, or archival workflows. // Prompt: Batch process image files, overlay each with a generated barcode, and save the results as BMP. -// Tags: barcode, code128, overlay, batch, bmp, aspose.barcode, aspose.drawing +// Tags: barcode, code128, overlay, batch, bmp, aspose.barcode, aspose.drawing, image-processing using System; using System.IO; -using System.Linq; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Example program that processes a set of image files, adds a generated barcode to each, -/// and saves the combined image as a BMP file. +/// Example program that batch processes images, overlays each with a generated barcode, +/// and saves the combined result as a BMP file. /// class Program { /// - /// Entry point of the application. Performs batch processing of images with barcode overlay. + /// Entry point of the application. Performs folder setup, sample image creation, + /// barcode generation, image compositing, and output saving. /// static void Main() { - // Define input and output directories (adjust paths as needed) - string inputDir = "input_images"; - string outputDir = "output_images"; + // Define input and output folders relative to the current directory + string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "input_images"); + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "output_images"); - // Ensure the output directory exists; create it if it does not - if (!Directory.Exists(outputDir)) - { - Directory.CreateDirectory(outputDir); - } + // Ensure the input and output directories exist + Directory.CreateDirectory(inputFolder); + Directory.CreateDirectory(outputFolder); - // Verify that the input directory exists before proceeding - if (!Directory.Exists(inputDir)) + // Prepare sample images if the input folder is empty (self‑contained example) + string[] samplePatterns = new[] { "*.png", "*.jpg", "*.bmp" }; + bool anyImageExists = false; + foreach (var pattern in samplePatterns) { - Console.WriteLine($"Input directory not found: {inputDir}"); - return; + if (Directory.GetFiles(inputFolder, pattern).Length > 0) + { + anyImageExists = true; + break; + } } - // Retrieve up to five image files with supported extensions from the input directory - string[] files = Directory.GetFiles(inputDir, "*.*") - .Where(f => f.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase) || - f.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || - f.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase) || - f.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || - f.EndsWith(".gif", StringComparison.OrdinalIgnoreCase)) - .Take(5) - .ToArray(); - - // If no images were found, inform the user and exit - if (files.Length == 0) + if (!anyImageExists) { - Console.WriteLine("No image files found to process."); - return; + // Create 5 simple placeholder images + for (int i = 1; i <= 5; i++) + { + string samplePath = Path.Combine(inputFolder, $"sample{i}.png"); + using (var bmp = new Bitmap(300, 200)) + { + using (var g = Graphics.FromImage(bmp)) + { + g.Clear(Color.LightGray); + g.DrawString($"Sample {i}", new Font("Arial", 24f), new SolidBrush(Color.Black), new PointF(50f, 80f)); + } + bmp.Save(samplePath, ImageFormat.Png); + } + } } - // Process each image file individually - foreach (string filePath in files) + // Iterate over each supported image pattern + foreach (var pattern in samplePatterns) { - // Derive the output file name by appending "_barcode" and changing the extension to BMP - string fileName = Path.GetFileNameWithoutExtension(filePath); - string outputPath = Path.Combine(outputDir, $"{fileName}_barcode.bmp"); - - // Load the original image from disk - using (Image baseImage = Image.FromFile(filePath)) + // Process every file that matches the current pattern + foreach (var imagePath in Directory.GetFiles(inputFolder, pattern)) { - // Create a barcode generator for Code128 with sample text - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + try { - // Optional: configure barcode size and scaling mode - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - generator.Parameters.ImageWidth.Point = 200f; // Desired barcode width - generator.Parameters.ImageHeight.Point = 80f; // Desired barcode height - - // Generate the barcode as a bitmap image - using (Bitmap barcodeBitmap = generator.GenerateBarCodeImage()) + // Load the original image from disk + using (var original = (Bitmap)Image.FromFile(imagePath)) { - // Draw the barcode onto the base image using graphics context - using (Graphics graphics = Graphics.FromImage(baseImage)) + // Use the file name (without extension) as the barcode text + string codeText = Path.GetFileNameWithoutExtension(imagePath); + + // Create a Code128 barcode generator + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - // Position the barcode at the bottom‑right corner with a 10‑pixel margin - int x = baseImage.Width - barcodeBitmap.Width - 10; - int y = baseImage.Height - barcodeBitmap.Height - 10; - graphics.DrawImage(barcodeBitmap, x, y, barcodeBitmap.Width, barcodeBitmap.Height); + // Optional: adjust the module size for better readability + generator.Parameters.Barcode.XDimension.Point = 2f; + + // Render the barcode to a memory stream in PNG format + using (var barcodeStream = new MemoryStream()) + { + generator.Save(barcodeStream, BarCodeImageFormat.Png); + barcodeStream.Position = 0; + + // Load the rendered barcode image from the stream + using (var barcodeImage = (Bitmap)Image.FromStream(barcodeStream)) + { + // Calculate bottom‑right position with a 10‑pixel margin + int margin = 10; + int xPos = original.Width - barcodeImage.Width - margin; + int yPos = original.Height - barcodeImage.Height - margin; + if (xPos < 0) xPos = 0; + if (yPos < 0) yPos = 0; + + // Draw the barcode onto the original image + using (var graphics = Graphics.FromImage(original)) + { + graphics.DrawImage(barcodeImage, xPos, yPos, barcodeImage.Width, barcodeImage.Height); + } + } + } } - // Save the combined image as a BMP file - baseImage.Save(outputPath, ImageFormat.Bmp); + // Build the output file name and path + string outputFileName = Path.GetFileNameWithoutExtension(imagePath) + "_with_barcode.bmp"; + string outputPath = Path.Combine(outputFolder, outputFileName); + + // Save the combined image as BMP + original.Save(outputPath, ImageFormat.Bmp); Console.WriteLine($"Processed and saved: {outputPath}"); } } + catch (Exception ex) + { + // Log any errors that occur during processing of a single file + Console.WriteLine($"Error processing '{imagePath}': {ex.Message}"); + } } } + + Console.WriteLine("Batch processing completed."); } } \ No newline at end of file diff --git a/barcode-saving-and-export/configure-generator-to-output-tiff-in-cmyk-color-space-for-print-ready-files.cs b/barcode-saving-and-export/configure-generator-to-output-tiff-in-cmyk-color-space-for-print-ready-files.cs index f02f22b..f290a72 100644 --- a/barcode-saving-and-export/configure-generator-to-output-tiff-in-cmyk-color-space-for-print-ready-files.cs +++ b/barcode-saving-and-export/configure-generator-to-output-tiff-in-cmyk-color-space-for-print-ready-files.cs @@ -1,47 +1,42 @@ -// Title: Generate CMYK TIFF Barcode for Print -// Description: Demonstrates configuring Aspose.BarCode to generate a Code128 barcode saved as a CMYK TIFF image suitable for print. +// Title: Generate a Code128 barcode saved as CMYK TIFF for print-ready output +// Description: Demonstrates configuring Aspose.BarCode to produce a TIFF image in CMYK color space, suitable for high‑quality printing. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to use BarcodeGenerator with EncodeTypes, set barcode text, and save in specific image formats such as CMYK TIFF. Developers often need to create print‑ready barcodes with precise color profiles, using classes like BarcodeGenerator, BarCodeImageFormat, and CMYKColor for color management. // Prompt: Configure the generator to output TIFF in CMYK color space for print‑ready files. -// Tags: code128, barcode generation, tiff, cmyk, print, aspose.barcode, aspose.drawing +// Tags: code128, barcode generation, tiff, cmyk, print-ready, aspose.barcode, image format using System; +using System.IO; using Aspose.BarCode.Generation; using Aspose.Drawing; -using Aspose.Drawing.Imaging; /// -/// Example program that creates a Code128 barcode and saves it as a CMYK TIFF file, -/// ready for high‑quality printing. +/// Demonstrates generating a Code128 barcode and saving it as a CMYK TIFF image. /// class Program { /// - /// Entry point of the application. Generates the barcode and writes it to disk. + /// Entry point. Creates the barcode, configures CMYK colors, and saves the image. /// static void Main() { - // Barcode content to encode - const string codeText = "PrintReady123"; - - // Destination file name (TIFF format) - const string outputPath = "barcode_cmyk.tif"; + // Define the output file path for the CMYK TIFF barcode + string outputPath = "barcode_cmyk.tif"; // Initialize the barcode generator with Code128 symbology - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + using (var generator = new BarcodeGenerator(EncodeTypes.Code128)) { - // Set image resolution to 300 DPI, a common print standard - generator.Parameters.Resolution = 300; + // Set the text that will be encoded into the barcode + generator.CodeText = "PrintReady123"; - // Define bar (foreground) and background colors. - // Colors are specified in RGB; the TIFF encoder will convert them to CMYK. - generator.Parameters.Barcode.BarColor = Color.FromArgb(0, 0, 0); // Black bars - generator.Parameters.BackColor = Color.FromArgb(255, 255, 255); // White background + // Optional: define CMYK colors for the barcode and background + // generator.Parameters.Pdf.CMYKBarColor = new CMYKColor(0, 0, 0, 100); // Black in CMYK + // generator.Parameters.Pdf.CMYKBackColor = new CMYKColor(0, 0, 0, 0); // White in CMYK - // Save the barcode as a TIFF image. - // The internal encoder produces a CMYK TIFF when the pixel format supports it. - generator.Save(outputPath, BarCodeImageFormat.Tiff); + // Save the barcode as a TIFF image using the CMYK color space + generator.Save(outputPath, BarCodeImageFormat.TiffInCmyk); } - // Inform the user that the file has been created - Console.WriteLine($"Barcode saved to {outputPath}"); + // Inform the user where the barcode image has been saved + Console.WriteLine($"Barcode saved to {Path.GetFullPath(outputPath)}"); } } \ No newline at end of file diff --git a/barcode-saving-and-export/create-barcode-apply-anti-aliasing-settings-and-export-as-png-for-crisp-screen-display.cs b/barcode-saving-and-export/create-barcode-apply-anti-aliasing-settings-and-export-as-png-for-crisp-screen-display.cs index 317db2e..0fce36b 100644 --- a/barcode-saving-and-export/create-barcode-apply-anti-aliasing-settings-and-export-as-png-for-crisp-screen-display.cs +++ b/barcode-saving-and-export/create-barcode-apply-anti-aliasing-settings-and-export-as-png-for-crisp-screen-display.cs @@ -1,46 +1,46 @@ -// Title: Generate Code128 Barcode with Anti-Aliasing and Export as PNG -// Description: Demonstrates creating a Code128 barcode, enabling anti‑aliasing, setting image size and resolution, and saving it as a PNG for clear screen display. +// Title: Generate a Code128 barcode with anti‑aliasing and save as PNG +// Description: Demonstrates creating a Code128 barcode, enabling anti‑aliasing and high resolution for a crisp PNG image suitable for screen display. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure rendering options such as anti‑aliasing, resolution, and colors using the BarcodeGenerator class. Typical use cases include producing high‑quality barcodes for web pages, mobile apps, or UI components where visual clarity is essential. Developers often need to adjust these settings to meet design guidelines and ensure readability across devices. // Prompt: Create a barcode, apply anti‑aliasing settings, and export as PNG for crisp screen display. -// Tags: code128, barcode generation, anti-aliasing, png, aspose.barcode, c# +// Tags: code128, anti-aliasing, png, barcode generation, aspose.barcode using System; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; -using Aspose.BarCode.BarCodeRecognition; /// -/// Example program that generates a Code128 barcode, applies anti‑aliasing, -/// configures image dimensions and resolution, and saves the result as a PNG file. +/// Example program that creates a Code128 barcode, applies anti‑aliasing, +/// sets a high resolution, and saves the result as a PNG image. /// class Program { /// - /// Entry point of the application. Creates the barcode and writes it to disk. + /// Entry point of the example. Generates the barcode and writes it to disk. /// static void Main() { - // Initialize a barcode generator for Code128 with the sample text "1234567890". - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Define the output file path for the generated PNG image. + string outputPath = "barcode.png"; + + // Initialize the BarcodeGenerator with Code128 symbology and sample data. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Enable anti‑aliasing to produce smoother edges when the image is displayed on screen. + // Enable anti‑aliasing to smooth edges and improve visual quality. generator.Parameters.UseAntiAlias = true; - // Use interpolation mode so the image size can be set directly without distortion. - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - - // Define the desired image width and height in points for a crisp visual appearance. - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; - - // Optionally increase the resolution (dots per inch) to improve overall quality. + // Set a higher resolution (dots per inch) for a sharper image on screens. generator.Parameters.Resolution = 300f; - // Save the generated barcode as a PNG file. - generator.Save("barcode.png"); + // Optional: Define foreground (barcode) and background colors. + generator.Parameters.Barcode.BarColor = Color.Black; + generator.Parameters.BackColor = Color.White; + + // Save the configured barcode as a PNG file. + generator.Save(outputPath, BarCodeImageFormat.Png); } - // Inform the user that the barcode has been successfully created. - Console.WriteLine("Barcode generated and saved as 'barcode.png'."); + // Inform the user where the barcode image has been saved. + Console.WriteLine($"Barcode saved to {outputPath}"); } } \ No newline at end of file diff --git a/barcode-saving-and-export/create-barcode-as-bitmap-resize-it-with-systemdrawing-then-save-image.cs b/barcode-saving-and-export/create-barcode-as-bitmap-resize-it-with-systemdrawing-then-save-image.cs index f146afe..9c09c56 100644 --- a/barcode-saving-and-export/create-barcode-as-bitmap-resize-it-with-systemdrawing-then-save-image.cs +++ b/barcode-saving-and-export/create-barcode-as-bitmap-resize-it-with-systemdrawing-then-save-image.cs @@ -1,7 +1,8 @@ -// Title: Generate and Resize a Code128 Barcode Image -// Description: Demonstrates creating a Code128 barcode as a bitmap, enlarging it using System.Drawing, and saving both original and resized images as PNG files. +// Title: Generate and Resize a Code128 Barcode as PNG +// Description: Creates a Code128 barcode, resizes it using System.Drawing, and saves it as a PNG image. +// Category-Description: This example belongs to the Aspose.BarCode image generation and manipulation category. It demonstrates how to use BarcodeGenerator (Aspose.BarCode.Generation) to produce a barcode bitmap, employ Aspose.Drawing (System.Drawing compatible) for resizing, and persist the result with Aspose.Drawing.Imaging. Developers often need to generate barcodes, adjust dimensions for UI or printing, and export them in common image formats. // Prompt: Create a barcode as a Bitmap, resize it with System.Drawing, then save the image. -// Tags: code128, barcode generation, resize, png, aspose.barcode, aspose.drawing +// Tags: code128, generate, resize, png, aspose.barcode, aspose.drawing, aspose.drawing.imaging using System; using System.IO; @@ -11,55 +12,50 @@ using Aspose.Drawing.Imaging; /// -/// Example program that generates a barcode, resizes it, and saves both versions as PNG files. +/// Demonstrates barcode generation, resizing, and saving using Aspose.BarCode and Aspose.Drawing. /// class Program { /// - /// Entry point of the application. - /// Generates a Code128 barcode, resizes it using System.Drawing, and writes the images to disk. + /// Entry point. Generates a Code128 barcode, resizes it, and writes the result to a PNG file. /// static void Main() { - // Paths for the original and resized barcode images - string originalPath = "barcode_original.png"; - string resizedPath = "barcode_resized.png"; + // Output file path for the resized barcode image + const string outputPath = "barcode_resized.png"; - // 1. Generate a Code128 barcode and save it as a PNG file - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Initialize a barcode generator for Code128 with sample data + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) { - generator.Save(originalPath, BarCodeImageFormat.Png); - } - - // 2. Load the generated image using Aspose.Drawing - using (var originalImage = Image.FromFile(originalPath) as Bitmap) - { - if (originalImage == null) + // Produce the barcode as an Aspose.Drawing.Bitmap + using (var originalBitmap = generator.GenerateBarCodeImage()) { - Console.WriteLine("Failed to load the generated barcode image."); - return; - } + // Target dimensions for the resized image + const int newWidth = 300; + const int newHeight = 150; - // Define new dimensions (e.g., double the size) - int newWidth = originalImage.Width * 2; - int newHeight = originalImage.Height * 2; - - // 3. Create a new bitmap with the desired size - using (var resizedBitmap = new Bitmap(newWidth, newHeight)) - { - // 4. Draw the original image onto the resized bitmap - using (var graphics = Graphics.FromImage(resizedBitmap)) + // Create a blank bitmap with the desired size + using (var resizedBitmap = new Bitmap(newWidth, newHeight)) { - graphics.DrawImage(originalImage, 0, 0, newWidth, newHeight); + // Obtain a graphics object to draw onto the new bitmap + using (var graphics = Graphics.FromImage(resizedBitmap)) + { + // Draw and scale the original barcode onto the resized bitmap + graphics.DrawImage( + originalBitmap, + new Rectangle(0, 0, newWidth, newHeight)); + } + + // Save the resized bitmap as a PNG file + using (var fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) + { + resizedBitmap.Save(fileStream, ImageFormat.Png); + } } - - // 5. Save the resized image as PNG - resizedBitmap.Save(resizedPath, ImageFormat.Png); } } - // Output the locations of the saved images - Console.WriteLine($"Original barcode saved to: {originalPath}"); - Console.WriteLine($"Resized barcode saved to: {resizedPath}"); + // Inform the user where the file was saved + Console.WriteLine($"Resized barcode saved to '{Path.GetFullPath(outputPath)}'"); } } \ No newline at end of file diff --git a/barcode-saving-and-export/create-barcode-with-custom-background-color-and-export-it-as-gif-image-for-web-use.cs b/barcode-saving-and-export/create-barcode-with-custom-background-color-and-export-it-as-gif-image-for-web-use.cs index 65085fe..d3234f3 100644 --- a/barcode-saving-and-export/create-barcode-with-custom-background-color-and-export-it-as-gif-image-for-web-use.cs +++ b/barcode-saving-and-export/create-barcode-with-custom-background-color-and-export-it-as-gif-image-for-web-use.cs @@ -1,39 +1,42 @@ -// Title: Generate Code128 Barcode with Custom Colors and Save as GIF -// Description: Demonstrates creating a Code128 barcode, applying custom background and bar colors, and exporting it as a GIF image suitable for web usage. +// Title: Generate a Code128 barcode with custom background color and save as GIF +// Description: Demonstrates creating a Code128 barcode, applying a light gray background, and exporting it as a GIF image suitable for web pages. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to customize barcode appearance using the BarcodeGenerator class. Typical use cases include branding, UI integration, and web-friendly image output. Developers often need to adjust colors, formats, and symbologies when embedding barcodes in web applications. // Prompt: Create a barcode with custom background color and export it as a GIF image for web use. -// Tags: code128, barcode, color, gif, aspose.barcode, aspose.drawing, generation +// Tags: code128, barcode generation, gif, background color, aspose.barcode, aspnet using System; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; -/// -/// Example program that generates a Code128 barcode with custom colors -/// and saves it as a GIF image for web use. -/// -class Program +namespace BarcodeExample { /// - /// Entry point of the application. - /// Creates a barcode, customizes its appearance, and writes it to a GIF file. + /// Provides an example that creates a Code128 barcode, sets a custom background color, + /// and saves the result as a GIF image for web usage. /// - static void Main() + class Program { - // Initialize a BarcodeGenerator for Code128 with the desired text. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "HelloWorld")) + /// + /// Entry point of the example. Generates the barcode and writes the output path to the console. + /// + static void Main() { - // Apply a custom background color to the image. - generator.Parameters.BackColor = Color.LightYellow; + // Define the output file name and format + string outputPath = "barcode.gif"; - // Apply a custom foreground (bar) color to the barcode. - generator.Parameters.Barcode.BarColor = Color.DarkBlue; + // Initialize the barcode generator with Code128 symbology and sample data + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + { + // Apply a light gray background color to the generated image + generator.Parameters.BackColor = Color.LightGray; - // Save the generated barcode as a GIF file, which is web‑friendly. - generator.Save("barcode.gif"); - } + // Save the barcode as a GIF image, which is optimal for web delivery + generator.Save(outputPath, BarCodeImageFormat.Gif); + } - // Inform the user that the operation completed successfully. - Console.WriteLine("Barcode generated and saved as barcode.gif"); + // Inform the user where the barcode image has been saved + Console.WriteLine($"Barcode saved to {outputPath}"); + } } } \ No newline at end of file diff --git a/barcode-saving-and-export/create-barcode-with-custom-font-for-human-readable-text-and-export-it-as-svg-for-scalable-rendering.cs b/barcode-saving-and-export/create-barcode-with-custom-font-for-human-readable-text-and-export-it-as-svg-for-scalable-rendering.cs index 7a9657a..2254b76 100644 --- a/barcode-saving-and-export/create-barcode-with-custom-font-for-human-readable-text-and-export-it-as-svg-for-scalable-rendering.cs +++ b/barcode-saving-and-export/create-barcode-with-custom-font-for-human-readable-text-and-export-it-as-svg-for-scalable-rendering.cs @@ -1,41 +1,60 @@ -// Title: Generate Code39 Barcode with Custom Font and Export as SVG -// Description: Demonstrates creating a Code39 barcode, applying a custom font to the human‑readable text, and saving the result as an SVG file for scalable rendering. +// Title: Create Code39 barcode with custom font and export as SVG +// Description: Demonstrates how to generate a Code39 barcode, apply a custom font to the human‑readable text, and save it as an SVG file for scalable rendering. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, EncodeTypes, and BarCodeImageFormat classes. Typical use cases include creating barcodes with styled captions and exporting them to vector formats for web or print. Developers often need to customize appearance and choose scalable output formats like SVG. // Prompt: Create a barcode with custom font for human‑readable text and export it as SVG for scalable rendering. -// Tags: code39, barcode, custom font, svg, aspose.barcode, generation +// Tags: code39, custom font, svg, barcode generation, aspose.barcode, vector output using System; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; /// -/// Example program that generates a Code39 barcode with a custom font for the human‑readable text -/// and saves it as an SVG file for scalable rendering. +/// Demonstrates creating a Code39 barcode with a custom font for the human‑readable text and exporting it as an SVG file. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Generates the barcode and saves it to disk. /// static void Main() { - // Define the output file path for the generated SVG barcode. - string outputPath = "custom_font_barcode.svg"; + // Define the output file path for the SVG image + string outputPath = "barcode.svg"; - // Create a BarcodeGenerator for Code39 symbology with the desired code text. - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code39, "Sample123")) + // Resolve the full directory path and ensure it exists + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(outputDir)) { - // Set the font family and size for the human‑readable text. - generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Courier New"; + Directory.CreateDirectory(outputDir); + } + + // Initialize a BarcodeGenerator for Code39 with the desired data + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code39, "12345")) + { + // Set the barcode's foreground (bars) and background colors + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; + + // Customize the font of the human‑readable (code text) portion + generator.Parameters.Barcode.CodeTextParameters.Font.FamilyName = "Helvetica"; generator.Parameters.Barcode.CodeTextParameters.Font.Size.Point = 12f; - // Center the human‑readable text beneath the barcode. - generator.Parameters.Barcode.CodeTextParameters.Alignment = TextAlignment.Center; + // Optionally adjust the module (X) dimension for finer control over size + generator.Parameters.Barcode.XDimension.Point = 2f; - // Save the barcode as an SVG file to preserve scalability. - generator.Save(outputPath, BarCodeImageFormat.Svg); + // Attempt to save the barcode as an SVG file; handle evaluation‑license restrictions + try + { + generator.Save(outputPath, BarCodeImageFormat.Svg); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + catch (Exception ex) when (ex.Message.Contains("evaluation")) + { + Console.WriteLine("SVG export requires a full license for this symbology."); + Console.WriteLine(ex.Message); + } } - - // Inform the user that the barcode has been saved. - Console.WriteLine($"Barcode saved to {outputPath}"); } } \ No newline at end of file diff --git a/barcode-saving-and-export/embed-generated-barcode-image-into-html-img-tag-using-data-uri-from-memorystream.cs b/barcode-saving-and-export/embed-generated-barcode-image-into-html-img-tag-using-data-uri-from-memorystream.cs index b993d4e..376b473 100644 --- a/barcode-saving-and-export/embed-generated-barcode-image-into-html-img-tag-using-data-uri-from-memorystream.cs +++ b/barcode-saving-and-export/embed-generated-barcode-image-into-html-img-tag-using-data-uri-from-memorystream.cs @@ -1,43 +1,48 @@ -// Title: Generate Code128 Barcode and Embed as Data URI in HTML -// Description: Creates a Code128 barcode image, encodes it to Base64, and embeds it in an HTML img tag using a data URI. +// Title: Embed Barcode as Data URI in HTML +// Description: Demonstrates generating a Code128 barcode, converting it to PNG, and embedding it in an HTML img tag using a data URI. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator, EncodeTypes, and BarCodeImageFormat to create barcode images in memory. Typical use cases include embedding barcodes directly into web pages or emails without writing files to disk. Developers often need to convert generated images to Base64 strings for data URI usage, enabling seamless integration in HTML content. // Prompt: Embed a generated barcode image into an HTML img tag using a data URI from a MemoryStream. -// Tags: barcode, code128, datauri, html, memorystream, png, aspose.barcode +// Tags: barcode symbology, generation, png, data-uri, html, memorystream, aspose.barcode using System; using System.IO; -using System.Text; using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Demonstrates how to generate a barcode image, convert it to a Base64 data URI, -/// and embed it within an HTML tag. +/// Generates a Code128 barcode, converts it to a PNG image in memory, +/// and outputs an HTML tag with a data URI containing the image. /// class Program { /// - /// Entry point of the example. Generates a Code128 barcode, encodes it, - /// and writes the resulting HTML img tag to the console. + /// Entry point of the example. Writes the HTML img tag to the console. /// static void Main() { - // Initialize a barcode generator for Code128 with the sample text "1234567890" - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + // Define the text to encode in the barcode. + string codeText = "1234567890"; + + // Initialize the barcode generator for Code128 symbology. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) { - // Create a memory stream to hold the generated PNG image - using (var memoryStream = new MemoryStream()) + // Create a memory stream to hold the generated PNG image. + using (MemoryStream ms = new MemoryStream()) { - // Save the barcode image into the memory stream in PNG format - generator.Save(memoryStream, BarCodeImageFormat.Png); + // Save the barcode image into the memory stream in PNG format. + generator.Save(ms, BarCodeImageFormat.Png); + + // Retrieve the raw image bytes from the stream. + byte[] imageBytes = ms.ToArray(); - // Convert the image bytes from the memory stream to a Base64 string - string base64 = Convert.ToBase64String(memoryStream.ToArray()); + // Encode the image bytes to a Base64 string for the data URI. + string base64 = Convert.ToBase64String(imageBytes); - // Build the HTML tag using a data URI that embeds the Base64 image - string htmlImgTag = $"\"Barcode\""; + // Build the HTML tag with the data URI source. + string htmlImg = $"\"Barcode\""; - // Output the HTML tag to the console - Console.WriteLine(htmlImgTag); + // Output the HTML string to the console. + Console.WriteLine(htmlImg); } } } diff --git a/barcode-saving-and-export/export-barcode-as-emf-file-then-convert-it-to-pdf-using-third-party-library.cs b/barcode-saving-and-export/export-barcode-as-emf-file-then-convert-it-to-pdf-using-third-party-library.cs index a76be88..9eb17a7 100644 --- a/barcode-saving-and-export/export-barcode-as-emf-file-then-convert-it-to-pdf-using-third-party-library.cs +++ b/barcode-saving-and-export/export-barcode-as-emf-file-then-convert-it-to-pdf-using-third-party-library.cs @@ -1,48 +1,49 @@ -// Title: Export Code128 barcode to EMF and convert to PDF -// Description: Demonstrates generating a Code128 barcode, saving it as an EMF vector image, then embedding that image into a PDF using Aspose libraries. +// Title: Export barcode to EMF and convert to PDF +// Description: Demonstrates generating a Code128 barcode, saving it as an EMF vector image, and then embedding that image into a PDF using Aspose.Pdf. +// Category-Description: This example belongs to the Aspose.BarCode image export and document conversion category. It showcases the use of BarcodeGenerator for creating barcodes, BarCodeImageFormat for vector output, and Aspose.Pdf Document for embedding images into PDF files—common tasks for developers needing high‑quality printable barcodes in reports or invoices. // Prompt: Export a barcode as an EMF file, then convert it to PDF using a third‑party library. -// Tags: barcode, code128, export, emf, pdf, aspose.barcode, aspose.pdf +// Tags: barcode, code128, emf, pdf, aspose.barcode, aspose.pdf, image-export, document-conversion using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; using Aspose.Pdf; /// -/// Demonstrates exporting a barcode to EMF and converting it to PDF. +/// Generates a Code128 barcode, saves it as an EMF file, and converts the EMF to a PDF document. /// class Program { /// - /// Entry point. Generates a Code128 barcode, saves as EMF, then embeds into a PDF. + /// Entry point of the example. Executes barcode generation, EMF export, and PDF conversion. /// static void Main() { - // Define file paths for the intermediate EMF and final PDF files + // Define output file paths string emfPath = "barcode.emf"; string pdfPath = "barcode.pdf"; // ------------------------------------------------------------ - // Generate a Code128 barcode and save it as an EMF file + // Generate a barcode and export it as EMF // ------------------------------------------------------------ try { - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Optional: set image dimensions (in points) for better quality - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; + // Set barcode and background colors using Aspose.Drawing types + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; - // Save the generated barcode as an EMF vector image + // Save the barcode image in EMF format generator.Save(emfPath, BarCodeImageFormat.Emf); + Console.WriteLine($"Barcode saved as EMF: {emfPath}"); } } catch (Exception ex) { - // Handle licensing issues specific to EMF export for this barcode type - if (ex.Message.Contains("evaluation")) + // Handle licensing errors specific to EMF export + if (ex.Message.Contains("evaluation", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("A valid Aspose.BarCode license is required for EMF export of this barcode type."); return; @@ -50,43 +51,34 @@ static void Main() throw; } - // Verify that the EMF file was successfully created + // Verify that the EMF file was created before proceeding if (!File.Exists(emfPath)) { - Console.WriteLine($"Failed to create EMF file at '{emfPath}'."); + Console.WriteLine($"EMF file not found: {emfPath}"); return; } // ------------------------------------------------------------ // Convert the EMF image to a PDF document using Aspose.Pdf // ------------------------------------------------------------ - using (var pdfDocument = new Document()) + using (var pdfDoc = new Document()) { - // Add a new page to the PDF document - var page = pdfDocument.Pages.Add(); + // Add a new page to the PDF + var page = pdfDoc.Pages.Add(); - // Load the EMF image from the file system and add it to the PDF page + // Open the EMF file as a stream and embed it as an image using (var emfStream = new FileStream(emfPath, FileMode.Open, FileAccess.Read)) { - var pdfImage = new Aspose.Pdf.Image + var image = new Aspose.Pdf.Image { ImageStream = emfStream }; - page.Paragraphs.Add(pdfImage); + page.Paragraphs.Add(image); } - // Save the PDF document to the specified path - pdfDocument.Save(pdfPath); - } - - // Verify that the PDF file was successfully created and report the result - if (File.Exists(pdfPath)) - { - Console.WriteLine($"Barcode successfully exported to EMF ('{emfPath}') and converted to PDF ('{pdfPath}')."); - } - else - { - Console.WriteLine("PDF conversion failed."); + // Save the resulting PDF file + pdfDoc.Save(pdfPath); + Console.WriteLine($"PDF created from EMF: {pdfPath}"); } } } \ No newline at end of file diff --git a/barcode-saving-and-export/export-barcode-as-emf-vector-file-and-import-it-into-powerpoint-slide-programmatically.cs b/barcode-saving-and-export/export-barcode-as-emf-vector-file-and-import-it-into-powerpoint-slide-programmatically.cs index bb355a9..aff7dff 100644 --- a/barcode-saving-and-export/export-barcode-as-emf-vector-file-and-import-it-into-powerpoint-slide-programmatically.cs +++ b/barcode-saving-and-export/export-barcode-as-emf-vector-file-and-import-it-into-powerpoint-slide-programmatically.cs @@ -1,80 +1,93 @@ -// Title: Export Barcode to EMF and Embed in PowerPoint -// Description: Generates a Code128 barcode, saves it as an EMF vector image, and inserts the image into a PowerPoint slide. +// Title: Export barcode to EMF and embed in PowerPoint +// Description: Demonstrates generating a Code128 barcode, saving it as an EMF vector file, and programmatically inserting it into a PowerPoint slide. +// Category-Description: This example belongs to the Aspose.BarCode and Aspose.Slides integration category, showcasing how to use BarcodeGenerator to create vector images and Presentation to embed them. Typical use cases include automated report generation, batch creation of slide decks with barcodes, and dynamic document assembly. Developers often need to combine barcode creation with Office document manipulation, using classes like BarcodeGenerator, BarCodeImageFormat, Presentation, and ImageCollection. // Prompt: Export a barcode as an EMF vector file and import it into a PowerPoint slide programmatically. -// Tags: barcode, code128, export, emf, powerpoint, aspose.barcode, aspose.slides +// Tags: barcode, code128, emf, vector, powerpoint, aspose.barcode, aspose.slides, generation, import using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; using Aspose.Slides; using Aspose.Slides.Export; +using Aspose.Drawing; /// -/// Demonstrates how to generate a barcode, export it as an EMF vector file, -/// and embed the resulting image into a PowerPoint presentation using Aspose APIs. +/// Demonstrates exporting a barcode as an EMF file and embedding it into a PowerPoint presentation. /// class Program { /// - /// Entry point of the example. Generates a barcode, saves it as EMF, - /// creates a PowerPoint slide, and inserts the EMF image. + /// Entry point of the example. Generates a Code128 barcode, saves it as EMF, and creates a PPTX with the barcode image. /// static void Main() { - // Define file paths for the intermediate EMF image and the final PPTX file - string emfPath = "barcode.emf"; - string pptxPath = "barcode_presentation.pptx"; + // Prepare output directory and file paths + string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Output"); + Directory.CreateDirectory(outputDir); + string emfPath = Path.Combine(outputDir, "barcode.emf"); + string pptxPath = Path.Combine(outputDir, "BarcodePresentation.pptx"); // ----------------------------------------------------------------- - // 1. Generate a barcode and save it as an EMF vector image + // 1. Generate a barcode and export it as an EMF vector file // ----------------------------------------------------------------- try { - // Initialize the barcode generator with Code128 symbology and sample data - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Let the generator automatically determine the optimal size using interpolation - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; + // Optional visual settings + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; - // Export the barcode to an EMF file + // Save the barcode in EMF format generator.Save(emfPath, BarCodeImageFormat.Emf); + Console.WriteLine($"Barcode saved as EMF: {emfPath}"); } } catch (Exception ex) { - // Provide a clear message if the evaluation version blocks EMF export - if (ex.Message.Contains("evaluation")) + // EMF export requires a licensed version; handle evaluation limitation gracefully + if (ex.Message != null && ex.Message.Contains("evaluation", StringComparison.OrdinalIgnoreCase)) { - Console.WriteLine("A valid Aspose.BarCode license is required for EMF export of this barcode type."); + Console.WriteLine("A valid Aspose.BarCode license is required for EMF export."); return; } - // Re‑throw unexpected exceptions - throw; + Console.WriteLine($"Error generating barcode: {ex.Message}"); + return; } // ----------------------------------------------------------------- - // 2. Create a PowerPoint presentation and insert the EMF image + // 2. Create a PowerPoint presentation and embed the EMF image // ----------------------------------------------------------------- - using (Presentation pres = new Presentation()) + try { - // The newly created presentation contains a single default slide - var slide = pres.Slides[0]; + using (var presentation = new Presentation()) + { + // Use the first (default) slide + var slide = presentation.Slides[0]; - // Read the EMF file into a byte array and add it to the presentation's image collection - byte[] emfBytes = File.ReadAllBytes(emfPath); - IPPImage emfImage = pres.Images.AddImage(emfBytes); + // Load EMF image bytes and add to the presentation's image collection + byte[] emfBytes = File.ReadAllBytes(emfPath); + var image = presentation.Images.AddImage(emfBytes); - // Insert the EMF image onto the slide as a picture frame - // Position (0,0) and size (400x300) are arbitrary and can be adjusted as needed - slide.Shapes.AddPictureFrame(ShapeType.Rectangle, 0, 0, 400, 300, emfImage); + // Define picture frame position and size (in points) + float x = 50f; + float y = 50f; + float width = 400f; + float height = 150f; - // Save the populated presentation to a PPTX file - pres.Save(pptxPath, SaveFormat.Pptx); - } + // Insert the EMF image as a picture frame + slide.Shapes.AddPictureFrame(ShapeType.Rectangle, x, y, width, height, image); - Console.WriteLine("Barcode exported as EMF and embedded into PowerPoint slide successfully."); + // Save the presentation + presentation.Save(pptxPath, SaveFormat.Pptx); + Console.WriteLine($"Presentation saved: {pptxPath}"); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error creating presentation: {ex.Message}"); + } } } \ No newline at end of file diff --git a/barcode-saving-and-export/export-datamatrix-barcode-to-memory-stream-in-jpeg-format-for-http-response.cs b/barcode-saving-and-export/export-datamatrix-barcode-to-memory-stream-in-jpeg-format-for-http-response.cs index e4ebba9..5da60ae 100644 --- a/barcode-saving-and-export/export-datamatrix-barcode-to-memory-stream-in-jpeg-format-for-http-response.cs +++ b/barcode-saving-and-export/export-datamatrix-barcode-to-memory-stream-in-jpeg-format-for-http-response.cs @@ -1,46 +1,42 @@ -// Title: Export DataMatrix Barcode to JPEG Memory Stream -// Description: Generates a DataMatrix barcode, saves it as a JPEG into a memory stream, and outputs the image as a Base64 string for HTTP response demonstration. +// Title: Export DataMatrix Barcode to JPEG MemoryStream +// Description: Demonstrates exporting a DataMatrix barcode as a JPEG image into a memory stream, suitable for HTTP response. +// Category-Description: This example belongs to the Aspose.BarCode generation category, showcasing how to create barcodes using the BarcodeGenerator class, encode data into DataMatrix symbology, and output the result in JPEG format. Developers often need to generate barcode images on-the-fly for web APIs, embed them in HTML responses, or store them in databases. The example highlights key API classes such as BarcodeGenerator, EncodeTypes, and BarCodeImageFormat, providing a template for similar barcode export scenarios. // Prompt: Export a DataMatrix barcode to a memory stream in JPEG format for HTTP response. -// Tags: datamatrix, barcode-generation, export, jpeg, memorystream, aspose.barcode, aspose.barcode.generation +// Tags: datamatrix, export, jpeg, memorystream, barcode generation, aspose.barcode using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeRecognition; /// -/// Demonstrates how to generate a DataMatrix barcode and export it as a JPEG image -/// stored in a . The resulting image is shown as a Base64 -/// string, which can be sent in an HTTP response. +/// Provides an example of generating a DataMatrix barcode and exporting it as a JPEG image +/// into a memory stream, which can be used directly in an HTTP response. /// class Program { /// - /// Entry point of the example. Creates a DataMatrix barcode, saves it to a memory - /// stream in JPEG format, and writes the Base64 representation to the console. + /// Entry point of the example. Generates a DataMatrix barcode, saves it as JPEG into a + /// memory stream, and writes the resulting byte size to the console. /// static void Main() { - // Initialize a DataMatrix barcode generator with sample text. - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.DataMatrix, "Sample DataMatrix")) - { - // Let the generator automatically determine the optimal size using interpolation. - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; + // Define the text to encode in the barcode. + const string codeText = "Hello World"; - // Create a memory stream to hold the JPEG image. - using (MemoryStream memoryStream = new MemoryStream()) + // Create a memory stream that will hold the JPEG image data. + using (var memoryStream = new MemoryStream()) + { + // Initialize the barcode generator with DataMatrix symbology and the sample text. + using (var generator = new BarcodeGenerator(EncodeTypes.DataMatrix, codeText)) { - // Save the generated barcode into the memory stream as a JPEG. + // Save the generated barcode directly into the memory stream in JPEG format. generator.Save(memoryStream, BarCodeImageFormat.Jpeg); - - // Reset the stream position to the beginning for reading. - memoryStream.Position = 0; - - // Convert the JPEG bytes to a Base64 string for demonstration (e.g., HTTP response). - string base64Image = Convert.ToBase64String(memoryStream.ToArray()); - Console.WriteLine("DataMatrix JPEG (Base64):"); - Console.WriteLine(base64Image); } + + // Output the size of the generated JPEG image for verification. + Console.WriteLine($"Generated DataMatrix JPEG size: {memoryStream.Length} bytes"); } } } \ No newline at end of file diff --git a/barcode-saving-and-export/generate-barcode-and-write-it-directly-to-responseoutputstream-in-aspnet-for-immediate-download.cs b/barcode-saving-and-export/generate-barcode-and-write-it-directly-to-responseoutputstream-in-aspnet-for-immediate-download.cs index 47d1967..121a5d4 100644 --- a/barcode-saving-and-export/generate-barcode-and-write-it-directly-to-responseoutputstream-in-aspnet-for-immediate-download.cs +++ b/barcode-saving-and-export/generate-barcode-and-write-it-directly-to-responseoutputstream-in-aspnet-for-immediate-download.cs @@ -1,48 +1,52 @@ -// Title: Generate Code128 barcode and output as Base64 (console demo) -// Description: Demonstrates creating a Code128 barcode image using Aspose.BarCode, converting it to a Base64 string for display. In ASP.NET you would write the image directly to Response.OutputStream for download. +// Title: Generate Code128 barcode and stream as PNG in ASP.NET +// Description: Demonstrates creating a Code128 barcode with Aspose.BarCode and writing it directly to the HTTP response output stream for immediate download. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator class to produce barcode images in common formats such as PNG. Typical use cases include generating barcodes on-the-fly in web applications for inventory, shipping, or ticketing systems. Developers often need to stream the generated image directly to the client without intermediate files, using HttpResponse.OutputStream. // Prompt: Generate a barcode and write it directly to Response.OutputStream in ASP.NET for immediate download. -// Tags: barcode, code128, generation, png, memorystream, base64, aspose.barcode, asp.net +// Tags: code128, barcode, generation, png, aspnet, aspose.barcode, barcodegenerator using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing.Imaging; /// -/// Console application that generates a Code128 barcode, converts it to a Base64 string, -/// and writes the result to the console. In a web scenario the image would be sent -/// directly to the HTTP response stream for immediate download. +/// Demonstrates barcode generation using Aspose.BarCode and how the result could be streamed +/// directly to an ASP.NET response. In this console example the image is saved to a file for +/// verification purposes. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Generates a Code128 barcode, saves it to a PNG file, + /// and includes comments showing how to write the image to HttpResponse.OutputStream in a web context. /// static void Main() { - // NOTE: The original ASP.NET example cannot use Response.OutputStream in a console app, - // so we generate the barcode, store it in a memory stream, and output the image as Base64. + // NOTE: In an ASP.NET controller you would replace the file‑write logic with: + // HttpResponse response = HttpContext.Current.Response; + // response.ContentType = "image/png"; + // response.AddHeader("Content-Disposition", "attachment; filename=barcode.png"); + // generator.Save(response.OutputStream, BarCodeImageFormat.Png); + // response.End(); - // Create a barcode generator for Code128 with the desired text. + // Create a BarcodeGenerator for Code128 with the sample text "1234567890". using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Optional: customize barcode appearance (foreground and background colors). - generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; - generator.Parameters.BackColor = Aspose.Drawing.Color.White; - - // Use a memory stream to hold the generated PNG image. - using (var memory = new MemoryStream()) + // Prepare a memory stream to hold the PNG image. + using (var memoryStream = new MemoryStream()) { - // Save the barcode image into the memory stream in PNG format. - generator.Save(memory, BarCodeImageFormat.Png); + // Save the generated barcode into the memory stream in PNG format. + generator.Save(memoryStream, BarCodeImageFormat.Png); + memoryStream.Position = 0; // Reset the stream position for subsequent reading. - // Retrieve the raw image bytes from the memory stream. - byte[] imageBytes = memory.ToArray(); + // For this console demonstration, write the PNG image to a file in the current directory. + const string outputPath = "barcode.png"; + using (var fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) + { + memoryStream.CopyTo(fileStream); + } - // Convert the image bytes to a Base64 string for console output. - string base64 = Convert.ToBase64String(imageBytes); - Console.WriteLine(base64); + Console.WriteLine($"Barcode image saved to '{outputPath}'."); } } } diff --git a/barcode-saving-and-export/generate-barcode-obtain-bitmap-apply-grayscale-filter-then-save-as-jpeg.cs b/barcode-saving-and-export/generate-barcode-obtain-bitmap-apply-grayscale-filter-then-save-as-jpeg.cs index fbb06e9..f8f7a6e 100644 --- a/barcode-saving-and-export/generate-barcode-obtain-bitmap-apply-grayscale-filter-then-save-as-jpeg.cs +++ b/barcode-saving-and-export/generate-barcode-obtain-bitmap-apply-grayscale-filter-then-save-as-jpeg.cs @@ -1,7 +1,8 @@ -// Title: Generate Code128 barcode, convert to grayscale, and save as JPEG -// Description: Demonstrates creating a barcode image, applying a simple grayscale filter, and persisting the result as a JPEG file. +// Title: Generate Code128 barcode, apply grayscale filter, and save as JPEG +// Description: This example creates a Code128 barcode, converts it to a bitmap, applies a grayscale filter, and saves the result as a JPEG file. +// Category-Description: Demonstrates Aspose.BarCode image generation and manipulation using Aspose.Drawing. It shows how to generate a barcode with BarcodeGenerator, obtain a Bitmap, process pixel data, and save in a common image format. Developers working with barcode rendering, image post‑processing, or custom graphics pipelines often need these steps. // Prompt: Generate a barcode, obtain a Bitmap, apply a grayscale filter, then save as JPEG. -// Tags: barcode, code128, grayscale, jpeg, aspose.barcode, aspose.drawing, image-processing +// Tags: code128, barcode, grayscale, jpeg, bitmap, aspose.barcode, aspose.drawing, image-processing using System; using System.IO; @@ -11,54 +12,57 @@ using Aspose.Drawing.Imaging; /// -/// Demonstrates barcode generation, grayscale conversion, and JPEG saving using Aspose.BarCode and Aspose.Drawing. +/// Example program that generates a Code128 barcode, converts it to a grayscale bitmap, +/// and saves the image as a JPEG file using Aspose.BarCode and Aspose.Drawing APIs. /// class Program { /// - /// Entry point. Generates a Code128 barcode, converts it to grayscale, and writes it to a JPEG file. + /// Entry point of the application. /// static void Main() { - // Define the output file path for the final JPEG image + // Define the output file path for the JPEG image. string outputPath = "barcode.jpg"; - // Initialize a barcode generator for Code128 with the sample text "123456" - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) + // Ensure the target directory exists; create it if necessary. + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(outputDir)) { - // Generate the barcode image as a bitmap (color) - using (Bitmap barcodeBitmap = generator.GenerateBarCodeImage()) + Directory.CreateDirectory(outputDir); + } + + // Initialize a barcode generator for Code128 with the sample text "Sample123". + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + { + // Generate the barcode image as an Aspose.Drawing.Bitmap. + using (Bitmap bitmap = generator.GenerateBarCodeImage()) { - // Create a new bitmap with the same dimensions to hold the grayscale version - using (Bitmap grayBitmap = new Bitmap(barcodeBitmap.Width, barcodeBitmap.Height)) + // Iterate over each pixel to apply a simple grayscale filter. + for (int y = 0; y < bitmap.Height; y++) { - // Iterate over each pixel to compute its grayscale value - for (int y = 0; y < barcodeBitmap.Height; y++) + for (int x = 0; x < bitmap.Width; x++) { - for (int x = 0; x < barcodeBitmap.Width; x++) - { - // Retrieve the original color of the current pixel - Color original = barcodeBitmap.GetPixel(x, y); - // Compute the average of the RGB components to obtain a gray intensity - int gray = (original.R + original.G + original.B) / 3; - // Create a new color where R, G, and B are all set to the gray intensity - Color grayColor = Color.FromArgb(gray, gray, gray); - // Set the pixel in the grayscale bitmap - grayBitmap.SetPixel(x, y, grayColor); - } - } + // Retrieve the original pixel color. + Color original = bitmap.GetPixel(x, y); - // Open a file stream to write the grayscale bitmap as a JPEG image - using (FileStream fs = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) - { - // Save the bitmap using the JPEG image format - grayBitmap.Save(fs, ImageFormat.Jpeg); + // Compute the luminance as the average of the RGB components. + int gray = (original.R + original.G + original.B) / 3; + + // Create a new color with full opacity and the computed gray value. + Color grayColor = Color.FromArgb(255, gray, gray, gray); + + // Set the pixel to the new grayscale color. + bitmap.SetPixel(x, y, grayColor); } } + + // Save the processed bitmap to the specified path in JPEG format. + bitmap.Save(outputPath, ImageFormat.Jpeg); } } - // Output the full path of the saved JPEG file for verification - Console.WriteLine($"Barcode saved as JPEG at: {Path.GetFullPath(outputPath)}"); + // Inform the user where the image has been saved. + Console.WriteLine($"Barcode image saved to: {Path.GetFullPath(outputPath)}"); } } \ No newline at end of file diff --git a/barcode-saving-and-export/generate-barcode-obtain-bitmap-draw-additional-text-with-gdi-then-save-as-png.cs b/barcode-saving-and-export/generate-barcode-obtain-bitmap-draw-additional-text-with-gdi-then-save-as-png.cs index 3858bdb..4a74c5a 100644 --- a/barcode-saving-and-export/generate-barcode-obtain-bitmap-draw-additional-text-with-gdi-then-save-as-png.cs +++ b/barcode-saving-and-export/generate-barcode-obtain-bitmap-draw-additional-text-with-gdi-then-save-as-png.cs @@ -1,7 +1,8 @@ -// Title: Generate Code128 barcode, add custom text, and save as PNG -// Description: Creates a Code128 barcode, draws extra text using GDI+, and writes the result to a PNG file. +// Title: Generate Code128 barcode, add custom text with GDI+, save as PNG +// Description: Demonstrates creating a Code128 barcode using Aspose.BarCode, converting it to a Bitmap, drawing extra text with GDI+, and saving the result as a PNG file. +// Category-Description: This example belongs to the Aspose.BarCode generation and image manipulation category. It showcases the use of BarcodeGenerator, BarCodeImageFormat, and Aspose.Drawing classes to produce a barcode image, modify it with GDI+ graphics, and export it. Developers often need to embed additional information or branding onto barcode images, and this pattern illustrates the typical workflow for such customizations. // Prompt: Generate a barcode, obtain a Bitmap, draw additional text with GDI+, then save as PNG. -// Tags: code128, barcode, gdi+, png, aspose.barcode, aspose.drawing +// Tags: code128, barcode generation, png, aspose.barcodes, aspose.drawing, gdi+, bitmap, text overlay using System; using System.IO; @@ -11,54 +12,54 @@ using Aspose.Drawing.Imaging; /// -/// Demonstrates how to generate a barcode, overlay custom text using GDI+, and save the result as a PNG image. +/// Example program that creates a Code128 barcode, adds custom text using GDI+, and saves the result as a PNG image. /// class Program { /// - /// Entry point of the example. Generates a barcode, adds text, and saves the image. + /// Entry point of the application. /// static void Main() { - // Define the output file path for the final PNG image + // Define the output file path for the final image. string outputPath = "barcode_with_text.png"; - // Initialize a barcode generator for Code128 with the sample code text + // Initialize a barcode generator for Code128 with the desired code text. using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Configure auto‑size mode and set explicit image dimensions (points) - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; - generator.Parameters.ImageWidth.Point = 300f; - generator.Parameters.ImageHeight.Point = 150f; + // Set the module (X) dimension to control barcode size. + generator.Parameters.Barcode.XDimension.Point = 2f; - // Generate the barcode image as a bitmap - using (var barcodeBitmap = generator.GenerateBarCodeImage()) + // Save the generated barcode to a memory stream in PNG format. + using (var ms = new MemoryStream()) { - // Create a Graphics object to draw additional text onto the bitmap - using (var graphics = Graphics.FromImage(barcodeBitmap)) + generator.Save(ms, BarCodeImageFormat.Png); + ms.Position = 0; // Reset stream position for reading. + + // Load the barcode image from the memory stream as a Bitmap. + using (var barcodeImage = (Bitmap)Image.FromStream(ms)) { - // Define the font and brush used for the overlay text - using (var font = new Font("Arial", 12f)) - using (var brush = new SolidBrush(Color.Black)) + // Create a Graphics object to draw on the bitmap. + using (var graphics = Graphics.FromImage(barcodeImage)) { - // Calculate the position near the bottom of the image - float x = 10f; - float y = barcodeBitmap.Height - 30f; + string extraText = "Sample Text"; - // Render the custom text onto the bitmap - graphics.DrawString("Sample Text", font, brush, new PointF(x, y)); + // Define the font and brush for the overlay text. + using (var font = new Font("Arial", 12f)) + using (var brush = new SolidBrush(Color.Black)) + { + // Calculate position near the bottom‑right corner. + var position = new PointF(barcodeImage.Width - 100f, barcodeImage.Height - 20f); + graphics.DrawString(extraText, font, brush, position); + } } - } - // Save the modified bitmap to a PNG file using a file stream - using (var fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) - { - barcodeBitmap.Save(fileStream, ImageFormat.Png); + // Save the modified bitmap (barcode + text) as a PNG file. + barcodeImage.Save(outputPath, ImageFormat.Png); } } } - // Output the full path of the saved image for verification - Console.WriteLine($"Barcode image saved to: {Path.GetFullPath(outputPath)}"); + Console.WriteLine($"Barcode image saved to: {outputPath}"); } } \ No newline at end of file diff --git a/barcode-saving-and-export/generate-barcode-set-its-margins-and-export-as-svg-ensuring-viewbox-matches-barcode-size.cs b/barcode-saving-and-export/generate-barcode-set-its-margins-and-export-as-svg-ensuring-viewbox-matches-barcode-size.cs index e801b35..bfa0c6f 100644 --- a/barcode-saving-and-export/generate-barcode-set-its-margins-and-export-as-svg-ensuring-viewbox-matches-barcode-size.cs +++ b/barcode-saving-and-export/generate-barcode-set-its-margins-and-export-as-svg-ensuring-viewbox-matches-barcode-size.cs @@ -1,39 +1,58 @@ -// Title: Generate Code39 Barcode with Margins and Export as SVG -// Description: Creates a Code39 barcode, applies uniform padding, and saves it as an SVG file with a viewBox that matches the barcode dimensions. +// Title: Generate Code39 barcode with margins and export to SVG +// Description: Demonstrates creating a Code39 barcode, applying custom margins, and saving it as an SVG file where the viewBox matches the barcode dimensions. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode parameters such as padding, colors, and AutoSizeMode using the BarcodeGenerator class. Typical use cases include generating barcodes for web or print with precise layout control. Developers often need to export barcodes to vector formats like SVG while preserving exact sizing for responsive designs. // Prompt: Generate a barcode, set its margins, and export as SVG ensuring the viewBox matches the barcode size. -// Tags: code39, barcode, margin, svg, aspose.barcode, generation +// Tags: code39, barcode, margin, svg, autosizemode, aspose.barcode, generation using System; +using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; +using Aspose.Drawing; -/// -/// Demonstrates barcode generation, margin configuration, and SVG export using Aspose.BarCode. -/// -class Program +namespace BarcodeSvgExample { /// - /// Entry point of the application. Generates a Code39 barcode, sets padding, and saves it as an SVG file. + /// Provides an entry point that generates a Code39 barcode, applies padding, + /// and saves the result as an SVG file with a viewBox that matches the barcode size. /// - static void Main() + class Program { - // Initialize the barcode generator with Code39 symbology and sample data - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code39, "Sample123")) + /// + /// Generates the barcode, configures its appearance, and writes the SVG output. + /// + static void Main() { - // Set uniform padding (10 points) on all sides of the barcode - generator.Parameters.Barcode.Padding.Left.Point = 10f; - generator.Parameters.Barcode.Padding.Top.Point = 10f; - generator.Parameters.Barcode.Padding.Right.Point = 10f; - generator.Parameters.Barcode.Padding.Bottom.Point = 10f; + // Define the output SVG file path + string outputPath = "barcode.svg"; - // Ensure the generated image size matches the barcode dimensions - generator.Parameters.AutoSizeMode = AutoSizeMode.Interpolation; + // Initialize a Code39 barcode generator with the sample text "123ABC" + using (var generator = new BarcodeGenerator(EncodeTypes.Code39, "123ABC")) + { + // Configure padding (margins) in points for each side + generator.Parameters.Barcode.Padding.Left.Point = 10f; + generator.Parameters.Barcode.Padding.Top.Point = 10f; + generator.Parameters.Barcode.Padding.Right.Point = 10f; + generator.Parameters.Barcode.Padding.Bottom.Point = 10f; - // Save the barcode as an SVG file; the viewBox will correspond to the barcode size - generator.Save("barcode.svg"); - } + // Optional: set foreground (barcode) and background colors + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + generator.Parameters.BackColor = Aspose.Drawing.Color.White; + + // Ensure the SVG viewBox matches the exact barcode size (no auto‑scaling) + generator.Parameters.AutoSizeMode = AutoSizeMode.None; - // Inform the user that the barcode has been successfully generated and saved - Console.WriteLine("Barcode generated and saved as barcode.svg"); + // Attempt to save the barcode as an SVG file and report the result + try + { + generator.Save(outputPath, BarCodeImageFormat.Svg); + Console.WriteLine($"Barcode saved to {Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error saving SVG: {ex.Message}"); + } + } + } } } \ No newline at end of file diff --git a/barcode-saving-and-export/generate-barcode-set-its-rotation-angle-and-save-as-bmp-file-preserving-orientation.cs b/barcode-saving-and-export/generate-barcode-set-its-rotation-angle-and-save-as-bmp-file-preserving-orientation.cs index e94e1aa..1547687 100644 --- a/barcode-saving-and-export/generate-barcode-set-its-rotation-angle-and-save-as-bmp-file-preserving-orientation.cs +++ b/barcode-saving-and-export/generate-barcode-set-its-rotation-angle-and-save-as-bmp-file-preserving-orientation.cs @@ -1,42 +1,37 @@ -// Title: Rotated Code128 Barcode Generation and BMP Export -// Description: Demonstrates creating a Code128 barcode, rotating it 90 degrees, and saving the image as a BMP while preserving orientation. +// Title: Generate Rotated Code128 Barcode and Save as BMP +// Description: Demonstrates creating a Code128 barcode, applying a rotation angle, and saving it as a BMP image while preserving orientation. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode parameters such as rotation using the BarcodeGenerator class. Typical use cases include producing barcodes for printed labels that require specific orientation. Developers often need to set rotation, size, and format before saving the image with BarCodeImageFormat. // Prompt: Generate a barcode, set its rotation angle, and save as a BMP file preserving orientation. -// Tags: barcode, code128, rotation, bmp, aspose.barcode, generation +// Tags: code128, rotation, bmp, barcode, generation, aspose.barcode using System; using Aspose.BarCode; using Aspose.BarCode.Generation; -namespace BarcodeExample +/// +/// Example program that creates a rotated Code128 barcode and saves it as a BMP file. +/// +class Program { /// - /// Example program that generates a rotated Code128 barcode and saves it as a BMP file. + /// Entry point of the application. /// - class Program + static void Main() { - /// - /// Entry point of the application. Creates a barcode, applies rotation, and writes the image to disk. - /// - static void Main() - { - // Define the output file path for the rotated barcode image. - string outputPath = "rotated_barcode.bmp"; - - // Initialize a barcode generator for Code128 with the sample text "Sample123". - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) - { - // Set the rotation angle to 90 degrees (float value required by the API). - generator.Parameters.RotationAngle = 90f; - - // Optional: increase the resolution to 300 DPI for higher image quality. - generator.Parameters.Resolution = 300; + // Define the output file path for the generated barcode image. + string outputPath = "rotated_barcode.bmp"; - // Save the barcode as a BMP file; the format is inferred from the file extension. - generator.Save(outputPath); - } + // Initialize a BarcodeGenerator for Code128 symbology with sample data. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "123456789")) + { + // Set the rotation angle to 90 degrees (float value required by the API). + generator.Parameters.RotationAngle = 90f; - // Inform the user that the barcode has been saved. - Console.WriteLine($"Barcode saved to {outputPath}"); + // Save the barcode image as BMP, preserving the specified orientation. + generator.Save(outputPath, BarCodeImageFormat.Bmp); } + + // Inform the user where the barcode image has been saved. + Console.WriteLine($"Barcode saved to {outputPath}"); } } \ No newline at end of file diff --git a/barcode-saving-and-export/generate-ean13-barcode-and-write-it-directly-to-filestream-using-asynchronous-i-o.cs b/barcode-saving-and-export/generate-ean13-barcode-and-write-it-directly-to-filestream-using-asynchronous-i-o.cs index 7019282..7c72fa5 100644 --- a/barcode-saving-and-export/generate-ean13-barcode-and-write-it-directly-to-filestream-using-asynchronous-i-o.cs +++ b/barcode-saving-and-export/generate-ean13-barcode-and-write-it-directly-to-filestream-using-asynchronous-i-o.cs @@ -1,7 +1,8 @@ // Title: Generate EAN13 barcode and save asynchronously to file -// Description: Demonstrates creating an EAN13 barcode with Aspose.BarCode and writing the PNG image directly to a FileStream using async I/O. +// Description: Creates an EAN13 barcode image and writes it directly to a PNG file using asynchronous file I/O. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator and related parameter classes to produce barcodes. Typical use cases include creating product labels, inventory tags, or any scenario requiring EAN13 symbology. Developers often need to generate barcode images and store them efficiently, leveraging asynchronous I/O for better performance in server or cloud environments. // Prompt: Generate an EAN13 barcode and write it directly to a FileStream using asynchronous I/O. -// Tags: ean13, barcode, async, filestream, aspose.barcode, png +// Tags: ean13, barcode, asynchronous, fileio, aspose.barcode, png, generation using System; using System.IO; @@ -10,29 +11,26 @@ using Aspose.BarCode.Generation; /// -/// Example program that generates an EAN13 barcode and writes it to a PNG file using asynchronous I/O. +/// Demonstrates generating an EAN13 barcode and saving it asynchronously to a PNG file. /// class Program { /// - /// Asynchronously creates an EAN13 barcode image and saves it to a file. + /// Asynchronously generates the barcode and writes it to disk. /// - /// Command‑line arguments (not used). - static async Task Main(string[] args) + static async Task Main() { - // Define the output file path for the generated PNG image - const string outputPath = "ean13.png"; + // Define the output file path for the generated barcode image. + string outputPath = "ean13.png"; - // EAN13 barcode requires exactly 12 numeric characters; the checksum digit is added automatically - const string codeText = "123456789012"; - - // Initialize the barcode generator for the EAN13 symbology with the provided code text - using (var generator = new BarcodeGenerator(EncodeTypes.EAN13, codeText)) + // Initialize a BarcodeGenerator for the EAN13 symbology. + // The provided 12‑digit string will have its checksum calculated automatically. + using (var generator = new BarcodeGenerator(EncodeTypes.EAN13, "123456789012")) { - // Configure the human‑readable text to appear below the barcode bars - generator.Parameters.Barcode.CodeTextParameters.Location = CodeLocation.Below; + // Suppress exceptions for minor code‑text inaccuracies. + generator.Parameters.Barcode.ThrowExceptionWhenCodeTextIncorrect = false; - // Open a FileStream for writing the image; enable asynchronous operations + // Open a FileStream with asynchronous I/O enabled. using (var fileStream = new FileStream( outputPath, FileMode.Create, @@ -41,15 +39,15 @@ static async Task Main(string[] args) bufferSize: 4096, useAsync: true)) { - // Save the generated barcode directly to the stream in PNG format + // Save the barcode image directly to the stream (synchronous write to the stream). generator.Save(fileStream, BarCodeImageFormat.Png); - // Flush any buffered data to the underlying file asynchronously + // Flush any buffered data to the underlying file asynchronously. await fileStream.FlushAsync(); } } - // Inform the user that the barcode has been saved + // Inform the user that the barcode has been saved. Console.WriteLine($"EAN13 barcode saved to {outputPath}"); } } \ No newline at end of file diff --git a/barcode-saving-and-export/generate-qr-code-and-save-it-as-png-file-with-300-dpi-resolution.cs b/barcode-saving-and-export/generate-qr-code-and-save-it-as-png-file-with-300-dpi-resolution.cs index 51d43d3..8110b2d 100644 --- a/barcode-saving-and-export/generate-qr-code-and-save-it-as-png-file-with-300-dpi-resolution.cs +++ b/barcode-saving-and-export/generate-qr-code-and-save-it-as-png-file-with-300-dpi-resolution.cs @@ -1,33 +1,36 @@ // Title: Generate QR Code PNG with 300 DPI -// Description: Creates a QR code containing 'Hello World' and saves it as a PNG image at 300 DPI resolution. +// Description: This example creates a QR code containing sample text and saves it as a PNG image with a resolution of 300 DPI. +// Category-Description: Demonstrates Aspose.BarCode generation of 2‑D barcodes. The example uses BarcodeGenerator, EncodeTypes, and BarCodeImageFormat to produce a QR code image. Typical use cases include creating printable QR codes for marketing, product tracking, or authentication. Developers often need to set image resolution, format, and content when integrating barcode generation into .NET applications. // Prompt: Generate a QR code and save it as a PNG file with 300 DPI resolution. -// Tags: qr, barcode, generation, png, 300dpi, aspose.barcode +// Tags: qr code, generation, png, resolution, aspose.barcode, barcodegenerator using System; -using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Demonstrates generating a QR code and saving it as a PNG file with 300 DPI resolution using Aspose.BarCode. +/// Example program that generates a QR code and saves it as a PNG file with 300 DPI resolution. /// class Program { /// - /// Entry point of the example. Generates the QR code and writes it to disk. + /// Entry point of the application. /// static void Main() { - // Initialize the QR code generator with the QR symbology. - using (var generator = new BarcodeGenerator(EncodeTypes.QR)) - { - // Define the data to encode in the QR code. - generator.CodeText = "Hello World"; + // Define the output file path for the generated QR code image. + string outputPath = "qr.png"; - // Configure the output image resolution (dots per inch). + // Initialize the barcode generator with QR encoding and the desired text. + using (var generator = new BarcodeGenerator(EncodeTypes.QR, "Hello World")) + { + // Configure the image resolution to 300 DPI for high‑quality output. generator.Parameters.Resolution = 300; - // Persist the generated QR code as a PNG file. - generator.Save("qr.png"); + // Save the generated QR code as a PNG file at the specified location. + generator.Save(outputPath, BarCodeImageFormat.Png); } + + // Inform the user that the QR code has been successfully saved. + Console.WriteLine($"QR code saved to {outputPath}"); } } \ No newline at end of file diff --git a/barcode-saving-and-export/produce-barcode-with-transparent-background-and-export-it-as-png-preserving-alpha-channel.cs b/barcode-saving-and-export/produce-barcode-with-transparent-background-and-export-it-as-png-preserving-alpha-channel.cs index e6df108..5bec91c 100644 --- a/barcode-saving-and-export/produce-barcode-with-transparent-background-and-export-it-as-png-preserving-alpha-channel.cs +++ b/barcode-saving-and-export/produce-barcode-with-transparent-background-and-export-it-as-png-preserving-alpha-channel.cs @@ -1,43 +1,35 @@ // Title: Generate a Code128 barcode with transparent background and save as PNG -// Description: Demonstrates creating a barcode with a transparent background and exporting it as a PNG while preserving the alpha channel. +// Description: Demonstrates creating a Code128 barcode, setting a transparent background, and exporting it to a PNG file while preserving the alpha channel. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to customize barcode appearance using the BarcodeGenerator class. Typical use cases include creating barcodes for web or UI overlays where background transparency is required. Developers often need to adjust colors, backgrounds, and export formats using the Parameters property and Save method. // Prompt: Produce a barcode with transparent background and export it as PNG preserving the alpha channel. -// Tags: code128, barcode, transparent background, png, aspose.barcode, aspose.drawing +// Tags: code128, barcode generation, transparent background, png, aspose.barcode, aspose.drawing using System; -using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; /// -/// Example program that creates a Code128 barcode with a transparent background -/// and saves it as a PNG image preserving the alpha channel. +/// Demonstrates generating a barcode with a transparent background and saving it as a PNG image. /// class Program { /// - /// Entry point of the application. - /// Generates the barcode, configures colors, and writes the PNG file. + /// Entry point of the example. Creates a Code128 barcode, applies a transparent background, and saves it. /// static void Main() { - // Define the output file name (saved in the current working directory) - string outputPath = "transparent_barcode.png"; - - // Initialize the barcode generator with the desired symbology (Code128) and data - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // Initialize the barcode generator with Code128 symbology and sample text. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) { - // Configure the background to be fully transparent - generator.Parameters.BackColor = Color.Transparent; - - // Optionally set the foreground (bars) color; black is used here - generator.Parameters.Barcode.BarColor = Color.Black; + // Set the background color to transparent so the PNG retains the alpha channel. + generator.Parameters.BackColor = Aspose.Drawing.Color.Transparent; - // Save the generated barcode as a PNG file; transparency is retained in the output - generator.Save(outputPath, BarCodeImageFormat.Png); + // Save the generated barcode as a PNG file; transparency is preserved. + generator.Save("transparent_barcode.png"); } - // Output the absolute path of the saved image for user reference - Console.WriteLine("Barcode saved to: " + Path.GetFullPath(outputPath)); + // Inform the user that the barcode has been generated. + Console.WriteLine("Barcode generated with transparent background."); } } \ No newline at end of file diff --git a/barcode-saving-and-export/save-barcode-as-jpeg-with-quality-level-set-to-80-to-balance-size-and-readability.cs b/barcode-saving-and-export/save-barcode-as-jpeg-with-quality-level-set-to-80-to-balance-size-and-readability.cs index 1e68248..cee8971 100644 --- a/barcode-saving-and-export/save-barcode-as-jpeg-with-quality-level-set-to-80-to-balance-size-and-readability.cs +++ b/barcode-saving-and-export/save-barcode-as-jpeg-with-quality-level-set-to-80-to-balance-size-and-readability.cs @@ -1,53 +1,60 @@ -// Title: Save Barcode as JPEG with Specified Quality -// Description: Generates a Code128 barcode and saves it as a JPEG image with quality level 80 to balance file size and readability. +// Title: Save Code128 barcode as JPEG with quality 80 +// Description: Demonstrates generating a Code128 barcode and saving it as a JPEG image with a quality setting of 80 to balance file size and readability. +// Category-Description: This example belongs to the Aspose.BarCode image generation category, illustrating how to use BarcodeGenerator, Bitmap, and image encoding classes to produce barcode images. Typical use cases include creating printable barcodes for inventory, shipping labels, or product packaging, where developers need control over output format and compression quality. The snippet shows how to locate the JPEG codec and apply EncoderParameters for quality settings. // Prompt: Save a barcode as a JPEG with quality level set to 80 to balance size and readability. -// Tags: code128, barcode, jpeg, quality, aspose.barcode, aspose.drawing +// Tags: code128, barcode generation, jpeg, image quality, aspose.barcode, aspose.drawing using System; -using System.Linq; +using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Demonstrates how to generate a Code128 barcode and save it as a JPEG -/// with a specific quality setting using Aspose.BarCode and Aspose.Drawing. +/// Generates a Code128 barcode and saves it as a JPEG image with a quality level of 80. /// class Program { /// - /// Entry point of the example. Generates the barcode and writes it to disk. + /// Entry point of the example. Creates the barcode, configures JPEG encoding, and writes the file. /// static void Main() { - // Initialize a barcode generator for Code128 with the sample text "Sample123" - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + // Define the output file path for the JPEG image. + string outputPath = "barcode.jpg"; + + // Initialize the barcode generator with Code128 symbology and sample data. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Render the barcode to a bitmap image + // Generate the barcode as a Bitmap object. using (Bitmap bitmap = generator.GenerateBarCodeImage()) { - // Locate the JPEG image codec from the installed encoders - ImageCodecInfo jpegCodec = ImageCodecInfo.GetImageEncoders() - .FirstOrDefault(codec => codec.FormatID == ImageFormat.Jpeg.Guid); + // Locate the JPEG codec among the installed image encoders. + ImageCodecInfo jpegCodec = null; + foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageEncoders()) + { + if (codec.FormatID == ImageFormat.Jpeg.Guid) + { + jpegCodec = codec; + break; + } + } - // If the JPEG codec cannot be found, fall back to default saving + // If the JPEG codec is not found, report the issue and exit. if (jpegCodec == null) { - Console.WriteLine("JPEG codec not found. Saving with default settings."); - bitmap.Save("barcode.jpg", ImageFormat.Jpeg); + Console.WriteLine("JPEG codec not found."); return; } - // Prepare encoder parameters to set JPEG quality to 80 (value must be a long) + // Configure encoder parameters to set JPEG quality to 80 (range 0-100). EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 80L); - // Save the bitmap as a JPEG file using the specified codec and quality settings - bitmap.Save("barcode.jpg", jpegCodec, encoderParams); + // Save the bitmap as a JPEG file using the selected codec and quality settings. + bitmap.Save(outputPath, jpegCodec, encoderParams); + Console.WriteLine($"Barcode saved to {outputPath}"); } } - - // Inform the user that the operation completed successfully - Console.WriteLine("Barcode saved as barcode.jpg with quality 80."); } } \ No newline at end of file diff --git a/barcode-saving-and-export/save-barcode-as-tiff-file-with-lzw-compression-enabled-to-reduce-file-size.cs b/barcode-saving-and-export/save-barcode-as-tiff-file-with-lzw-compression-enabled-to-reduce-file-size.cs index 190d4d5..3ef7f39 100644 --- a/barcode-saving-and-export/save-barcode-as-tiff-file-with-lzw-compression-enabled-to-reduce-file-size.cs +++ b/barcode-saving-and-export/save-barcode-as-tiff-file-with-lzw-compression-enabled-to-reduce-file-size.cs @@ -1,62 +1,64 @@ // Title: Save Barcode as TIFF with LZW Compression -// Description: Generates a Code128 barcode and saves it as a TIFF image using LZW compression to reduce file size. +// Description: Demonstrates saving a Code128 barcode to a TIFF file using LZW compression to reduce file size. +// Category-Description: This example belongs to the Aspose.BarCode image generation category. It shows how to use the BarcodeGenerator class to create a barcode, render it as a bitmap, and then save the image with specific encoder settings (LZW compression) via Aspose.Drawing.Imaging. Developers often need to export barcodes to various formats with optimized file sizes for storage or transmission. // Prompt: Save a barcode as a TIFF file with LZW compression enabled to reduce file size. -// Tags: barcode, code128, tiff, lzw, compression, aspose.barcode, aspose.drawing +// Tags: code128, barcode generation, tiff, lzw compression, aspose.barcode, image saving using System; -using System.IO; -using System.Linq; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; using Aspose.Drawing.Imaging; /// -/// Demonstrates how to generate a barcode and save it as a TIFF file with LZW compression. +/// Example program that generates a Code128 barcode and saves it as a TIFF file +/// using LZW compression to minimize the output file size. /// class Program { /// - /// Entry point of the application. Generates a Code128 barcode and writes it to a compressed TIFF file. + /// Entry point of the example. Generates the barcode and writes the compressed TIFF file. /// static void Main() { // Define the output file path for the TIFF image string outputPath = "barcode.tiff"; - // Ensure the target directory exists; create it if necessary - string directory = Path.GetDirectoryName(Path.GetFullPath(outputPath)); - if (!Directory.Exists(directory)) - { - Directory.CreateDirectory(directory); - } - // Initialize the barcode generator with Code128 symbology and sample data - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "Sample123")) + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Generate the barcode as a bitmap image + // Render the barcode to a bitmap image using (Bitmap bitmap = generator.GenerateBarCodeImage()) { // Locate the TIFF image codec from the installed encoders - ImageCodecInfo tiffCodec = ImageCodecInfo.GetImageEncoders() - .FirstOrDefault(c => c.FormatID == ImageFormat.Tiff.Guid); + ImageCodecInfo tiffCodec = null; + foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageEncoders()) + { + if (codec.FormatID == ImageFormat.Tiff.Guid) + { + tiffCodec = codec; + break; + } + } + + // If the TIFF codec is not found, abort with a message if (tiffCodec == null) { - Console.WriteLine("TIFF codec not found."); + Console.WriteLine("TIFF codec not found. Cannot save with LZW compression."); return; } - // Configure encoder parameters to use LZW compression + // Configure encoder parameters to enable LZW compression using (EncoderParameters encoderParams = new EncoderParameters(1)) { encoderParams.Param[0] = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionLZW); - // Save the bitmap as a TIFF file with the specified compression + // Save the bitmap as a TIFF file using the selected codec and compression settings bitmap.Save(outputPath, tiffCodec, encoderParams); } } } - // Inform the user that the barcode has been saved - Console.WriteLine($"Barcode saved to {outputPath}"); + // Inform the user that the barcode has been saved successfully + Console.WriteLine($"Barcode saved to {outputPath} with LZW compression."); } } \ No newline at end of file diff --git a/barcode-saving-and-export/save-barcode-directly-to-memorystream-and-convert-stream-to-base64-string.cs b/barcode-saving-and-export/save-barcode-directly-to-memorystream-and-convert-stream-to-base64-string.cs index 4c4e4ee..77acade 100644 --- a/barcode-saving-and-export/save-barcode-directly-to-memorystream-and-convert-stream-to-base64-string.cs +++ b/barcode-saving-and-export/save-barcode-directly-to-memorystream-and-convert-stream-to-base64-string.cs @@ -1,7 +1,8 @@ -// Title: Generate Code128 Barcode and Encode as Base64 -// Description: Creates a Code128 barcode, saves it to a MemoryStream as PNG, and converts the image bytes to a Base64 string for easy transport or embedding. +// Title: Save barcode to MemoryStream and convert to Base64 string +// Description: Demonstrates generating a Code128 barcode, saving it directly to a MemoryStream in PNG format, and converting the image bytes to a Base64 string for easy transport or embedding. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator class to create barcodes, work with in‑memory streams, and produce Base64‑encoded output. Typical use cases include embedding barcodes in JSON payloads, HTML pages, or transmitting them over APIs without writing files to disk. Developers often need to generate barcodes on the fly and serialize them for web or mobile applications. // Prompt: Save a barcode directly to a MemoryStream and convert the stream to a Base64 string. -// Tags: code128, barcode generation, memorystream, base64, png, aspose.barcode +// Tags: barcode, code128, generation, memorystream, base64, png, aspose.barcode using System; using System.IO; @@ -9,26 +10,26 @@ using Aspose.BarCode.Generation; /// -/// Demonstrates how to generate a Code128 barcode, store it in a , -/// and convert the resulting image to a Base64 string. +/// Demonstrates saving a barcode image to a MemoryStream and converting it to a Base64 string. /// class Program { /// - /// Entry point of the example. Generates the barcode and writes the Base64 representation to the console. + /// Entry point. Generates a Code128 barcode, writes it to a MemoryStream in PNG format, + /// converts the stream to a Base64 string, and writes the result to the console. /// static void Main() { - // Initialize a barcode generator for Code128 with sample text "1234567890" + // Initialize a barcode generator for Code128 with the sample text "1234567890" using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Create a memory stream to hold the generated PNG image + // Create a memory stream to hold the generated barcode image using (var memoryStream = new MemoryStream()) { // Save the barcode image directly into the memory stream in PNG format generator.Save(memoryStream, BarCodeImageFormat.Png); - // Convert the image bytes from the memory stream to a Base64-encoded string + // Convert the image bytes stored in the memory stream to a Base64 string string base64String = Convert.ToBase64String(memoryStream.ToArray()); // Output the Base64 string to the console diff --git a/barcode-saving-and-export/save-barcode-to-temporary-file-then-move-it-to-permanent-directory-with-unique-name.cs b/barcode-saving-and-export/save-barcode-to-temporary-file-then-move-it-to-permanent-directory-with-unique-name.cs index f8a7125..e71647b 100644 --- a/barcode-saving-and-export/save-barcode-to-temporary-file-then-move-it-to-permanent-directory-with-unique-name.cs +++ b/barcode-saving-and-export/save-barcode-to-temporary-file-then-move-it-to-permanent-directory-with-unique-name.cs @@ -1,58 +1,53 @@ -// Title: Save Barcode to Temporary File and Move to Permanent Directory -// Description: Generates a Code128 barcode, saves it to a temporary PNG file, then moves it to a permanent folder with a unique filename. +// Title: Save barcode to temporary file then move to permanent location +// Description: Demonstrates generating a barcode image, saving it to a temporary file, and moving it to a permanent directory with a unique filename. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator to create barcodes, save them as images, and manage file storage. Developers often need to generate barcodes on the fly, store them temporarily, and then move them to a persistent location for later use, such as embedding in documents or serving via web APIs. // Prompt: Save a barcode to a temporary file, then move it to a permanent directory with a unique name. -// Tags: barcode, code128, save, temporary file, permanent directory, aspose.barcode, png +// Tags: barcode generation, code128, png, temporary file, file move, aspose.barcode using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing; /// -/// Demonstrates generating a barcode, storing it temporarily, and then moving it to a permanent location with a unique name. +/// Demonstrates creating a barcode, saving it to a temporary file, and moving it to a permanent directory with a unique name. /// class Program { /// - /// Entry point of the example. Generates a Code128 barcode, saves it to a temporary file, - /// creates a permanent directory if needed, and moves the file there with a unique filename. + /// Entry point of the example. Generates a Code128 barcode, stores it temporarily, then moves it to a permanent folder. /// static void Main() { - // Define the barcode content. + // Define the barcode content and symbology (Code128) string codeText = "1234567890"; + BaseEncodeType encodeType = EncodeTypes.Code128; - // Build a temporary file path with a .png extension. + // Build a unique temporary file path in the system's temp folder string tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".png"); - // Generate the barcode and write it to the temporary file. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + // Generate the barcode and save it directly to the temporary file (PNG format by default) + using (var generator = new BarcodeGenerator(encodeType, codeText)) { - // Optional visual customization. - generator.Parameters.Barcode.BarColor = Color.Black; - generator.Parameters.BackColor = Color.White; - - // Save the generated barcode image. generator.Save(tempFilePath); } - // Determine the permanent directory path (relative to the current working directory). - string permanentDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + // Determine the permanent directory relative to the current working directory + string permanentDir = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); - // Ensure the permanent directory exists. + // Ensure the permanent directory exists; create it if necessary if (!Directory.Exists(permanentDir)) { Directory.CreateDirectory(permanentDir); } - // Create a unique file name for the permanent location. + // Create a unique file name for the permanent location to avoid collisions string permanentFilePath = Path.Combine(permanentDir, Guid.NewGuid().ToString() + ".png"); - // Move the barcode image from the temporary location to the permanent directory. + // Move the barcode image from the temporary location to the permanent directory File.Move(tempFilePath, permanentFilePath); - // Inform the user where the barcode was saved. - Console.WriteLine($"Barcode saved to: {permanentFilePath}"); + // Output the final location of the saved barcode + Console.WriteLine("Barcode saved to: " + permanentFilePath); } } \ No newline at end of file diff --git a/barcode-saving-and-export/save-code128-barcode-to-bmp-file-using-custom-foreground-color.cs b/barcode-saving-and-export/save-code128-barcode-to-bmp-file-using-custom-foreground-color.cs index e987563..d03eb94 100644 --- a/barcode-saving-and-export/save-code128-barcode-to-bmp-file-using-custom-foreground-color.cs +++ b/barcode-saving-and-export/save-code128-barcode-to-bmp-file-using-custom-foreground-color.cs @@ -1,42 +1,41 @@ -// Title: Save Code128 barcode as BMP with custom color -// Description: Demonstrates generating a Code128 barcode, applying a dark green foreground, and saving it as a BMP image file. +// Title: Save Code128 barcode as BMP with custom foreground color +// Description: Demonstrates generating a Code128 barcode and saving it as a BMP image while applying a custom bar color. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to configure barcode appearance using the BarcodeGenerator class. Typical use cases include creating printable barcodes with brand‑specific colors for inventory, shipping, or retail applications. Developers often need to customize colors, formats, and symbologies before exporting images. // Prompt: Save a Code128 barcode to a BMP file using a custom foreground color. -// Tags: barcode, code128, bmp, color, generation, aspose.barcode +// Tags: code128, barcode, save, bmp, foreground color, aspose.barcode, generation using System; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Drawing; -/// -/// Example program that creates a Code128 barcode, sets a custom bar color, -/// and saves the result as a BMP image file. -/// -class Program +namespace BarcodeSample { /// - /// Entry point of the application. - /// Generates the barcode and writes it to disk. + /// Entry point for the barcode generation sample. /// - static void Main() + class Program { - // Text to encode in the barcode - const string codeText = "ABC123"; + /// + /// Generates a Code128 barcode, applies a custom blue bar color, and saves it as a BMP file. + /// + static void Main() + { + // Define the output file path + string outputPath = "code128.bmp"; - // Output file name (BMP format) - const string outputFile = "code128.bmp"; + // Initialize the barcode generator with Code128 symbology and sample data + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) + { + // Apply a custom foreground color to the bars + generator.Parameters.Barcode.BarColor = Color.Blue; - // Initialize the barcode generator for Code128 with the specified text - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) - { - // Apply a custom foreground (bar) color – dark green in this case - generator.Parameters.Barcode.BarColor = Color.DarkGreen; + // Export the barcode to a BMP image file + generator.Save(outputPath, BarCodeImageFormat.Bmp); + } - // Save the generated barcode image as a BMP file - generator.Save(outputFile, BarCodeImageFormat.Bmp); + // Inform the user where the file was saved + Console.WriteLine($"Barcode saved to {outputPath}"); } - - // Inform the user that the file has been created - Console.WriteLine($"Code128 barcode saved to '{outputFile}'."); } } \ No newline at end of file diff --git a/barcode-saving-and-export/save-multiple-barcodes-to-separate-svg-files-in-loop-for-batch-processing.cs b/barcode-saving-and-export/save-multiple-barcodes-to-separate-svg-files-in-loop-for-batch-processing.cs index 418864b..042d5c9 100644 --- a/barcode-saving-and-export/save-multiple-barcodes-to-separate-svg-files-in-loop-for-batch-processing.cs +++ b/barcode-saving-and-export/save-multiple-barcodes-to-separate-svg-files-in-loop-for-batch-processing.cs @@ -1,7 +1,8 @@ -// Title: Batch Barcode Generation to Separate Files -// Description: Demonstrates generating multiple Code128 barcodes and saving each to an individual file in a loop for batch processing. +// Title: Batch generate multiple barcodes and save as SVG files +// Description: Demonstrates generating several barcodes of different symbologies in a loop and saving each as a separate SVG file for batch processing. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use the BarcodeGenerator class to create various barcode types (e.g., Code39, Code128, QR, DataMatrix, Aztec) and export them to SVG format. Typical use cases include bulk barcode creation for inventory, shipping labels, or marketing materials. Developers often need to automate barcode production, customize appearance, and handle multiple formats in a single workflow. // Prompt: Save multiple barcodes to separate SVG files in a loop for batch processing. -// Tags: code128, barcode, batch, svg, generation, aspose.barcode +// Tags: barcode symbology, batch processing, svg, generation, aspose.barcode using System; using System.IO; @@ -9,56 +10,59 @@ using Aspose.BarCode.Generation; /// -/// Generates a series of barcodes and saves each to a separate file. +/// Demonstrates batch generation of different barcode types and saving each as an SVG file. /// class Program { /// - /// Entry point of the application. Creates an output directory, iterates over sample texts, - /// generates a Code128 barcode for each, saves it to a file, and logs the operation. + /// Entry point of the example. Generates a set of barcodes and writes them to the file system. /// static void Main() { - // Define the output directory for generated barcode files - string outputDir = "Barcodes"; + // Define the output folder for the generated SVG files. + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); - // Ensure the output directory exists - if (!Directory.Exists(outputDir)) + // Collection of barcode specifications to be generated. + var barcodeInfos = new[] { - Directory.CreateDirectory(outputDir); - } - - // Sample texts to encode into barcodes - string[] sampleTexts = new string[] - { - "Sample001", - "Sample002", - "Sample003", - "Sample004", - "Sample005" + new { EncodeType = EncodeTypes.Code39, CodeText = "CODE39-1" }, + new { EncodeType = EncodeTypes.Code128, CodeText = "CODE128-123" }, + new { EncodeType = EncodeTypes.QR, CodeText = "https://example.com" }, + new { EncodeType = EncodeTypes.DataMatrix, CodeText = "DM12345" }, + new { EncodeType = EncodeTypes.Aztec, CodeText = "AZTEC" } }; - // Loop through each sample text, generate a barcode, and save it - for (int i = 0; i < sampleTexts.Length; i++) + int index = 1; + // Iterate over each barcode definition and generate the corresponding SVG file. + foreach (var info in barcodeInfos) { - // Current text to encode - string codeText = sampleTexts[i]; + // Build a unique file name that includes the index and barcode type. + string fileName = $"barcode_{index}_{info.EncodeType}.svg"; + string filePath = Path.Combine(outputFolder, fileName); - // Build the output file name (e.g., barcode_1.png) - string fileName = Path.Combine(outputDir, $"barcode_{i + 1}.png"); - - // Create a barcode generator for Code128 with the current text - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + // Create and configure the barcode generator for the current barcode. + using (var generator = new BarcodeGenerator(info.EncodeType, info.CodeText)) { - // Save the generated barcode to the specified file - generator.Save(fileName); + // Optional: set the barcode color (default is black). + generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Black; + + // Attempt to save the barcode as an SVG file. + try + { + generator.Save(filePath, BarCodeImageFormat.Svg); + Console.WriteLine($"Saved {filePath}"); + } + catch (Exception ex) + { + // Log any errors that occur during the save operation. + Console.WriteLine($"Failed to save {filePath}: {ex.Message}"); + } } - // Log the successful save operation - Console.WriteLine($"Saved barcode '{codeText}' to '{fileName}'."); + index++; } - // Indicate that the batch process has finished - Console.WriteLine("Batch barcode generation completed."); + Console.WriteLine("Barcode generation completed."); } } \ No newline at end of file diff --git a/barcode-saving-and-export/save-pdf417-barcode-as-emf-vector-file-and-embed-it-into-word-document.cs b/barcode-saving-and-export/save-pdf417-barcode-as-emf-vector-file-and-embed-it-into-word-document.cs index 8fba711..c9d80d3 100644 --- a/barcode-saving-and-export/save-pdf417-barcode-as-emf-vector-file-and-embed-it-into-word-document.cs +++ b/barcode-saving-and-export/save-pdf417-barcode-as-emf-vector-file-and-embed-it-into-word-document.cs @@ -1,46 +1,49 @@ -// Title: Save PDF417 barcode as EMF and embed in Word -// Description: Demonstrates generating a PDF417 barcode, exporting it as an EMF vector image, and inserting the image into a Word document. +// Title: Save PDF417 barcode as EMF and embed in Word document +// Description: Demonstrates generating a PDF417 barcode, exporting it as an EMF vector image, and inserting it into a Word document. +// Category-Description: This example belongs to the Aspose.BarCode generation and Aspose.Words document manipulation category. It showcases the use of BarcodeGenerator (Aspose.BarCode.Generation) to create a PDF417 barcode, the BarCodeImageFormat enumeration to export the barcode as an EMF vector file, and the Document/DocumentBuilder classes (Aspose.Words) to embed the image into a Word document. Developers often need to generate high‑quality barcodes for print media and embed them directly into office documents, making this pattern a common requirement. // Prompt: Save a PDF417 barcode as an EMF vector file and embed it into a Word document. -// Tags: pdf417, barcode, emf, word, aspose.barcode, aspose.words +// Tags: pdf417, barcode, emf, word, aspose.barcode, aspose.words, generation, embedding using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; using Aspose.Words; +using Aspose.Words.Drawing; /// -/// Example program that creates a PDF417 barcode, saves it as an EMF file, -/// and embeds the EMF image into a Word document. +/// Generates a PDF417 barcode, saves it as an EMF file, and embeds the image into a Word document. /// class Program { /// - /// Entry point of the application. + /// Entry point of the example. Executes the barcode generation, EMF export, and Word embedding steps. /// - /// Command‑line arguments (not used). - static void Main(string[] args) + static void Main() { - // Define output file paths - string emfPath = "pdf417.emf"; - string docPath = "BarcodeDocument.docx"; + // Sample data to encode in the PDF417 barcode + const string codeText = "Sample PDF417 Text"; - // Text to encode in the PDF417 barcode - string codeText = "Sample PDF417 Barcode Text"; + // Define output file paths for the EMF image and the Word document + const string emfPath = "pdf417.emf"; + const string docPath = "Pdf417Document.docx"; - // Generate the PDF417 barcode and save it as an EMF vector image + // ------------------------------------------------------------ + // Generate PDF417 barcode and save it as an EMF vector image + // ------------------------------------------------------------ try { + // Initialize the barcode generator with PDF417 symbology and the sample text using (var generator = new BarcodeGenerator(EncodeTypes.Pdf417, codeText)) { - // Export the barcode to EMF format + // Export the generated barcode to an EMF file (vector format) generator.Save(emfPath, BarCodeImageFormat.Emf); } } catch (Exception ex) { - // Handle evaluation version limitation for EMF export - if (ex.Message.Contains("evaluation")) + // Handle evaluation version limitation for EMF export gracefully + if (ex.Message != null && ex.Message.Contains("evaluation")) { Console.WriteLine("A valid Aspose.BarCode license is required for EMF export of this barcode type."); return; @@ -50,21 +53,27 @@ static void Main(string[] args) throw; } - // Ensure the EMF file was created successfully + // Verify that the EMF file was successfully created if (!File.Exists(emfPath)) { Console.WriteLine($"Failed to create EMF file at '{emfPath}'."); return; } - // Create a new Word document and insert the EMF image + // ------------------------------------------------------------ + // Create a new Word document and embed the EMF barcode image + // ------------------------------------------------------------ var doc = new Document(); var builder = new DocumentBuilder(doc); + + // Insert the EMF image at the current cursor position builder.InsertImage(emfPath); + + // Save the Word document with the embedded barcode doc.Save(docPath); // Output the locations of the generated files Console.WriteLine($"PDF417 barcode saved as EMF: {Path.GetFullPath(emfPath)}"); - Console.WriteLine($"Word document with embedded barcode saved as: {Path.GetFullPath(docPath)}"); + Console.WriteLine($"Word document created with embedded barcode: {Path.GetFullPath(docPath)}"); } } \ No newline at end of file diff --git a/barcode-saving-and-export/set-image-resolution-to-600-dpi-and-save-upc-barcode-as-tiff-file.cs b/barcode-saving-and-export/set-image-resolution-to-600-dpi-and-save-upc-barcode-as-tiff-file.cs index 2db5e94..7ab2e35 100644 --- a/barcode-saving-and-export/set-image-resolution-to-600-dpi-and-save-upc-barcode-as-tiff-file.cs +++ b/barcode-saving-and-export/set-image-resolution-to-600-dpi-and-save-upc-barcode-as-tiff-file.cs @@ -1,15 +1,16 @@ -// Title: Generate UPC-A barcode with 600 DPI resolution and save as TIFF -// Description: Demonstrates creating a UPC-A barcode, setting the image resolution to 600 DPI, and saving the result as a TIFF file. +// Title: Generate a 600 DPI UPC‑A barcode and save as TIFF +// Description: Demonstrates setting a high image resolution and exporting a UPC‑A barcode to a TIFF file using Aspose.BarCode. +// Category-Description: This example belongs to the barcode generation category of Aspose.BarCode, illustrating how to configure image resolution and output format. It uses the BarcodeGenerator class with EncodeTypes to create common symbologies, a typical task for developers needing high‑quality printable barcodes in formats like TIFF. // Prompt: Set image resolution to 600 DPI and save a UPC‑A barcode as a TIFF file. -// Tags: barcode, upc-a, resolution, tiff, aspose.barcode, generation +// Tags: upc-a, barcode, resolution, tiff, generation, aspose.barcode using System; using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Example program that creates a UPC‑A barcode, configures a high‑resolution output, -/// and saves the image as a TIFF file. +/// Example program that creates a UPC‑A barcode, sets the image resolution to 600 DPI, +/// and saves the result as a TIFF file using Aspose.BarCode. /// class Program { @@ -18,14 +19,18 @@ class Program /// static void Main() { - // Initialize a barcode generator for the UPC‑A symbology with a valid 12‑digit value. - using (var generator = new BarcodeGenerator(EncodeTypes.UPCA, "012345678905")) + // Initialize a barcode generator for the UPC‑A symbology with an 11‑digit code. + // The check digit will be calculated automatically. + using (var generator = new BarcodeGenerator(EncodeTypes.UPCA, "01234567890")) { - // Configure the image resolution to 600 DPI for high‑quality output. + // Configure the output image resolution to 600 DPI. generator.Parameters.Resolution = 600f; - // Persist the generated barcode as a TIFF image file. + // Save the generated barcode as a TIFF image file. generator.Save("upc_a.tiff"); } + + // Inform the user that the barcode has been saved. + Console.WriteLine("UPC-A barcode saved as 'upc_a.tiff' with 600 DPI resolution."); } } \ No newline at end of file diff --git a/barcode-saving-and-export/use-barcodegeneratorsave-overload-to-write-png-image-to-cloudblob-stream-for-azure-storage.cs b/barcode-saving-and-export/use-barcodegeneratorsave-overload-to-write-png-image-to-cloudblob-stream-for-azure-storage.cs index a45c36b..df7ff91 100644 --- a/barcode-saving-and-export/use-barcodegeneratorsave-overload-to-write-png-image-to-cloudblob-stream-for-azure-storage.cs +++ b/barcode-saving-and-export/use-barcodegeneratorsave-overload-to-write-png-image-to-cloudblob-stream-for-azure-storage.cs @@ -1,61 +1,62 @@ // Title: Generate Code128 barcode PNG and upload to Azure Blob storage (demo) -// Description: Demonstrates creating a Code128 barcode, saving it as PNG to a stream, and showing how to upload the stream to Azure Blob storage. +// Description: Demonstrates creating a Code128 barcode, saving it as PNG, and showing how to upload the image to Azure Blob storage using a stream. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator and its Save overload to produce image streams. Typical scenarios include generating barcodes on the fly for web services, storing them in cloud storage, or embedding them in documents. Developers often need to convert barcodes to common image formats and write them directly to cloud storage streams such as Azure Blob storage. // Prompt: Use BarcodeGenerator.Save overload to write a PNG image to a CloudBlob stream for Azure storage. -// Tags: barcode, code128, png, azure blob, aspose.barcode, stream +// Tags: code128, barcode generation, png, azure blob, aspnet, aspose.barcode, image stream using System; using System.IO; using Aspose.BarCode; using Aspose.BarCode.Generation; -using Aspose.Drawing.Imaging; -namespace BarcodeToAzureBlobDemo +/// +/// Demonstrates barcode generation and (commented) Azure Blob upload using Aspose.BarCode. +/// +class Program { /// - /// Demonstrates barcode generation and (simulated) upload to Azure Blob storage. + /// Entry point of the example. Generates a Code128 barcode, saves it as PNG to a stream, + /// and illustrates how to upload the stream to Azure Blob storage. /// - class Program + static void Main() { - /// - /// Entry point. Generates a Code128 barcode, saves it as PNG to a stream, - /// and writes the image to a local file (placeholder for Azure Blob upload). - /// - static void Main() - { - // Initialize a barcode generator for Code128 with sample text. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) - { - // Optional: customize barcode appearance (blue bars on white background). - generator.Parameters.Barcode.BarColor = Aspose.Drawing.Color.Blue; - generator.Parameters.BackColor = Aspose.Drawing.Color.White; - - // Save the barcode image to a memory stream in PNG format. - using (var memoryStream = new MemoryStream()) - { - generator.Save(memoryStream, BarCodeImageFormat.Png); - memoryStream.Position = 0; // Reset stream position for subsequent reading. + // Define the data to encode in the barcode. + const string codeText = "1234567890"; - // ----------------------------------------------------------------- - // Real Azure Blob storage implementation (requires Azure.Storage.Blobs NuGet package): - // ----------------------------------------------------------------- - // using Azure.Storage.Blobs; - // var blobServiceClient = new BlobServiceClient(""); - // var containerClient = blobServiceClient.GetBlobContainerClient("mycontainer"); - // var blobClient = containerClient.GetBlobClient("barcode.png"); - // await blobClient.UploadAsync(memoryStream, overwrite: true); - // ----------------------------------------------------------------- - // Since Azure SDK is not available in the snippet runner, write to a local file instead. + // Initialize the barcode generator with Code128 symbology. + using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + { + // Optional: adjust barcode appearance (e.g., X-dimension). + generator.Parameters.Barcode.XDimension.Point = 2f; - const string localFilePath = "barcode.png"; + // Create a memory stream to hold the PNG image. + using (var memoryStream = new MemoryStream()) + { + // Save the generated barcode image into the memory stream in PNG format. + generator.Save(memoryStream, BarCodeImageFormat.Png); + memoryStream.Position = 0; // Reset position for subsequent reads. - // Write the PNG data from the memory stream to a local file. - using (var fileStream = new FileStream(localFilePath, FileMode.Create, FileAccess.Write)) - { - memoryStream.CopyTo(fileStream); - } + // ----------------------------------------------------------------- + // Azure Blob upload example (requires Azure.Storage.Blobs package) + // ----------------------------------------------------------------- + // The following code shows how to upload the PNG stream to Azure Blob storage. + // It is commented out because the Azure SDK is not referenced in this snippet. + /* + var blobServiceClient = new Azure.Storage.Blobs.BlobServiceClient(""); + var containerClient = blobServiceClient.GetBlobContainerClient(""); + var blobClient = containerClient.GetBlobClient("barcode.png"); + blobClient.Upload(memoryStream, overwrite: true); + */ - Console.WriteLine($"Barcode image saved to '{localFilePath}'."); + // For demonstration purposes, write the PNG to a local file instead. + const string localPath = "barcode.png"; + using (var fileStream = new FileStream(localPath, FileMode.Create, FileAccess.Write)) + { + memoryStream.CopyTo(fileStream); } + + Console.WriteLine($"Barcode image saved to local file: {localPath}"); + // If Azure upload were enabled, the image would be stored in the specified blob container. } } } diff --git a/barcode-saving-and-export/use-barcodegeneratorsave-to-write-gif-image-to-network-stream-for-real-time-transmission.cs b/barcode-saving-and-export/use-barcodegeneratorsave-to-write-gif-image-to-network-stream-for-real-time-transmission.cs index 881be28..5b27341 100644 --- a/barcode-saving-and-export/use-barcodegeneratorsave-to-write-gif-image-to-network-stream-for-real-time-transmission.cs +++ b/barcode-saving-and-export/use-barcodegeneratorsave-to-write-gif-image-to-network-stream-for-real-time-transmission.cs @@ -1,55 +1,56 @@ -// Title: Generate Code128 Barcode GIF and Send via TCP -// Description: Creates a Code128 barcode, saves it as a GIF directly to a network stream, and transmits it to a TCP server in real time. +// Title: Write barcode GIF to network stream using BarcodeGenerator.Save +// Description: Demonstrates generating a Code128 barcode and sending it as a GIF image over a TCP connection in real‑time. +// Category-Description: This example belongs to the Aspose.BarCode image generation and network transmission category. It showcases the use of BarcodeGenerator, its Parameters, and the Save method with BarCodeImageFormat to produce barcode images directly to streams. Typical scenarios include real‑time barcode delivery to remote services, printers, or web clients where immediate transmission is required. Developers often need to generate barcodes on‑the‑fly and stream them without intermediate files. // Prompt: Use BarcodeGenerator.Save to write a GIF image to a network stream for real‑time transmission. -// Tags: barcode, code128, gif, network, tcp, aspnet, aspose.barcode, generation +// Tags: barcode, code128, gif, network, stream, save, aspnet, aspose.barcode, generation using System; +using System.IO; using System.Net.Sockets; using Aspose.BarCode; using Aspose.BarCode.Generation; /// -/// Demonstrates generating a Code128 barcode as a GIF and sending it over a TCP connection. +/// Demonstrates generating a Code128 barcode and transmitting it as a GIF image over a TCP connection. /// class Program { /// - /// Entry point of the example. Generates the barcode and streams it to a TCP server. + /// Entry point of the example. Connects to a TCP server and streams the generated barcode. /// static void Main() { - // Barcode data to encode - const string codeText = "1234567890"; + // Server details for the network transmission + string server = "127.0.0.1"; + int port = 5000; - // Destination server details (modify as required) - const string host = "localhost"; - const int port = 5000; - - try + // Create a barcode generator for Code128 with sample text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "123456")) { - // Establish a TCP connection to the target server - using (TcpClient client = new TcpClient()) - { - client.Connect(host, port); + // Optional: set a higher resolution for better image quality + generator.Parameters.Resolution = 300; - // Obtain the network stream for sending data - using (NetworkStream networkStream = client.GetStream()) + try + { + // Establish a TCP connection to the server + using (TcpClient client = new TcpClient()) { - // Initialize the barcode generator for Code128 symbology - using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + client.Connect(server, port); + + // Obtain the network stream for writing data + using (NetworkStream networkStream = client.GetStream()) { - // Directly write the generated barcode as a GIF to the network stream + // Save the barcode directly to the network stream as a GIF image generator.Save(networkStream, BarCodeImageFormat.Gif); + networkStream.Flush(); // Ensure all data is sent } } } - - Console.WriteLine("Barcode GIF sent successfully."); - } - catch (Exception ex) - { - // Output any errors that occur during the process - Console.WriteLine($"Error: {ex.Message}"); + catch (Exception ex) + { + // Log any errors that occur during transmission + Console.WriteLine("Error transmitting barcode: " + ex.Message); + } } } } \ No newline at end of file diff --git a/barcode-saving-and-export/use-barcodegeneratorsave-to-write-tiff-image-to-filestream-with-async-await-pattern.cs b/barcode-saving-and-export/use-barcodegeneratorsave-to-write-tiff-image-to-filestream-with-async-await-pattern.cs index cecf92d..62d9b2e 100644 --- a/barcode-saving-and-export/use-barcodegeneratorsave-to-write-tiff-image-to-filestream-with-async-await-pattern.cs +++ b/barcode-saving-and-export/use-barcodegeneratorsave-to-write-tiff-image-to-filestream-with-async-await-pattern.cs @@ -1,7 +1,8 @@ -// Title: Async TIFF Barcode Generation with Aspose.BarCode -// Description: Demonstrates generating a Code128 barcode and saving it as a TIFF image using an asynchronous FileStream. +// Title: Asynchronous TIFF Barcode Generation to FileStream +// Description: Demonstrates generating a Code128 barcode and saving it as a TIFF image using async/await with a FileStream. +// Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating how to use BarcodeGenerator and BarCodeImageFormat to create barcode images. Typical use cases include creating printable barcode files in various formats, such as TIFF, for integration into document workflows. Developers often need to generate barcodes asynchronously to avoid blocking I/O operations. // Prompt: Use BarcodeGenerator.Save to write a TIFF image to a FileStream with async/await pattern. -// Tags: barcode, code128, async, tiff, aspose.barcode, fileio +// Tags: code128, barcode generation, tiff, async, filestream, aspose.barcode using System; using System.IO; @@ -10,44 +11,41 @@ using Aspose.BarCode.Generation; /// -/// Example program that creates a Code128 barcode and writes it to a TIFF file asynchronously. +/// Demonstrates asynchronous generation and saving of a Code128 barcode as a TIFF image. /// class Program { /// - /// Entry point of the application. Generates a barcode and saves it as a TIFF image using async/await. + /// Entry point. Generates a barcode and saves it asynchronously to a TIFF file. /// /// Command‑line arguments (not used). + /// A task representing the asynchronous operation. static async Task Main(string[] args) { - // Define the barcode content and the output file path. - string codeText = "1234567890"; + // Define the output file path for the generated barcode image. string outputPath = "barcode.tiff"; - // Ensure the directory for the output file exists. + // Ensure the target directory exists; create it if necessary. string directory = Path.GetDirectoryName(Path.GetFullPath(outputPath)); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } - // Initialize the barcode generator for Code128 symbology. - using (var generator = new BarcodeGenerator(EncodeTypes.Code128, codeText)) + // Open a FileStream configured for asynchronous writing. + using (FileStream stream = new FileStream( + outputPath, + FileMode.Create, + FileAccess.Write, + FileShare.None, + bufferSize: 4096, + useAsync: true)) { - // Open a FileStream with async support to write the TIFF image. - using (var stream = new FileStream( - outputPath, - FileMode.Create, - FileAccess.Write, - FileShare.None, - bufferSize: 4096, - useAsync: true)) + // Initialize the barcode generator with Code128 symbology and sample data. + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Code128, "1234567890")) { - // Perform the save operation on a background thread to avoid blocking. + // Save the barcode as a TIFF image to the stream asynchronously. await Task.Run(() => generator.Save(stream, BarCodeImageFormat.Tiff)); - - // Ensure all buffered data is flushed to the file. - await stream.FlushAsync(); } }