Search⌘ K
AI Features

Reading and Writing QR Codes

Explore how to generate QR codes using the qrcode library with customizable parameters, embed images into QR codes, and use the pyzbar library to decode and locate QR codes in images. This lesson builds hands-on skills for handling 2D barcodes with Python.

A quick way to generate a QR code

Here is a quick example that shows how to generate a QR code containing a link to the Educative website:

Python 3.10.4
import qrcode
data = 'https://educative.io'
img = qrcode.make(data)
print(type(img))
img.save('output/qrcode.png')

Line 1: First, we import the qrcode library.

Line 2: Then, we define the data we wish to encode in the QR code. In this case, we use the URL of the Educative website. This data can be any kind of character string data. It doesn’t have to be a URL.

Line 3: By using the qrcode.make() function, we generate a QR code using the data we just defined. The output is a PIL image. Consequently, we can apply all the image operations from the PIL library to the resulting image.

Line 4: We show that the type of output from the above function is indeed an image. For this, we use a print(type()) statement.

Line 5: Finally, we use the save() method on the PIL image to save the QR code image to a PNG file.

More options for generating a QR code

The qrcode library also allows us to create QR codes using various parameters. With this, we can achieve more control over the generated QR codes.

Below, we can see a more advanced example using various parameters:

Python 3.10.4
import qrcode
qr = qrcode.QRCode(
version = 2,
error_correction = qrcode.constants.ERROR_CORRECT_H,
box_size = 10,
border = 2,
)
data = 'https://educative.io'
qr.add_data(data)
qr.make(fit = True)
img = qr.make_image(fill_color = "black", back_color = "white")
img.save('output/qrcode.png')

Lines 2–7: To start out, we define an instance of the qrcode.QRCode() class. This constructor allows us to set a few parameters.

Line 3: Here, we first set the version of the QR code to 2. As we mentioned before, QR codes can have version numbers from 1 to 40.

These version numbers ...