DEV Community

Cover image for Generate QR Codes Quickly with C#
Jeremy K.
Jeremy K.

Posted on

Generate QR Codes Quickly with C#

QR codes have emerged as a highly efficient information-carrying medium, with widespread applications across payment systems, logistics tracking, identity authentication, and beyond. For .NET developers, Spire.Barcode for .NET offers a lightweight yet fully-featured solution that supports the generation and decoding of multiple barcode and QR code formats. This article provides a step-by-step guide to implementing QR code generation with this library, from basic setup to advanced customization.

Environment Preparation

To get started, install the Spire.Barcode package via NuGet.

Package Manager Console

Install-Package Spire.Barcode
Enter fullscreen mode Exit fullscreen mode

Basic: Generate a Simple QR Code

The following example demonstrates how to create a basic QR code with custom text/URL content and save it as a local PNG image.

using Spire.Barcode;
using System.Drawing;
using System.Drawing.Imaging;

namespace QRCodeGeneratorDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize barcode configuration
            var barcodeSettings = new BarcodeSettings
            {
                // Set barcode type to QR Code
                Type = BarCodeType.QRCode,
                // Define QR code content (supports text, URLs, phone numbers, etc.)
                Data = "https://www.example.com/",
                // Auto-detect data type for optimal encoding
                QRCodeDataMode = QRCodeDataMode.Auto
            };

            // Create generator instance and generate QR code image
            var generator = new BarCodeGenerator(barcodeSettings);
            using (var qrImage = generator.GenerateImage())
            {
                // Save image to local directory (PNG is recommended for lossless quality)
                qrImage.Save("BasicQRCode.png", ImageFormat.Png);
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Breakdown

  • BarcodeSettings: The core configuration class for all barcode generation rules. It centralizes settings for barcode type, data content, and visual styles.
  • QRCodeDataMode.Auto: Automatically identifies the input data type (e.g., URL, numeric string, Chinese characters), eliminating the need for manual encoding mode configuration.
  • BarCodeGenerator: The engine that transforms BarcodeSettings into a usable QR code image.
  • GenerateImage(): Renders the QR code as a System.Drawing.Image object, ready for further processing or saving.
  • Save(): Saves the image to disk. The first parameter specifies the file path, while the second defines the image format (PNG is preferred for QR codes due to its lossless compression).

Advanced: Customize QR Code Styles (with Logo Embedding)

Spire.Barcode enables advanced customization to enhance brand identity, including adding logos, adjusting text display, and configuring error correction levels. The following example implements a production-ready QR code with these features.

using Spire.Barcode;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace CustomQRCodeGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Initialize configuration with refined settings
                var barcodeSettings = new BarcodeSettings
                {
                    // Basic QR code configuration
                    Type = BarCodeType.QRCode,
                    Data = "https://www.example.com/",
                    Data2D = "Scan to Visit Example.com", // Footer text
                    ShowTextOnBottom = true,
                    TextFont = new Font("Arial", 16, FontStyle.Regular),

                    // Encoding and error correction
                    QRCodeDataMode = QRCodeDataMode.Auto,
                    QRCodeECL = QRCodeECL.H, // High error correction (30% damage recoverable)

                    // Module size: Controls the size of individual QR code squares
                    X = 3.0f
                };

                // Embed logo (recommended size: 15%-20% of QR code area)
                var logoPath = "Logo.png";
                if (File.Exists(logoPath))
                {
                    barcodeSettings.QRCodeLogoImage = Image.FromFile(logoPath);
                }
                else
                {
                    Console.WriteLine("Logo file not found. Generating QR code without logo.");
                }

                // Generate and save the custom QR code
                var generator = new BarCodeGenerator(barcodeSettings);
                using (var qrImage = generator.GenerateImage())
                {
                    var outputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CustomQRCode.png");
                    qrImage.Save(outputPath, ImageFormat.Png);
                    Console.WriteLine($"QR code generated successfully! File path: {outputPath}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"QR code generation failed: {ex.Message}");
            }

            Console.ReadLine();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Key Parameters

  • QRCodeLogoImage: Embeds a brand logo into the center of the QR code. Critical Note: To ensure scannability, the logo should not exceed 20% of the QR code’s total area. Larger logos may block essential data modules.
  • QRCodeECL: Defines the error correction level, a critical parameter for QR code reliability. Options include:
    • L: Recovers from up to 7% damage (ideal for low-risk use cases like marketing flyers)
    • M: Recovers from up to 15% damage (default setting, balanced for most scenarios)
    • Q: Recovers from up to 25% damage (suitable for outdoor applications)
    • H: Recovers from up to 30% damage (best for high-reliability use cases like payment QR codes)
  • X: Sets the width of a single QR code module (the small square building blocks). A higher value results in a larger QR code, which is easier to scan from a distance.

Common Issues and Troubleshooting Tips

  1. Logo File Not Found Errors

    • Verify the logo file path. Use absolute paths (e.g., C:/Assets/Logo.png for Windows, /home/user/assets/Logo.png for Linux) if relative paths fail.
    • Ensure the logo file is not corrupted and is in a supported format (PNG, JPG, BMP).
  2. Garbled or Missing Footer Text

    • Use system-installed fonts (e.g., Arial, SimSun, Segoe UI) to avoid compatibility issues.
    • Adjust the TextFont size to prevent text from being cut off or overlapping with the QR code.
  3. Content Length Limitations

    • QR code capacity varies by error correction level:
      • Level H: Supports up to ~429 alphanumeric characters
      • Level L: Supports up to ~2,953 alphanumeric characters
    • For long content, use a URL shortener to reduce data length.
  4. Poor Scannability

    • Save QR codes in PNG format to avoid compression artifacts that can disrupt scanning.
    • If a logo causes scanning failures, reduce its size to ≤15% of the QR code area or lower the error correction level to free up data modules.

Conclusion

With Spire.Barcode for .NET, C# developers can quickly implement robust QR code generation functionality—from basic static codes to branded, high-reliability codes—with minimal code. By leveraging the library’s customization options, you can tailor QR codes to fit specific use cases, whether for e-commerce, logistics, or customer engagement. For production environments, always test QR code scannability across multiple devices and scenarios to ensure optimal user experience.

Top comments (0)