Skip to main content

Command Palette

Search for a command to run...

A Guide to Generate QR Codes with C#

Published
4 min read

As an efficient information carrier, QR codes are widely used in scenarios such as payment, logistics, and identity verification. In .NET development, Spire.Barcode for .NET provides a lightweight yet fully-featured solution that supports generating and reading multiple barcode and QR code formats. This article will detail how to generate QR codes using this library.


Environment Setup

First, install the required package via NuGet:

Install-Package Spire.Barcode

Generate a Simple QR Code in C

The following example shows how to generate a basic QR code containing text content and save it as a local image:

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

namespace GenerateQRCode
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize barcode settings
            BarcodeSettings settings = new BarcodeSettings();
            // Set the barcode type to QR Code
            settings.Type = BarCodeType.QRCode;
            // Set QR code content (customizable: text, URL, phone number, etc.)
            settings.Data = "https://www.example.com/";
            // Set digital encoding mode
            settings.QRCodeDataMode = QRCodeDataMode.Auto;

            // Create an instance of the barcode generator
            BarCodeGenerator generator = new BarCodeGenerator(settings);
            // Generate the QR code image
            Image qr = generator.GenerateImage();
            // Save the image
            qr.Save("QR Code.png", ImageFormat.Png);
        }
    }
}

Code Explanation

  • BarcodeSettings class: Initializes the configuration object. All barcode generation rules (type, data, style) are configured through this object.
  • QRCodeDataMode: Data encoding mode. When set to Auto, the component automatically identifies the data type (e.g., URL, pure number) without manual specification.
  • BarCodeGenerator class: The core generator class. Passing the configuration to the generator establishes a configuration-generation association.
  • GenerateImage method: Generates a QR code image based on the configuration.
  • Save method: Saves the generated QR code as an image. The first parameter is the save path, and the second parameter is the image format.

Advanced: Customize QR Code Styles (Embed Images)

Spire.Barcode supports embedding logo images into QR codes, as well as customizing the QR code's display text, size, error correction level, etc., to meet personalized requirements.

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

namespace GenerateQRCode
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // 1. Initialize the QR code configuration object (core of refined configuration)
                BarcodeSettings settings = new BarcodeSettings();

                // 2. Basic type and content configuration
                settings.Type = BarCodeType.QRCode; // Specify to generate a QR code
                settings.Data = "https://www.example.com/"; // Core data of the QR code
                settings.Data2D = "Scan to go to example.com"; // Text displayed at the bottom of the QR code
                settings.ShowTextOnBottom = true; // Display text at the bottom
                settings.TextFont = new Font(FontFamily.GenericSansSerif, 16.0f); // Font and size of the bottom text

                // 3. QR code encoding and error correction configuration
                settings.QRCodeDataMode = QRCodeDataMode.Auto; // Automatically identify data types (text/URL/number, etc.)
                settings.QRCodeECL = QRCodeECL.H; // Error correction level H (highest, recovers from up to 30% damage)

                // 4. Customize module size (width of a single QR code module)
                settings.X = 3.0f;

                // 5. Embed logo (it is recommended that the logo size does not exceed 15%-20% of the QR code to avoid affecting recognition)
                if (System.IO.File.Exists("Logo.png"))
                {
                    settings.QRCodeLogoImage = Image.FromFile("Logo.png");
                }
                else
                {
                    Console.WriteLine("Logo.png not found, a QR code without logo will be generated");
                }

                // 6. Generate and save the QR code
                BarCodeGenerator generator = new BarCodeGenerator(settings);
                Image qrImage = generator.GenerateImage(); // Generate the QR code image object
                qrImage.Save("CustomizeCode.png", ImageFormat.Png); // Save as PNG format (lossless compression, high recognition rate)

                Console.WriteLine("QR code generated successfully! File path: " + AppDomain.CurrentDomain.BaseDirectory + "QR Code.png");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to generate QR code: " + ex.Message);
            }

            Console.ReadLine();
        }
    }
}

Key Parameter Description

  • QRCodeLogoImage: Embeds a logo image. Ensure the image file path is correct. An overly large logo will make the QR code unrecognizable (recommended size ≤ 20% of the QR code area).
  • QRCodeECL: QR code error correction level. Available options:
    • L: Recovers from up to 7% damage;
    • M: Recovers from up to 15% damage (default);
    • Q: Recovers from up to 25% damage;
    • H: Recovers from up to 30% damage.

Common Issues and Precautions

  1. Logo Image Path Issues: If a "file not found" prompt appears, check the path of Logo.png or use an absolute path (e.g., C:/Images/Logo.png).
  2. Abnormal Text Display: If the bottom text is garbled or not displayed, ensure the specified font exists. It is recommended to use system-built fonts (e.g., Arial).
  3. Content Length Limitations: The content length of a QR code is related to its error correction level. A higher error correction level means fewer characters can be stored.
  4. Image Format: It is recommended to save QR codes in PNG format. Compared with JPG, PNG offers lossless compression and higher scanning recognition rates.
  5. QR Code Recognition Failure: If the QR code cannot be recognized after embedding a logo, reduce the logo size (recommended ≤ 15% of the QR code area) or lower the error correction level (e.g., switch to Q/M level).

With the methods introduced in this article, developers can quickly implement QR code generation functionality through simple APIs, and customize key parameters such as display text, error correction level, and logo embedding. In actual projects, it is recommended to optimize the QR code's size, color, and content according to specific requirements to ensure optimal scanning and user experience.

More from this blog