Published on August 08, 2024By DeveloperBreeze

QR Code with Embedded Logo

import qrcode
from PIL import Image

def create_qr_with_logo(url, logo_path, output_path):
    # Generate a basic QR code
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=10,
        border=4,
    )
    qr.add_data(url)
    qr.make(fit=True)

    # Create an image from the QR Code instance
    qr_img = qr.make_image(fill_color="black", back_color="white").convert('RGB')

    # Open the logo image
    logo = Image.open(logo_path)

    # Calculate the size of the logo to be embedded
    qr_width, qr_height = qr_img.size
    logo_size = (qr_width // 4, qr_height // 4)
    logo = logo.resize(logo_size, Image.ANTIALIAS)

    # Calculate position to place the logo
    logo_position = (
        (qr_width - logo_size[0]) // 2,
        (qr_height - logo_size[1]) // 2
    )

    # Paste the logo image onto the QR code
    qr_img.paste(logo, logo_position, mask=logo)

    # Save the resulting QR code to a file
    qr_img.save(output_path)

# Example usage
create_qr_with_logo(
    url="https://www.example.com",
    logo_path="logo.png",  # Path to your logo image
    output_path="qr_with_logo.png"
)

How It Works

    • Dependencies: This code requires the qrcode and Pillow libraries. You can install them via pip:

pip install qrcode[pil]
   

    • QR Code Generation: The code creates a QR code using the qrcode library. It sets a high error correction level (ERROR_CORRECT_H) to allow for the logo to be embedded.

    • Logo Embedding: It opens the logo image using Pillow, resizes it, and calculates the position to place it at the center of the QR code.

    • Image Pasting: The logo is pasted onto the QR code using the paste method with a mask to maintain transparency.

    • Saving the Image: The final QR code with the embedded logo is saved as a PNG file.

Use Cases

  • Custom QR Codes: Use this script to generate QR codes with a personalized touch by embedding your brand's logo.

  • Marketing: Create QR codes that are visually appealing and easily recognizable for marketing campaigns.

  • Educational: Demonstrate the use of Python libraries for image processing and QR code generation.

Comments

Please log in to leave a comment.

Continue Reading: