Generating QR Codes using Python Libraries

Marc Bolle
11 min readApr 10, 2023

--

You may have noticed QR codes popping up everywhere lately. They’re called “Quick Response Code” because they’re super easy to scan with any digital device and they provide information in a snap. A single QR code can hold up to 4,000 alphanumeric characters in a grid of square-shaped pixels. That’s a lot of information packed into a small space, making it a super efficient way to store data.

QR codes became one of the most practical digital innovations every businessmen and marketer are turning into these days, as they provide an easy way to share information with customers, promote products or services cost-effectively, and track customer behavior for improved marketing strategies.

Create QR Codes using Python

Python includes several packages that make creating QR codes straightforward. If you want to generate QR codes with personalized content using Python, you’ve come to the right place!

The three main and easier Python packages to create QR codes are:

  1. qrcode
  2. PyQRCode
  3. segno

We’ll learn how to use them in this article. (If you want to discover the module that offers you the most customization options for a QR code, go directly to the segno module)

1. Generate QR Codes with the ‘qrcode’ library

qrcode is an amazing Python library that can generate QR codes in a snap! Not only is it super easy to use, but it also gives us the flexibility to create QR codes for various types of data, including URLs, text, email addresses, phone numbers, and more.

But that’s not all — qrcode also lets us customize our QR codes to our heart’s content. We can easily adjust the size and color of the code to match our branding or aesthetic preferences. Whether we’re creating QR codes for a website, a promotional campaign, or just for fun, qrcode is the way to go. So why not give it a try and start generating stunning QR codes today?

We can install qrcode (with pillow for generating images) via pip. Simply run the following code in your command line:

pip install qrcode[pil]

We can also install qrcode via the Anaconda command prompt:

conda install -c conda-forge qrcode

• Simple QR Code with qrcode

We can generate a simple QR code that displays text in three lines of code!
To do this, we use the qrcode.make()function and pass our text as the argument.

The code below produces automatically a simple QR code which reads “Hello World!”

import qrcode

simple_QR = qrcode.make('Hello World!')
simple_QR

We can save the QR code as an image on our disk with the function save():

simple_QR.save('Hello_World.png')

• Custom QR Code with qrcode

qrcode also allows us to generate more advanced QR codes with the QRcode class. It comes with several parameters and properties that we can adjust:

advanced_QR = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=4,
)
  • error_correction: aids the QR code detection when it is distorted or when there is an overlay image. This prevents confusion with other QR codes.
    There are four constant available with different percentage of error correction:
    ERROR_CORRECT_L: up to 7% errors can be corrected,
    ERROR_CORRECT_M: up to 15% errors can be corrected,
    ERROR_CORRECT_Q: default. Up to 25% errors can be corrected.
    ERROR_CORRECT_H: up to 30% errors can be corrected.
  • box_size: ontrols the number of pixels in each box of the QR code (e.g. 10 equels to 10 pixels per box).
  • border: controls the thickness of the border. The default border is 4 pixels, which is very thick.
  • version: controls the size of the QR code. It accepts an integer from 1 to 40. Version 1 being the smallest with a 21×21 matrix.
    If you aren’t sure about which version to use, you can set version to None and add the make(fit=True) function which will set the version automatically for you:
advanced_QR=qrcode.QRCode(
version=None,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=4,
)
advanced_QR.make(fit=True)

Then, we add the content the QR code will display by calling the add_data()function and add the text as an argument:

advanced_QR.add_data('Hello World!')

Finally, we generate the QR code with the make_image() function.

This function can be used to apply specific colors using two arguments:
fill_color changes the painting color of the QR code,
back_color changes the background color of the QR code.

QR_code_img = advanced_QR.make_image(fill_color="white", back_color="#D3D3D3")
QR_code_img

QR_code_img.save('QR_Code.png')

2. Generate QR Codes with the ‘PyQRCode’ library

PyQRCode is a super user-friendly QR code generator that’s perfect for anyone who wants to create QR codes without a lot of hassle. In fact, we can generate a QR code with only two lines of Python code, making it a great option for beginners or anyone who needs to quickly generate a QR code on the fly.

But don’t let its simplicity fool us— the PyQRCode module also gives us a lot of control over our QR codes. We can adjust various properties and create more advanced QR codes that are tailored to our specific needs. With this module, we can make sure our QR codes stand out and are easily scannable, all while using simple Python code. It’s a win-win!

PyQRCode can be installed from pip via the command line:

pip install pyqrcode

• Simple QR Code with PyQRCode

Using the pyqrcode.create() function, it is possible to generate a QR code easily. The content is provided as an argument, and the function will automatically adjust its properties. The output of this function is a QRCode object as follow:

import pyqrcode

QR_code = pyqrcode.create("Hello World!")
print(QR_code)

QRCode(content=b'Hello World!', error='H', version=2, mode='binary')

After creating the QR Code object, we can use the svg() and eps() functions to render it in SVG or EPS format and save the images on our disk:

#SVG
QR_code.svg("QR_code.svg", scale=8)

#EPS
QR_code.eps("QR_code.eps", scale=2)

We can also render the QR code in a PNG format if we install pypng, a Python module for saving and loading PNG images (pip install pypng):

#PNG
QR_code.png("QR_code.png", scale=6)

• Custom QR Code with PyQRCode

When it comes to creating QR codes, sometimes we might find ourself in a situation where we need more control over the final output. Fortunately, with pyqrcode.create() function, we can specify all the properties of our QR code.

import pyqrcode

advanced_QR_code = pyqrcode.create('Hello World!',
error='L',
version=27,
mode='binary')

In fact, there are three main properties that we can customize to achieve the desired result. By tweaking these parameters, we can create QR codes that fit our specific needs and use cases.

  • error : sets the error correction level of the QR code. The levels are associated with a letter: L (7%), M (15%), Q (25%) and H (30%). The default value for this parameter is ‘H’, which stands for the highest level of error correction. However, it’s worth noting that this level of error correction comes with a trade-off: it results in the smallest available data capacity for a given version of the QR code.
  • version: specifies the size and the data capacity of the QR code. The versions are associated with integer between 1 and 40. Version 1 being the smallest QR code, and version 40 being the largest. If you’re generating multiple QR codes with varying amounts of data, it might be useful to set this parameter for consistency. This way, all of the generated codes will have the same size, which can make it easier to use them together in a consistent and cohesive way.
  • mode : sets how the content will be encoded. It supports three techniques: numeric, alphanumeric, binary. By default, the object uses the most efficient encoding for the contents.

Now, let’s take a look at PyQRCode SVG, EPS, and PNG renderers. These renderers come with two parameters that allow you to modify the colors of the QR code. By adjusting these parameters, we can customize the look and feel of the QR code to better suit our needs and preferences:

advanced_QR_code.svg('qrcode.svg', scale=4, module_color="beige", background="cadetblue")

3. Generate QR Codes with the ‘segno’ library

segno is an awesome open-source QR code generator that allows us to create QR codes and micro QR codes without breaking a sweat.

But that’s not all, segno offers a wide range of customization options to make our QR codes stand out. We can make our QR codes truly unique by personalizing the colors, adding photos, embedding your contact information within the code, and even creating animated QR codes !

So, if we’re looking to create QR codes that truly represent our brand or personality, segno is definitely the way to go. It’s fun, easy to use, and offers a plethora of customization options that will take our QR codes to the next level!

We can use pip to install segno from PyPI:

pip install segno

We can also use the conda-forge:

conda install -c conda-forge segno

• Simple QR Code with segno

We can use the factory function segno.make_qr() to generate QR codes, and adjust their scale with the scale argument as follow:

import segno

QR_code = segno.make_qr("Hello World!")

Once we created our QR code, we have different options for saving it on your disk. With Segno, we have the freedom to save our QR codes in various file formats including .svg, .png, .eps, and .pdf. This means we can choose the format that works best for our needs, whether we want a high-quality vector image or a smaller file size for faster loading times.

#png
QR_code.save("QR_code.png", scale=10)

#svg
QR_code.save("QR_code.svg", scale=10)

#eps
QR_code.save("QR_code.eps", scale=10)

• Micro QR Code with segno

The Micro QR Code is a type of QR Code that was developed by a Japanese automotive supplier called Denso-Wave way back in 1994. It’s designed to take up less space than the traditional QR Code as it only needs one position indicator instead of multiple ones. It can only handle 35 characters. So, if we ever need to use a QR Code but have limited space to work with, the micro QR Code might be just the solution we need!

We can use the factory function segno.make_micro() to create micro QR codes. It will raise an error if the content is too large for a micro QR code (“DataOverflowError: Data too large”)

import segno

micro_QR_code = segno.make_micro("Hello World!")
micro_QR_code.save("micro_QR_code.png", scale=4)

Are you having trouble deciding whether to use a Micro QR Code or a regular QR Code? No worries! There’s actually a handy function called segno.make() that automatically chooses which type of code to generate based on the content you are trying to add. If the content to encode is small enough, a micro QR code is automatically generated.

import segno

QR_code = segno.make("Hello World!")
QR_code.is_micro

True

• QR Code for Wi-Fi Configuration with segno

Have you ever experienced the hassle of having your friends and family come over and ask for your Wi-Fi password? Even if you remember the long and complicated password, it’s not always easy for them to type it in manually. It can be such a frustrating process! But what if I told you that you could share your Wi-Fi with a QR code ? Yes, you heard that right.

Segno lets us create a QR code for Wi-Fi configuration with the helpers.make_wifi() function as follow:

from segno import helpers

qr_code_wifi = helpers.make_wifi(ssid='My network name', password='My network password', security='WPA')
qr_code_wifi.save('wifi-qr-code.png', scale=7)

• QR Code for Encoding Geographic Information with segno

Have you ever wanted to share a location with multiple people but found it too cumbersome to send it to them one by one? Well, all you need to do is create a QR code with geo-coordinates, and voila, you’re good to go.

segno allows us to create QR codes with geo-coordinates by using the helpers.make_geo(latitude, longitude)function as follow:

from segno import helpers

qrcode = helpers.make_geo(64.144769, -21.94096)
qrcode.save('location_wrcode.png', scale=7)

• QR Code for Encoding Contact Information with segno

Segno is amazing as it also gives us the ability to share all of our contact information in just one QR code. That means we can put our name, our phone numbers, our email addresses and our website URLs all in one convenient place.

The function helpers.make_mecard() allows us to do that as follow (the parameters email, phone and url accept multiple values):

from segno import helpers

qrcode_mecard = helpers.make_mecard(
name='Doe,John,Jr',
email=('me@example.org', 'another@example.org'),
url=['http://www.example.org', 'https://example.org/~joe'],
phone='+1234567'
)

qrcode_mecard.save('my-mecard.svg', scale=6)

• Custom QR Code with segno

If we want to customize the color of the dark and light modules of a QR code, segno has got us covered!

The following parameters of the save() function are the main parameters to customize the colors of our QR code:

  • dark: sets the (default) color of dark modules
  • light: sets the (default) color of light modules
  • data_dark: sets the color of the dark data modules
  • data_light: sets the color of the light data modules
import segno

qrcode = segno.make("Hello World")
qrcode.save('custom_qrcode.png', scale=6,
dark='darkred',
data_dark='darkorange',
light='lemonchiffon',
data_light='yellow')

Many other parameters are available to customize the colors of the QR code such as alignment_light, alignment_dark, finder_dark, finder_light . Take a look at segno documentation to learn more.

• Artistic QR Code with segno

Segno allows us to create artistic QR code with images, logos and gifs into the code itself. By using Segno, we can transform the typically mundane appearance of a QR code into a visually appealing work of art.

Advanced graphic operations require the qrcode-artistic plug-in, which in turn depends on the Pillow library. You can install it using PIP:

pip install qrcode-artistic
  • The first fun thing we can do is rotating the QR code using theto_pil().rotate() method:
import segno

qrcode = segno.make("Hello World!")
qrcode_rotated = qrcode.to_pil(scale=6).rotate(45, expand=True)
qrcode_rotated.save("qr_code_rotated.png")
  • The method to_artistic() can create animated QR codes. In the following example, we add a gif file as background to make an animated QR code:
import segno

qrcode = segno.make('The Beatles -- Albums')
qrcode.to_artistic(background='src/albums.gif', target='albums.gif', scale=8)
  • We can also add a background which comes from an URL. The link should be added as a file-like object as follow:
from urllib.request import urlopen
import segno

qrcode = segno.make('Ringo Starr', error='h')
url = 'https://media.giphy.com/media/HNo1tVKdFaoco/giphy.gif'
bg_file = urlopen(url)
qrcode.to_artistic(background=bg_file, target='ringo.gif', scale=10)

Conclusion

In conclusion, creating QR codes in Python is a straightforward process that can be accomplished using the libraries qrcode, PyQRcode, and segno. With these libraries, you can create simple, custom, and even artistic QR codes with a variety of options for customization, including size, color, shape, and image background. Whether you’re creating QR codes for personal or professional use, Python provides a powerful and flexible toolset for generating these essential, scannable codes. So why not give it a try and see what kind of creative QR codes you can come up with using Python?

--

--