Python and QRCodes

dimanche, 4 janvier 2015

Few days ago, I decided to try to generate QRCodes.

This article just shows a possibility using Python.


Googling for QRCodes generation I found some websites proposing to generate QRCodes for you.


The ZXing Generator and the Kaywa Generator seem really powerful and complete, but I was looking for a way of integring QRCode-generation in an piece of software without requiring an Internet access.

A guy (MarkTraceur) commented my post on reddit, talking about a tool he built : QRustom ! Thanks to him !

With python, you can use pyqrcode but it works using a C/C++ encoder and a Java decoder...

I also found the PyQRNative lib that seems to be a rewriting of this javascript generator (pretty sure great things can be done using this JS lib and Node.js).

The code (that you can wget here) would need a serious rewriting to become PEP8 compliant and documented but it works (here's a QR containing URL for this post generated using PyQRNative).

EDIT : After my post on reddit, Chris Beaven told me he did the rewriting. His version is available on Pypi. I've also rewritten this article using his lib.

Note that you'll have also to install the Python Imaging Library (PIL) in order to generate the images themselves.

Just run :

$ sudo pip install pil qrcode


from qrcode import *

qr = QRCode(version=20, error_correction=ERROR_CORRECT_L)
qr.make() # Generate the QRCode itself

# im contains a PIL.Image.Image object
im = qr.make_image()

# To save it"filename.png")

At line 3, we instanciate a new qrcode.QRCode object using two parameters. This class has other parameters that we don't use here (box_size, border, etc...).

The first one is the QR version, an integer between 0 and 40 which define the size of the barcode and the amount of data we'll be able to store.

The second is the correction level (redundancy). As said on Wikipedia, you can choose between :

7% of codewords can be restored
15% can be restored
25% can be restored
30% can be restored

It's this redundancy phenomenon that enables decoding even if the code is damaged.

When the lib guess what you need

The qrcode module add the fit parameter to the QRCode.make() method. If fit is used and QRCode.version is set to None, qrcode will guess the right version.

Faster !

This rewriting bring a short version for fast generation :

import qrcode
img = qrcode.make("your awesome data")

Chris, thank you for that great work !


QR Codes are an elegant way of share data between devices.

They can be used for a lot of applications, from product tracking inside a factory to blog post URL.

The redundancy phenomenon allow artistic use or deformation of QR Codes and things like that :


I really think that these codes are powerful.

Note also that, using processing and QR Codes, you can do Augmented Reality ;)