QR Codes are helpful in a lot of scenarios. For example, let's say you're making a social app where users interact with each other via visiting their profiles. Generating a QR Code for each profile will make it really easy for the users to share their profile. QR codes are also used in retail stores for redirecting to a payment gateway, or for simply sharing a link. In this article, I'll walk you through how you can simply create QR codes with couple of lines of code with the
As I've mentioned before, we'll be using the
pyqrcode package to generate the QR code for us. You can install it with pip simply by running the following command,
pip install pyqrcode
We'll need another module for saving the QR code in the file system, let's install it too.
pip install pypng
Here's the code for generating the QR Code, it's pretty simple.
# Import pyqrcode import pyqrcode # URL or string which will represent the QR code url = "https://dev.to/supanthapaul" # Generate QR code qr_code = pyqrcode.create(url)
Now we have the QR code generated which is of type
pyqrcode. One thing to note is, we can add additional parameters to the
create function like
mode. If you want to learn more, you can see the documentation page here.
Okay, we generated the QR code but there's no way for us to view it. Let's save the QR code to our file system as png!
# ... qr_code.png("image.png", scale=8)
This will save our QR code as
image.png in our current directory.
pyqrcode uses the
pypng package under the hood to save the QR code as a png. The scale parameter sets how large to draw a single module. By default one pixel is used to draw a single module which will make the code too small to be read efficiently. Increasing the scale will make the code larger.
you can add additional parameters like
background, read more about rendering the QR codes here.
As you can see, it's extremely easy to generate and save QR codes with
pyqrcode. If you wanted to generate QR codes for your mobile app, you can create a Python API that returns a QR code image for a particular link. If you want to know how to create web APIs using Python, I've written an article about Getting started with FastAPI to quickly create APIs using Python. Do check that out!