Generate QR codes with a logo image embedded in the center. Use high error correction and paste a logo over the center 20% of the QR code, ensuring it remains scannable due to error correction redundancy.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a great request to create QR codes with embedded logos. I'll provide a comprehensive solution that:
Generates QR codes using python's qrcode library
Embeds a logo image in the center
Uses high error correction level
Ensures the QR code remains scannable
I'll provide multiple examples:
Basic usage
Advanced with customization options
With fallback for logo creation if needed
Best practices for sizing and positioning
Let me create a complete solution:
python
import qrcode
from qrcode.image.pure import PyMagingImage
from PIL import Image
import os
def create_qr_with_logo(data, logo_path=None, output_path="qr_with_logo.png"):
"""
Generate a QR code with an embedded logo.
Args:
data: Data to encode in QR code
logo_path: Path to logo image file
output_path: Path to save the output image
"""
# Create QR code with HIGH error correction (allows up to 30% data loss)
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 image
img = qr.make_image(fill_color="black", back_color="white")
# If no logo provided, return basic QR code
if logo_path is None:
img.save(output_path)
return img
# Convert to RGB if necessary
if img.mode == 'P':
img = img.convert('RGB')
# Paste logo
if isinstance(logo_path, str) and os.path.exists(logo_path):
logo = Image.open(logo_path)
# Handle different image formats by converting to RGB
if logo.mode in ('RGBA', 'LA', 'P'):
logo = logo.convert('RGB')
# Size the logo to occupy roughly 20% of the QR code dimensions
qr_width, qr_height = img.size
logo_size = min(qr_width, qr_height) // 5
logo = logo.resize((logo_size, logo_size), Image.Resampling.LANCZOS)
# Add a white background behind the logo to ensure visibility against the QR pattern
I cannot complete this thought as the next thinking provided appears to be a new section rather than a continuation of the partial thought about creating the white background for the logo.
QR Code Generator with Embedded Logo
I'll provide a complete solution to generate QR codes with logos embedded in the center using high error correction.
Installation
bash
pip install qrcode[pil] pillow
Basic Implementation
python
import qrcode
from PIL import Image
import os
def create_qr_with_logo(
data,
logo_path=None,
output_path="qr_with_logo.png",
qr_version=1,
box_size=10,
border=4,
logo_size_percent=20
):
"""
Generate a QR code with embedded logo.
Args:
data: Text or URL to encode
logo_path: Path to logo image
output_path: Where to save the QR code
qr_version: QR code version (1-40)
box_size: Size of each box in pixels
border: Border size in boxes
logo_size_percent: Logo size as percentage of QR code
Returns:
PIL Image object
"""
# Create QR code with HIGH error correction
# ERROR_CORRECT_H allows recovery from ~30% data loss
qr = qrcode.QRCode(
version=qr_version,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=box_size,
border=border,
)
qr.add_data(data)
qr.make(fit=True)
# Create QR image
qr_img = qr.make_image(fill_color="black", back_color="white").convert('RGB')
# Add logo if provided
if logo_path and os.path.exists(logo_path):
qr_img = _paste_logo(qr_img, logo_path, logo_size_percent)
# Save
qr_img.save(output_path)
print(f"✓ QR code saved to {output_path}")
return qr_img
def _paste_logo(qr_img, logo_path, logo_size_percent=20):
"""Helper function to paste logo on QR code."""
# Open and prepare logo
logo = Image.open(logo_path)
# Convert to RGB if necessary
if logo.mode in ('RGBA', 'LA', 'P'):
logo = logo.convert('RGB')
# Calculate logo dimensions
qr_width, qr_height = qr_img.size
logo_size = max(int(min(qr_width, qr_height) * logo_size_percent / 100), 50)
# Resize logo
logo = logo.resize((logo_size, logo_size), Image.Resampling.LANCZOS)
# Create white background for logo (with border)
padding_percent = 10
padding = int(logo_size * padding_percent / 100)
bg_size = logo_size + (2 * padding)
logo_bg = Image.new('RGB', (bg_size, bg_size), 'white')
logo_bg.paste(logo, (padding, padding))
# Center logo on QR code
x = (qr_width - bg_size) // 2
y = (qr_height - bg_size) // 2
qr_img.paste(logo_bg, (x, y))
return qr_img
# Example usage
if __name__ == "__main__":
# Simple example
create_qr_with_logo(
data="https://github.com",
output_path="qr_basic.png"
)
# With logo (if you have one)
create_qr_with_logo(
data="https://github.com",
logo_path="logo.png", # Add your logo path
output_path="qr_with_logo.png",
logo_size_percent=20
)
Advanced Solution with Multiple Features
python
Create Test Logo Image
python
def create_test_logo(output_path="logo.png", size=200):
"""Create a simple test logo."""
# Create colorful test logo
img = Image.new('RGB', (size, size), color='white')
draw = ImageDraw.Draw(img)
# Draw circle
draw.ellipse(
[(10, 10), (size-10, size-10)],
fill='#FF6B6B',
outline='#C92A2A',
width=3
)
# Draw text
try:
draw.text(
(size//2, size//2),
"LOGO",
fill='white',
anchor='mm'
)
except:
pass
img.save(output_path)
print(f"✓ Test logo created: {output_path}")
return img
# Create test logo
create_test_logo()
Best Practices & Tips
python
"""
IMPORTANT CONSIDERATIONS FOR SCANNABLE QR CODES:
1. ERROR CORRECTION LEVELS:
- L (7% recovery): Basic, small logos/damage
- M (15% recovery): Standard, moderate logos
- Q (25% recovery): High, larger logos
- H (30% recovery): Maximum, large logos (RECOMMENDED)
2. LOGO SIZING:
- 15-20%: Safe, easily recoverable
- 20-25%: High error correction needed
- >25%: Risk of scan failures
3. LOGO FORMAT:
- Use PNG with transparency for best results
- Square logos work best
- Solid colors are more reliable than gradients
- Add white border around logo for better contrast
4. QR CODE SIZE:
- Larger box_size = larger final image (recommended)
- Large images are easier to scan
- Minimum 100x100 pixels for reliable scanning
5. COLORS:
- High contrast black/white is most reliable
- Dark on light background works best
- Avoid low-contrast colors
6. TESTING:
- Always test with multiple scanner apps
- Test on various devices and lighting conditions
- Keep original data accessible as fallback
"""
# Recommended configuration for production
PRODUCTION_CONFIG = QRConfig(
error_correction=ErrorCorrectionLevel.H, # Maximum recovery
box_size=15, # Larger = easier to scan
border=5,
fill_color="black",
back_color="white",
logo_size_percent=18, # Safe size
add_logo_border=True,
border_color="white"
)
Testing Scannability
python
import subprocess
import sys
def test_qr_code(qr_path):
"""Test if QR code can be scanned."""
try:
# Try to read with pyzbar (requires: pip install pyzbar)
from pyzbar.pyzbar import decode
img = Image.open(qr_path)
decoded = decode(img)
if decoded:
for obj in decoded:
print(f"✓ QR Code readable!")
print(f" Data: {obj.data.decode('utf-8')}")
return True
else:
print(f"✗ QR Code not readable")
return False
except ImportError:
print("Install pyzbar: pip install pyzbar python-libzbar")
return None
# Test your QR code
# test_qr_code("example_custom.png")
Key Features
✅ High Error Correction - 30% data recovery capability
✅ Embedded Logo - Centered with white background
✅ Configurable - Multiple customization options
✅ Batch Processing - Generate multiple codes
✅ Production Ready - Best practices included
✅ Testable - Can verify scannability
This solution ensures your QR codes remain scannable even with logos covering up to 20% of the center area!
import qrcode
from PIL import Image, ImageDraw
import os
from dataclasses import dataclass
from enum import Enum
class ErrorCorrectionLevel(Enum):
"""QR Code error correction levels."""
L = qrcode.constants.ERROR_CORRECT_L # 7% recovery
M = qrcode.constants.ERROR_CORRECT_M # 15% recovery
Q = qrcode.constants.ERROR_CORRECT_Q # 25% recovery
H = qrcode.constants.ERROR_CORRECT_H # 30% recovery
@dataclass
class QRConfig:
"""Configuration for QR code generation."""
error_correction: ErrorCorrectionLevel = ErrorCorrectionLevel.H
box_size: int = 10
border: int = 4
fill_color: str = "black"
back_color: str = "white"
logo_size_percent: int = 20
add_logo_border: bool = True
border_color: str = "white"
class QRCodeWithLogo:
"""Advanced QR Code generator with logo embedding."""
def __init__(self, config: QRConfig = None):
"""Initialize with configuration."""
self.config = config or QRConfig()
def generate(
self,
data: str,
logo_path: str = None,
output_path: str = "qr_code.png"
) -> Image.Image:
"""
Generate QR code with optional logo.
Args:
data: Data to encode
logo_path: Path to logo image
output_path: Where to save
Returns:
PIL Image object
"""
# Create QR code
qr = qrcode.QRCode(
version=1,
error_correction=self.config.error_correction.value,
box_size=self.config.box_size,
border=self.config.border,
)
qr.add_data(data)
qr.make(fit=True)
# Make image
img = qr.make_image(
fill_color=self.config.fill_color,
back_color=self.config.back_color
).convert('RGB')
# Add logo
if logo_path and os.path.exists(logo_path):
img = self._embed_logo(img, logo_path)
img.save(output_path)
print(f"✓ QR code generated: {output_path}")
return img
def _embed_logo(self, qr_img: Image.Image, logo_path: str) -> Image.Image:
"""Embed logo in center of QR code."""
try:
logo = Image.open(logo_path)
except Exception as e:
print(f"✗ Error opening logo: {e}")
return qr_img
# Convert to RGB
if logo.mode in ('RGBA', 'LA', 'P'):
logo = logo.convert('RGB')
# Calculate dimensions
qr_w, qr_h = qr_img.size
logo_size = max(int(min(qr_w, qr_h) * self.config.logo_size_percent / 100), 40)
# Resize logo
logo = logo.resize((logo_size, logo_size), Image.Resampling.LANCZOS)
# Create background
padding = 8
bg_size = logo_size + (2 * padding)
background = Image.new(
'RGB',
(bg_size, bg_size),
self.config.border_color
)
background.paste(logo, (padding, padding))
# Add border if requested
if self.config.add_logo_border:
draw = ImageDraw.Draw(background)
draw.rectangle(
[(0, 0), (bg_size - 1, bg_size - 1)],
outline=self.config.fill_color,
width=1
)
# Center and paste
x = (qr_w - bg_size) // 2
y = (qr_h - bg_size) // 2
qr_img.paste(background, (x, y))
return qr_img
def generate_batch(
self,
data_list: list,
logo_path: str = None,
output_dir: str = "qr_codes"
) -> list:
"""Generate multiple QR codes."""
os.makedirs(output_dir, exist_ok=True)
paths = []
for i, data in enumerate(data_list):
output_path = os.path.join(output_dir, f"qr_{i+1:03d}.png")
self.generate(data, logo_path, output_path)
paths.append(output_path)
return paths
# Usage examples
if __name__ == "__main__":
# Example 1: Basic usage with HIGH error correction
qr_gen = QRCodeWithLogo()
qr_gen.generate(
data="https://example.com",
output_path="example_basic.png"
)
# Example 2: With custom configuration
config = QRConfig(
error_correction=ErrorCorrectionLevel.H,
box_size=12,
border=5,
fill_color="darkblue",
back_color="white",
logo_size_percent=20,
add_logo_border=True
)
qr_gen = QRCodeWithLogo(config)
qr_gen.generate(
data="https://github.com",
logo_path="logo.png", # Add your logo
output_path="example_custom.png"
)
# Example 3: Batch generation
urls = [
"https://example.com/1",
"https://example.com/2",
"https://example.com/3",
]
qr_gen.generate_batch(
data_list=urls,
logo_path="logo.png",
output_dir="generated_qr_codes"
)