#!/usr/bin/env python3
"""
Branded QR Code Generator
=========================
A Python script to generate QR codes with custom branding, including:
- Custom foreground and background colors
- Optional centered logo overlay (with transparency support and aspect ratio preservation)
- Configurable box size, border, and error correction level
Requirements:
pip install qrcode[pil] pillow
Usage:
python qr_brand.py "https://example.com" -o qr.png -l logo.png --fg "#FF5733" --bg white --size 12 --error H
Examples:
python qr_brand.py "Hello, World!" -o hello.png
python qr_brand.py "https://trailblazerlabs.ai" -o branded.png -l mylogo.png --fg black --bg "#F0F8FF"
"""
import argparse
from PIL import Image
import qrcode
from qrcode.constants import ERROR_CORRECT_L, ERROR_CORRECT_M, ERROR_CORRECT_Q, ERROR_CORRECT_H
def generate_branded_qr(data, output="qr.png", logo_path=None, fg_color="black", bg_color="white",
box_size=10, border=4, error_correction="H"):
"""
Generate a branded QR code image.
Args:
data (str): Data to encode in the QR code.
output (str): Output image file path.
logo_path (str, optional): Path to logo image for center overlay.
fg_color (str): Foreground color (e.g., "black", "#FF5733").
bg_color (str): Background color (e.g., "white", "#F0F8FF").
box_size (int): Size of each QR module in pixels.
border (int): Border width in modules.
error_correction (str): Error correction level ("L", "M", "Q", "H").
"""
# Error correction mapping
error_map = {
"L": ERROR_CORRECT_L,
"M": ERROR_CORRECT_M,
"Q": ERROR_CORRECT_Q,
"H": ERROR_CORRECT_H,
}
# Create QR code object
qr = qrcode.QRCode(
version=None, # Auto-fit
error_correction=error_map[error_correction],
box_size=box_size,
border=border,
)
qr.add_data(data)
qr.make(fit=True)
# Generate base image with custom colors
img = qr.make_image(fill_color=fg_color, back_color=bg_color)
# Overlay logo if provided
if logo_path:
try:
logo = Image.open(logo_path).convert("RGBA")
# Resize logo to ~20% of QR size while preserving aspect ratio
logo_max_size = img.size[0] // 5
logo.thumbnail((logo_max_size, logo_max_size), Image.Resampling.LANCZOS)
# Calculate center position
paste_x = (img.size[0] - logo.size[0]) // 2
paste_y = (img.size[1] - logo.size[1]) // 2
pos = (paste_x, paste_y)
# Paste logo with transparency mask
img.paste(logo, pos, logo)
print(f"Logo '{logo_path}' overlaid successfully.")
except Exception as e:
print(f"Warning: Failed to overlay logo '{logo_path}': {e}")
# Save the image
img.save(output)
print(f"Branded QR code saved to '{output}'")
print(f"QR dimensions: {img.size[0]}x{img.size[1]} pixels")
print("Tip: Test scannability, especially with logos (high error correction recommended).")
def main():
parser = argparse.ArgumentParser(
description="Generate QR codes with custom branding (colors + optional logo).",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
%(prog)s "https://example.com" -o qr.png
%(prog)s "Text data" -l logo.png --fg "#00FF00" --bg "#000033" --size 15 --error H -o custom.png
"""
)
parser.add_argument("data", help="Data to encode (text, URL, etc.)")
parser.add_argument("-o", "--output", default="qr.png", help="Output PNG file (default: qr.png)")
parser.add_argument("-l", "--logo", help="Path to logo image (PNG recommended for transparency)")
parser.add_argument("--fg", "--foreground", default="black", help="Foreground color (default: black)")
parser.add_argument("--bg", "--background", default="white", help="Background color (default: white)")
parser.add_argument("--size", type=int, default=10, help="Box/module size in pixels (default: 10)")
parser.add_argument("--border", type=int, default=4, help="Quiet zone border in modules (default: 4)")
parser.add_argument("--error", choices=["L", "M", "Q", "H"], default="H",
help="Error correction: L=~7%, M=~15%, Q=~25%, H=~30% (default: H)")
args = parser.parse_args()
generate_branded_qr(
data=args.data,
output=args.output,
logo_path=args.logo,
fg_color=args.foreground,
bg_color=args.background,
box_size=args.size,
border=args.border,
error_correction=args.error
)
if __name__ == "__main__":
main()
Quick Start
-
Install dependencies:
pip install qrcode[pil] pillow
-
Save the script as qr_brand.py and run:
python qr_brand.py "https://trailblazerlabs.ai"
-
With branding:
python qr_brand.py "https://trailblazerlabs.ai" -o branded.png -l your_logo.png --fg "#2196F3" --bg white --error H
Features
- Custom Colors: Supports color names (e.g., "red") or hex (e.g., "#FF5733").
- Logo Overlay: Automatically resizes and centers logo (preserves aspect ratio, supports transparency).
- High Customizability: Box size, border, error correction (use "H" for logos to ensure scannability).
- Error Handling: Gracefully handles missing logos; auto-fits QR version.
- Output: Always PNG for best quality/transparency.
Test your generated QR codes with a scanner app to verify readability! 🚀