The user wants a Python script to generate QR codes with custom branding.
This means I need to:
Identify the core library: qrcode is the standard Python library for this. I'll also need Pillow (PIL) for image manipulation (resizing the logo, blending it into the QR code).
Determine the features:
Generate a standard QR code from a URL or text.
Add a logo/image in the center.
Customize colors (foreground, background).
Handle sizing to ensure the QR code remains scannable after adding the logo.
Structure the script:
Import necessary libraries.
Define a function, say generate_branded_qr, taking parameters like data (URL), logo path, output path, and colors.
Logic within the function:
Generate the base QR code.
Convert it to an PIL image.
Open the logo image.
Calculate the size for the logo (crucial: must not be too large, usually < 30% of the QR code size, or error correction must handle it).
Position the logo in the center.
Paste the logo onto the QR code.
Save the result.
Refinement - Error Correction: To put a logo on top of a QR code, you must use high error correction (H level). This is a critical technical detail.
Refinement - Dependency Management: I need to tell the user what to install (pip install qrcode[pil] or pip install qrcode pillow).
Drafting the Code:
python
import qrcode
from PIL import Image
def create_qr(data, logo_path, output_path):
# 1. Create QR instance with high error correction
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_H, # Important!
box_size=10,
border=4,
)
qr.add_data(data)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white").convert('RGB')
# 2. Open Logo
logo = Image.open(logo_path)
# 3. Calculate size and position
# The logo shouldn't cover too much of the code.
# Let's say max 30% width.
qr_width, qr_height = img.size
logo_max_width = qr_width // 3
# Resize logo maintaining aspect ratio
# ... (code to resize) ...
# Calculate position (center)
pos = ((qr_width - logo_width) // 2, (qr_height - logo_height) // 2)
# 4. Paste
img.paste(logo, pos, mask=logo) # mask is for transparency
img.save(output_path)
Adding Polish:
Add comments.
Add a main block to run the example.
Handle edge cases (like if the logo doesn't exist, though for a script example, standard happy path is usually enough, maybe a try-except).
Make the script flexible (arguments or variables at the top).
Final Output Generation:
Write the Python code.
Explain the dependencies.
Explain the parameters.
Provide a usage example.
(Self-Correction during drafting): Sometimes qrcode returns an image that isn't in RGB mode by default (it might be palette mode). Using .convert('RGB') is safer before pasting a colored logo to avoid mode mismatch errors.
(Self-Correction on Logo Size): If the user provides a huge logo, resizing it is necessary. If they provide a non-square logo, aspect ratio must be preserved.
Constructing the Final Response:
Prerequisites: pip install qrcode pillow
The Script: Clean, commented Python code.
Explanation: Why ERROR_CORRECT_H is used, how the math works for centering.
Let's write the actual response based on this plan.
To create a branded QR code with a logo, you need a Python script that generates the QR code with High Error Correction. This is crucial because covering the center of a QR code with a logo destroys data; high error correction allows the scanner to reconstruct the missing information.
You will need the qrcode and Pillow (PIL) libraries.
1. Install Dependencies
Run this command in your terminal:
bash
pip install qrcode pillow
2. The Python Script
Here is a complete, reusable function to generate a branded QR code. It handles resizing the logo, calculating the center position, and smoothing the edges.
python
import qrcode
from PIL import Image
import os
def generate_branded_qr(data, logo_path, output_path="branded_qr.png", fill_color="black", back_color="white"):
"""
Generates a QR code with a logo centered on top.
:param data: The URL or text to encode.
:param logo_path: Path to the logo image file (PNG recommended for transparency).
:param output_path: Filename for the final QR code.
:param fill_color: Color of the QR code pattern.
:param back_color: Background color.
"""
# 1. Check if logo exists
if not os.path.exists(logo_path):
print(f"Error: Logo file not found at {logo_path}")
return
# 2. Generate the QR Code
# ERROR_CORRECT_H is required (approx 30% of code can be covered/destroyed)
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=4,
)
qr.add_data(data)
qr.make(fit=True)
# Create the image
qr_img = qr.make_image(fill_color=fill_color, back_color=back_color).convert('RGB')
# 3. Open and Resize Logo
try:
logo = Image.open(logo_path)
# Calculate the maximum size the logo can be (approx 30% of the QR code width)
qr_width, qr_height = qr_img.size
logo_max_size = qr_width * 0.30
# Calculate aspect ratio to resize without stretching
wpercent = (logo_max_size / float(logo.size[0]))
hsize = int((float(logo.size[1]) * float(wpercent)))
# Use LANCZOS (formerly ANTIALIAS) for high-quality resizing
logo = logo.resize((int(logo_max_size), hsize), Image.Resampling.LANCZOS)
# 4. Calculate Position (Center)
logo_pos = (
(qr_width - logo.size[0]) // 2,
(qr_height - logo.size[1]) // 2
)
# 5. Paste Logo onto QR Code
# If the logo has transparency (alpha channel), use it as the mask
if logo.mode == "RGBA":
qr_img.paste(logo, logo_pos, logo)
else:
qr_img.paste(logo, logo_pos)
# 6. Save
qr_img.save(output_path)
print(f"Success! Branded QR code saved to: {output_path}")
except Exception as e:
print(f"An error occurred: {e}")
# =========================================
# USAGE EXAMPLE
# =========================================
# Configuration
WEBSITE_URL = "https://github.com"
LOGO_FILE = "my_logo.png" # Replace with your actual logo file path
OUTPUT_FILE = "my_custom_qr.png"
# Run the function
if __name__ == "__main__":
# Create a dummy logo image for testing if one doesn't exist
if not os.path.exists(LOGO_FILE):
print("Creating a dummy logo for demonstration...")
dummy_logo = Image.new('RGB', (200, 200), color = 'red')
dummy_logo.save(LOGO_FILE)
# Generate the QR Code
generate_branded_qr(
data=WEBSITE_URL,
logo_path=LOGO_FILE,
output_path=OUTPUT_FILE,
fill_color="#000000", # Optional: Hex color codes work here
back_color="#FFFFFF"
)
How it works:
Error Correction (ERROR_CORRECT_H): This is the most important setting. Standard QR codes can be read if up to 7% of the code is dirty or damaged. By setting this to H (High), the code stores redundant data so it can be read even if up to 30% of the code is obscured (by your logo).
Resizing: The script calculates a resize ratio to ensure the logo takes up roughly 30% of the width. If the logo is too big, scanners won't be able to read the QR code.
Transparency Handling: The script checks if your logo is a PNG with transparency (RGBA mode). If it is, it uses the alpha channel as a mask when pasting, allowing the QR background to show through transparent parts of your logo (e.g., a circular logo).
Convert to RGB: qr.make_image sometimes returns a palette image. We convert it to RGB mode to ensure custom background colors render correctly.