Thursday, December 26, 2024
Google search engine
HomeLanguagesHow to generate QR Codes with a custom logo using Python ?

How to generate QR Codes with a custom logo using Python ?

In this article, we will discuss how to generate a QR code with an image at its center. We are going to generate a QR code of any text, link, etc., and put an image in the center of that QR code such that it represents a branded QR code

Modules Required:

  • Pillow: It is a lightweight image processing tool that aid in editing, creating, and saving images. Pillow supports many image file formats including BMP, PNG, JPEG, and TIFF. It can be installed using the below command:
pip install Pillow
  • QRcode: It is an external python library used to generate QR codes. It can be installed using the below command:
pip install qrcode

Image used:

Python3




# import modules
import qrcode
from PIL import Image
 
# taking image which user wants
# in the QR code center
Logo_link = 'g4g.jpg'
 
logo = Image.open(Logo_link)
 
# taking base width
basewidth = 100
 
# adjust image size
wpercent = (basewidth/float(logo.size[0]))
hsize = int((float(logo.size[1])*float(wpercent)))
logo = logo.resize((basewidth, hsize), Image.ANTIALIAS)
QRcode = qrcode.QRCode(
    error_correction=qrcode.constants.ERROR_CORRECT_H
)
 
# taking url or text
 
# adding URL or text to QRcode
QRcode.add_data(url)
 
# generating QR code
QRcode.make()
 
# taking color name from user
QRcolor = 'Green'
 
# adding color to QR code
QRimg = QRcode.make_image(
    fill_color=QRcolor, back_color="white").convert('RGB')
 
# set size of QR code
pos = ((QRimg.size[0] - logo.size[0]) // 2,
       (QRimg.size[1] - logo.size[1]) // 2)
QRimg.paste(logo, pos)
 
# save the QR code generated
QRimg.save('gfg_QR.png')
 
print('QR code generated!')


Output:

QR code generated!

QR code:

Explanation:

  • When you run the program then it will take the input image and the base width. After that, the image will be reshaped and a QRcode object will be created.
  • Using the QRcode object various attributes will be assigned such as data or URL will be linked to the QR code using add_data() method, color of the QR code will be assigned using the make_image() method and the reshaped image will be placed in the QR code using the paste() method.
  • Finally, the generated QR code will be saved in a given location using the save() method.
RELATED ARTICLES

Most Popular

Recent Comments