Home > Dev > Python > QR Code Generation

QR Code Generation

This code includes advanced options for customizing the QR code and the logo, making it versatile and professional for various use cases.

import qrcode
from PIL import Image, ImageDraw, ImageOps

# Path to the logo
logo_path = 'image.png'

# Create a QR code instance
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_H,
    box_size=10,
    border=4,
)

# Add data to the QR code
qr.add_data('https://sample.com/')
qr.make(fit=True)

# Generate the QR code image
img_qr = qr.make_image(fill_color="#311cb5", back_color="white").convert('RGB')

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

# Set the logo size
logo_size = 100
logo = logo.resize((logo_size, logo_size), Image.Resampling.LANCZOS)

# Option to add a border around the logo
border_size = 10
border_color = "white"
logo_with_border = ImageOps.expand(logo, border=(border_size, border_size), fill=border_color)

# Create a mask for rounding the corners of the logo
mask = Image.new('L', logo_with_border.size, 0)
draw = ImageDraw.Draw(mask)
draw.rounded_rectangle([(0, 0), logo_with_border.size], radius=border_size, fill=255)

# Apply the mask to the logo with border
logo_with_border.putalpha(mask)

# Position the logo in the center of the QR code
pos = ((img_qr.size[0] - logo_with_border.size[0]) // 2, (img_qr.size[1] - logo_with_border.size[1]) // 2)
img_qr.paste(logo_with_border, pos, logo_with_border)

# Save the final QR code image
img_qr.save('qr_advanced.png')
Back