Created
November 4, 2024 15:58
-
-
Save zircote/68ab077990df0cb2e7b95138d79ee5a2 to your computer and use it in GitHub Desktop.
Generate a QR code with a logo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Import required libraries again after the environment reset | |
from PIL import Image | |
import qrcode | |
qr_data = "https://my-site.com" | |
new_logo_path = "~/Projects/qr/logo.png" | |
new_qr_image_path = "~/Projects/qr/qr_code_with_logo.png" | |
logo_size = 80 # Adjust the size if necessary | |
# Load the new logo image | |
new_logo = Image.open(new_logo_path) | |
# Resize the new logo to fit inside the QR code | |
new_logo = new_logo.resize((logo_size, logo_size)) | |
# Convert the new logo to have an alpha channel (transparency) | |
new_logo = new_logo.convert("RGBA") | |
# Create a mask from the alpha channel for transparency | |
new_logo_mask = new_logo.split()[3] | |
# Re-generate the QR code | |
qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_H) | |
qr.add_data(qr_data) | |
qr.make() | |
# Create the QR code image | |
qr_image = qr.make_image(fill="black", back_color="white").convert("RGB") | |
# Get the dimensions of the QR code | |
qr_width, qr_height = qr_image.size | |
logo_position = ((qr_width - logo_size) // 2, (qr_height - logo_size) // 2) | |
# Paste the new logo with transparency onto the QR code | |
qr_image_with_new_logo = qr_image.copy() | |
qr_image_with_new_logo.paste(new_logo, logo_position, mask=new_logo_mask) | |
# Save the result | |
qr_image_with_new_logo.save(new_qr_image_path) | |
new_qr_image_path |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment