Generate QR Code with Logo or Image in Python
In this Python tutorial we learn how to generate a QR code with a logo image inside using qrcode package.
Install qrcode package
Installing the QR code generator package using the following command which will include pillow package for generating image.
pip install qrcode[pil]
Generate QR Code with Logo Inside in Python
The following Python program to show you how to insert a logo image into a QR code during generating the QR code.
For example, we have a logo image file named sample_logo.png as below.
import qrcode
from PIL import Image
logo_file_name = 'sample_logo.png'
data_to_encode = "https://toricode.com"
qr_code = qrcode.QRCode(
error_correction=qrcode.constants.ERROR_CORRECT_H
)
qr_code.add_data(data_to_encode)
qr_code.make()
# qr code image
qr_code_image = qr_code.make_image().convert('RGB')
# logo image
logo = Image.open(logo_file_name)
# populate the position of the logo to center of QR code
logo_x_position = (qr_code_image.size[0] - logo.size[0]) // 2
logo_y_position = (qr_code_image.size[1] - logo.size[1]) // 2
logo_position = (logo_x_position, logo_y_position)
# insert logo image into qr code image
qr_code_image.paste(logo, logo_position)
# save QR code image
qr_code_image.save('toricode_qr.png')
print('QR code with logo successful generated as toricode_qr.png')
QR code with logo successful generated as toricode_qr.png
After execute the program above it will generate QR code image named toricode_qr.png as below.
Happy Coding 😊