Create a Python script to generate QR codes with custom branding.
- User
Create a Python script to generate QR codes with custom branding.
- Assistant
Designing a QR Code Script
The user wants a Python script to generate QR codes with custom branding, which means I might need to clarify some details since the request is quite broad. I can plan to use libraries like qrcode or segno, and I’ll need to focus on standard features including input data, custom logos, and color options.
I should design a CLI script that accepts parameters like data string, output file, colors, and logo overlay. I’ll ensure I include instructions for dependencies and provide a template for customization.Creating a QR Code Script
I need to outline the prerequisites for the script by mentioning that the user should install
qrcode[pil]and Pillow. The Python script begins with importing necessary libraries and defining functions for handling color strings and QR code creation.I’ll keep it simple with a
make_qrfunction that generates the QR code image, including an optional logo feature. I also plan to add argument parsing for various options like data input, output filename, and logo scaling. Though the user didn’t specifically request a CLI, it seems beneficial to include it.Focusing on Best PracticesI need to be cautious with the library names and color specifications, keeping best practices in mind. For custom branding, using a high error correction level (H) is important to ensure the QR code remains scannable. It's also essential to maintain a safe border around the edges.
When embedding a logo, I’ll set a default logo size ratio of 0.25, ensuring we don’t cover too much area. I'll aim for a concise yet clear write-up, including a small docstring at the top. Let's get to crafting this! Below is a self‑contained Python script that generates QR codes with custom colors and an optional centered logo (branding).
It uses:
qrcode(for QR generation)Pillow(for image manipulation / logo compositing)
1. Install dependencies
pip install qrcode[pil] pillow
2. Script:
branded_qr.py#!/usr/bin/env python3 """ Generate branded QR codes with custom colors and an optional logo. Usage examples: python branded_qr.py \ --data "https://example.com" \ --output qr_example.png \ --fg "#111827" \ --bg "#F9FAFB" \ --logo logo.png \ --logo-scale 0.25 \ --ec-level H """ import argparse import os from typing import Tuple from PIL import Image import qrcode from qrcode.constants import ERROR_CORRECT_L, ERROR_CORRECT_M, ERROR_CORRECT_Q, ERROR_CORRECT_H def parse_color(color_str: str) -> str: """ Parse a color specification. Accepts: - Hex-like strings: "#RRGGBB", "RRGGBB" - Comma separated RGB: "r,g,b" (0-255) Returns a Pillow-compatible color string/tuple. """ color_str = color_str.strip() if "," in color_str: parts = color_str.split(",") if len(parts) != 3: raise ValueError(f"Invalid RGB color: {color_str}") return tuple(int(p) for p in parts) if color_str.startswith("#"): return color_str # Assume hex without '#' if len(color_str) == 6: return f"#{color_str}" raise ValueError(f"Invalid color format: {color_str}") def get_error_correction(level: str) -> int: """ Map user-friendly error correction level (L/M/Q/H) to qrcode constant. """ level = level.upper() mapping = { "L": ERROR_CORRECT_L, "M": ERROR_CORRECT_M, "Q": ERROR_CORRECT_Q, "H": ERROR_CORRECT_H, } if level not in mapping: raise ValueError(f"Invalid error correction level '{level}'. Use one of L, M, Q, H.") return mapping[level] def add_logo( qr_img: Image.Image, logo_path: str, scale: float = 0.2, ) -> Image.Image: """ Add a centered logo on top of a QR code image. Args: qr_img: QR code image (Pillow Image, typically RGB or RGBA). logo_path: Path to the logo image file. scale: Fraction of QR code width/height that the logo should occupy (e.g., 0.2 = 20%). Returns: Composited QR image with logo. Notes: - Uses logo alpha transparency if present. - For reliability, keep scale <= ~0.3 and use high error correction. """ if not os.path.exists(logo_path): raise FileNotFoundError(f"Logo file not found: {logo_path}") logo = Image.open(logo_path).convert("RGBA") qr_w, qr_h = qr_img.size logo_size = int(min(qr_w, qr_h) * scale) # Maintain aspect ratio logo.thumbnail((logo_size, logo_size), Image.LANCZOS) # Center the logo pos = ( (qr_w - logo.width) // 2, (qr_h - logo.height) // 2, ) # Ensure QR is RGBA to support alpha compositing if qr_img.mode != "RGBA": qr_img = qr_img.convert("RGBA") qr_img.paste(logo, pos, mask=logo) return qr_img def generate_qr( data: str, output_path: str, fg_color: str = "#000000", bg_color: str = "#FFFFFF", version: int | None = None, box_size: int = 10, border: int = 4, ec_level: str = "H", logo_path: str | None = None, logo_scale: float = 0.2, ) -> None: """ Generate a (branded) QR code and save to a file. Args: data: Data to encode (URL, text, etc.). output_path: Path to saved PNG. fg_color: Foreground color (QR modules). bg_color: Background color. version: QR version (1–40) or None for automatic. box_size: Pixel size for each QR box. border: Border (quiet zone) in boxes. ec_level: Error correction level 'L', 'M', 'Q', or 'H'. logo_path: Optional path to logo to place in the center. logo_scale: Fraction of QR size used by logo (0.1 – 0.3 recommended). """ if not data: raise ValueError("Data to encode must not be empty.") fg = parse_color(fg_color) bg = parse_color(bg_color) ec = get_error_correction(ec_level) qr = qrcode.QRCode( version=version, error_correction=ec, box_size=box_size, border=border, ) qr.add_data(data) qr.make(fit=True) img = qr.make_image(fill_color=fg, back_color=bg).convert("RGB") if logo_path: img = add_logo(img, logo_path, scale=logo_scale) # Ensure directory exists os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True) img.save(output_path) print(f"Saved QR code to {output_path}") def build_arg_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description="Generate QR codes with custom colors and optional logo branding." ) parser.add_argument( "--data", "-d", required=True, help="Data to encode (e.g., URL, text, vCard).", ) parser.add_argument( "--output", "-o", default="qr_code.png", help="Output PNG file path (default: qr_code.png).", ) parser.add_argument( "--fg", "--foreground", default="#000000", help='Foreground color (e.g. "#000000", "000000", or "0,0,0").', ) parser.add_argument( "--bg", "--background", default="#FFFFFF", help='Background color (e.g. "#FFFFFF", "FFFFFF", or "255,255,255").', ) parser.add_argument( "--version", type=int, default=None, help="QR version (1–40) or omit for automatic sizing.", ) parser.add_argument( "--box-size", type=int, default=10, help="Pixel size of each QR box (default: 10).", ) parser.add_argument( "--border", type=int, default=4, help="Border (quiet zone) in boxes (default: 4).", ) parser.add_argument( "--ec-level", default="H", choices=["L", "M", "Q", "H"], help="Error correction level (L, M, Q, H). Higher = more robust (default: H).", ) parser.add_argument( "--logo", help="Path to logo image to place in the center of the QR code.", ) parser.add_argument( "--logo-scale", type=float, default=0.2, help="Logo size as fraction of QR size (e.g., 0.2 = 20%%).", ) return parser def main() -> None: parser = build_arg_parser() args = parser.parse_args() generate_qr( data=args.data, output_path=args.output, fg_color=args.fg, bg_color=args.bg, version=args.version, box_size=args.box_size, border=args.border, ec_level=args.ec_level, logo_path=args.logo, logo_scale=args.logo_scale, ) if __name__ == "__main__": main()
3. Example usages
Simple black‑on‑white QR:
python branded_qr.py \ --data "https://yourbrand.com" \ --output qr_basic.pngCustom brand colors:
python branded_qr.py \ --data "https://yourbrand.com" \ --output qr_brand.png \ --fg "#111827" \ --bg "#F9FAFB"With logo at center:
python branded_qr.py \ --data "https://yourbrand.com" \ --output qr_branded_logo.png \ --fg "#111827" \ --bg "#F9FAFB" \ --logo path/to/logo.png \ --logo-scale 0.25 \ --ec-level HIf you tell me your brand colors or desired style (flat, gradient, dark mode, etc.), I can adjust this script specifically for your branding.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.