QR code generator and reader/scanner in Python

Hi guys

Nowadays we see a lot of QR codes being used in commercial businesses, especially for transaction. QR code generator can encode many different kinds of data, such as plain text, website link (http or https protocol), vcard, geolocation and call.

There are several standards of QR codes. According to Wikipedia, there are four layers of structure of a QR code, as shown in the image below:

I am going to write tutorial on how to generate QR codes using qrcode Python package available at the PyPi website.

Part 1: Generate QR code using qrcode

Install qrcode package by using pip:

pip install qrcode

You should have a new command ‘qr’ in the terminal. From terminal (if you’re in UNIX/Linux environment) or command prompt (Windows), type:

qr "https://naimibrahim.me" > qrcode.png

It should generate an image in PNG format with the generated text encoded, like below:

For more advanced usage, please refer to the documentation.

Part 2: Read/scan QR code using zbarlight

My choice of package to read QR image is zbar, and its wrapper – zbarlight.

Firstly, download zbar source ball from its website http://zbar.sourceforge.net/download.html and compile it, or use the existing binary for your operating system.

from PIL import Image
import zbarlight
import sys

if len(sys.argv) < 2:
    exit
file_path = sys.argv[1]
with open(file_path, 'rb') as image_file:
    image = Image.open(image_file)
    image.load()

codes = zbarlight.scan_codes('qrcode', image)
print('QR codes: %s' % codes)

Run the above qrcode_scanner.py script by executing:

python qrcode_scanner.py qrcode.png

The output should be:

QR codes: [b'https://naimibrahim.me']

Now, you can even set up a web service to generate QR codes from your visitors, or print QR codes on pamphlets based on requirements from your customers, or any other idea that you have 🙂

Leave a Reply