QR Code Generator with Logo
This utility generates a QR code from text or a URL and optionally embeds a logo image in the center. It uses high error correction to ensure the QR code remains scannable even with the logo covering part of the data.
Modules Used:
qrcode: To generate the QR code matrix.- Pillow: To manipulate images (resize logo, paste onto QR code).
- argparse: To handle command-line arguments.
Installation
pip install "qrcode[pil]" pillow
The Code
Save this as qr_logo.py.
import qrcode
from PIL import Image
import argparse
import sys
import os
def generate_qr_with_logo(data, logo_path, output_path, fill_color="black", back_color="white"):
try:
# 1. Generate QR Code
# We use High Error Correction (H) to allow up to 30% damage (covered by logo)
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)
qr_img = qr.make_image(fill_color=fill_color, back_color=back_color).convert('RGB')
# 2. Add Logo
if logo_path and os.path.exists(logo_path):
logo = Image.open(logo_path)
# Calculate logo size
# The logo should not cover more than 25-30% of the QR code area
qr_width, qr_height = qr_img.size
logo_max_size = qr_width // 4 # 25% of QR code size
# Resize logo maintaining aspect ratio
logo.thumbnail((logo_max_size, logo_max_size))
# Calculate position to center the logo
logo_pos = ((qr_width - logo.size[0]) // 2, (qr_height - logo.size[1]) // 2)
# Paste logo
# If logo has transparency (RGBA), use it as a mask
if logo.mode == 'RGBA':
qr_img.paste(logo, logo_pos, mask=logo)
else:
qr_img.paste(logo, logo_pos)
print(f"Logo embedded: {logo_path}")
elif logo_path:
print(f"Warning: Logo file '{logo_path}' not found. Generating standard QR code.")
# 3. Save
qr_img.save(output_path)
print(f"QR Code saved to: {output_path}")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="QR Code Generator with Logo")
parser.add_argument("data", help="Data to encode (URL, text, etc.)")
parser.add_argument("-l", "--logo", help="Path to the logo image file")
parser.add_argument("-o", "--output", default="qrcode.png", help="Output filename (default: qrcode.png)")
args = parser.parse_args()
generate_qr_with_logo(args.data, args.logo, args.output)
Usage
# Generate a standard QR code
python qr_logo.py "https://www.example.com"
# Generate with a logo
python qr_logo.py "https://www.python.org" --logo python_logo.png --output python_qr.png