Generating your own QR Codes with Python
We’re going to take a quick dive into the world of QR codes and learn how to create our very own using Python like below.
To do this, we’ll be leveraging a popular Python library called qrcode
. First things first, let’s make sure we have the necessary tools installed. You can easily install the qrcode library along with the PIL (Python Imaging Library) dependency by running the following command in your terminal:
Installation:
pip install qrcode[pil]
The [pil]
option is necessary if you want to directly display or save the QR code using PIL (Python Imaging Library).
Now that we have our environment set up, let’s jump into the code:
import qrcode
qr = qrcode.QRCode(
box_size=5,
border=5,
)
link='https://medium.com/@codingpilot25'
qr.add_data(link)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
img.save('my_qr.png')
Let’s break down what’s happening here:
- We start by importing the qrcode module.
- Then, we create a QRCode object specifying its box size and border.
- We add the link we want to encode into the QR code using the
add_data
function. qr.make(fit=True)
If ``True`` (or if a size has not been provided), finds the best fit for the data to avoid data overflow errors.- Finally, we create the QR code image using the
make_image
function and save it as a PNG file.
And there you have it! With just a few lines of code, you’ve successfully generated your very own QR code.
Reference: https://pypi.org/project/qrcode/