How to Generate QR Codes in Python (Full Tutorial with Examples)

Generate QR Codes Using Python Library

QR codes have transformed how we bridge physical and digital experiences—from marketing campaigns to secure data sharing. For developers looking to generate QR codes in Python , Spire.Barcode for Python provides a complete toolkit for seamless QR code generation, offering both simplicity for basic needs and advanced customization for professional applications.

This step-by-step guide walks you through the entire QR code generation process in Python. You'll learn to programmatically create scannable codes, customize their appearance, embed logos, and optimize error correction - everything needed to implement robust QR code generation solutions for any business or technical requirement.

Table of Contents

  1. Introduction to Spire.Barcode for Python
  2. Setting Up the Environment
  3. Basic Example: Generating QR Codes in Python
  4. Customizing QR Code Appearance
  5. Generating QR Code with Logo
  6. Wrapping up
  7. FAQs

1. Introduction to Spire.Barcode for Python

Spire.Barcode for Python is a powerful library that enables developers to generate and read various barcode types, including QR codes, in Python applications. This robust solution supports multiple barcode symbologies while offering extensive customization options for appearance and functionality.

Key features of Spire.Barcode include:

  • Support for QR Code generation with customizable error correction levels
  • Flexible data encoding options (numeric, alphanumber, byte/binary)
  • Comprehensive appearance customization (colors, sizes, fonts)
  • High-resolution output capabilities
  • Logo integration within QR codes

2. Setting Up the Environment

Before we dive into generating QR codes, you need to set up your Python environment. Ensure you have Python installed, and then install the Spire.Barcode library using pip:

pip install spire.barcode

For the best results, obtain a free temporary license from our website. This will allow you to create professional QR code images without evaluation messages, enhancing both user experience and quality of the generated codes.

3. Basic Example: Generating QR Codes in Python

Now that we have everything set up, let's generate our first QR code. Below is the step-by-step process:

  1. Initial Setup :

    • Import the Spire.Barcode library.
    • Activate the library with a valid license key to remove the
  2. Configure Barcode Settings :

    • Create a BarcodeSettings object to control QR code properties.
    • Set barcode type to QR code.
    • Configure settings such as data mode and error correction level.
    • Define the content to encode.
    • Configure visual aspects like module width and text display options.
  3. Generate Barcode Image :

    • Create a BarCodeGenerator object with the configured settings.
    • Convert the configured QR code into an image object in memory.
  4. Save Image to File :

    • Write the generated QR code image to a specified file path in PNG format.

The following code snippet demonstrates how to generate QR codes in Python:

from spire.barcode import *

# Function to write all bytes to a file
def WriteAllBytes(fname: str, data):
    with open(fname, "wb") as fp:
        fp.write(data)
    fp.close()

# Apply license key for the barcode generation library
License.SetLicenseKey("your license key")

# Create a BarcodeSettings object to configure barcode properties
barcodeSettings = BarcodeSettings()

# Set the type of barcode to QR code
barcodeSettings.Type = BarCodeType.QRCode

# Set the data mode for QR code (automatic detection of data type)
barcodeSettings.QRCodeDataMode = QRCodeDataMode.Auto

# Set the error correction level (M means medium level of error correction)
barcodeSettings.QRCodeECL = QRCodeECL.M

# Set the data that will be encoded in the QR code
barcodeSettings.Data2D = "visit us at www.e-iceblue.com"

# Set the width of each module (the square bars) in the barcode
barcodeSettings.X = 3

# Hide the text that typically accompanies the barcode
barcodeSettings.ShowText = False

# Create a BarCodeGenerator object with the specified settings
barCodeGenerator = BarCodeGenerator(barcodeSettings)

# Generate the image for the barcode based on the settings
image = barCodeGenerator.GenerateImage()

# Write the generated PNG image to disk at the specified path
WriteAllBytes("output/QRCode.png", image)

Key Concepts:

A. QRCodeDataMode (Data Encoding Scheme)

Controls how the input data is encoded in the QR code:

Mode Best For Example Use Cases
Auto Let library detect automatically General purpose (default choice)
Numeric Numbers only (0-9) Product codes, phone numbers
AlphaNumber A-Z, 0-9, and some symbols URLs, simple messages
Byte Binary/Unicode data Complex text, special characters

Why it matters:

  • Different modes have different storage capacities.
  • Numeric mode can store more digits than other modes.
  • Auto mode is safest for mixed content.

B. QRCodeECL (Error Correction Level)

Determines how much redundancy is built into the QR code:

Level Recovery Capacity Use Case
L (Low) 7% damage recovery Small codes, short URLs
M (Medium) 15% damage recovery General purpose (recommended)
Q (Quartile) 25% damage recovery Codes with logos or decorations
H (High) 30% damage recovery Critical applications

Visual Impact:

Higher ECLs:

  • Increase QR code complexity (more modules/squares).
  • Make the code more scannable when damaged.
  • Are essential when adding logos (use at least Q or H).

Output:

A QR code generated by Spire.Barcode for Python

4. Customizing QR Code Appearance

Once you've generated a basic QR code, you can further customize its appearance to make it more visually appealing or to fit your brand. Here are some customization options:

4.1 Adjusting DPI Settings

The DPI (dots per inch) settings control the image quality of the QR code. Higher DPI values result in sharper images suitable for printing, while lower values (72-150) are typically sufficient for digital use.

barcodeSettings.DpiX = 150
barcodeSettings.DpiY = 150

4.2 Changing Foreground and Background Colors

You can customize your QR code’s color scheme. The ForeColor determines the color of the QR code modules (squares), while BackColor sets the background color. Ensure sufficient contrast for reliable scanning.

barcodeSettings.BackColor = Color.get_GhostWhite()
barcodeSettings.ForeColor = Color.get_Purple()

4.3 Displaying the Encoded Data

If you want users to see the encoded information without scanning, set the following properties:

barcodeSettings.ShowTextOnBottom = True
barcodeSettings.TextColor = Color.get_Purple()
barcodeSettings.SetTextFont("Arial", 13, FontStyle.Bold)

4.4 Adding Text Under QR Code

You can also add custom text under the QR code, which could be a call-to-action or instructions.

barcodeSettings.ShowBottomText = True
barcodeSettings.BottomText = "Scan Me"
barcodeSettings.SetBottomTextFont("Arial", 13, FontStyle.Bold)
barcodeSettings.BottomTextColor = Color.get_Black()

4.5 Setting Margins and Border

Defining margins and border styles enhances the presentation of the QR code. Here’s how to do it:

barcodeSettings.LeftMargin = 2
barcodeSettings.RightMargin = 2
barcodeSettings.TopMargin = 2
barcodeSettings.BottomMargin = 2

barcodeSettings.HasBorder = True
barcodeSettings.BorderWidth = 0.5
barcodeSettings.BorderColor = Color.get_Black()

5. Generating QR Code with Logo

For branding purposes, you might want to add a logo to your QR code. Spire.Barcode makes this process seamless while maintaining scannability. Here’s how:

barcodeSettings.SetQRCodeLogoImage("C:\\Users\\Administrator\\Desktop\\logo.png")

When adding a logo:

  • Use a simple, high-contrast logo for best results.
  • Test the scannability after adding the logo.
  • The QR code's error correction (set earlier) helps compensate for the obscured area.

The logo will be centered within the QR code, and Spire.Barcode will automatically resize it to ensure the QR code remains scannable.

Output:

QR code with a logo at the center

6. Wrapping up

Generating QR codes in Python using Spire.Barcode is a straightforward process that offers extensive customization options. From basic QR codes to branded versions with logos and custom styling, the library provides all the tools needed for professional barcode generation.

Key Benefits:

  • Spire.Barcode simplifies QR code generation with a clean API.
  • Extensive customization options allow for branded, visually appealing QR codes.
  • Error correction ensures reliability even with added logos.
  • High-resolution output supports both digital and print use cases.

Whether you're building an inventory system, creating marketing materials, or developing a mobile app integration, Spire.Barcode provides a robust solution for all your QR code generation needs in Python.

7. FAQs

Q1: What is a QR code?

A QR code (Quick Response code) is a type of matrix barcode that can store URLs and other information. It is widely used for quickly linking users to websites, apps, and digital content through mobile devices.

Q2: Can I generate QR codes without a license key?

Yes, you can generate QR codes without a license key; however, the generated barcode will display an evaluation message along with our company logo, which may detract from the user experience.

Q3: Can I generate different types of barcodes with Spire.Barcode?

Yes, Spire.Barcode supports various barcode types, not just QR codes. Detailed documentation can be found here: How to Generate Barcode in Python

Q4: How can I implement a QR code generator in Python using Spire.Barcode?

To implement a QR code generator in Python with Spire.Barcode, create a BarcodeSettings object to configure the QR code properties. Then, use the BarCodeGenerator class to generate the QR code image by calling the GenerateImage() method.

Q5: Can I scan or read QR code using Spire.Barcode?

Yes, you can scan and read QR codes using Spire.Barcode for Python. The library provides functionality for both generating and decoding QR codes. Follow this guide: How to Read Barcode Using Python

Get a Free License

To fully experience the capabilities of Spire.Barcode for Python without any evaluation limitations, you can request a free 30-day trial license.