The best way to Generate QR Codes in Python

-

to QR Codes

“QR” in QR code stands for quick response. QR codes are an emerging and straightforward strategy to retrieve information without typing or searching anything in your phone. These codes are essentially a pattern of black and white squares, with scannable digital codes embedded in them. Nowadays, restaurants use these QR Codes to present the menu to their customers, shops and marts use them as a type of contactless digital payments, event management teams use them as a fast check-in to their events and conferences, and so forth and so forth.

Generating QR Codes

As was mentioned earlier, QR Codes are developed as a pattern or a grid of small black and white squares that store information in binary form, that’s, as 0s and 1s. Information is encoded throughout the code in special arrangements with the feature of customizing the colours, background, and frames, so long as the pattern stays the identical.

The next is an example of a QR code that has been generated using the Python “qrcode” package:

Link to my TDS Writer Profile (Image by Writer)

Scanning the above code with a scanner that has QR code scanning capabilities will take you to my TDS profile, where you’ll be able to easily access beginner-friendly Python projects.

In this text, we are going to undergo the Python Package qrcode, installing it and exploring its different functions to design QR Codes.

Installing the Package

Before starting the project, we are going to install the relevant packages. I’m using PyCharm IDE for this task. With the intention to install the “qrcode” Python package, I’ll go to the Python terminal and kind the next:

pip install qrcode
Installing the qrcode Package (Image by Writer)

Installing the QRCode package will allow us to create QR codes as PNG files and render them into the Python console. Nevertheless, if we require more image-related functionality, we should always install the Pillow package for image processing capabilities.

pip install "qrcode[pil]"
Installing the QRCode package with Pillow (Image by Writer)

Importing Library and Generating a Easy QR Code

Now we are going to begin the coding. First, we are going to import the library and include an alias name for our ease. As might be seen within the QR Code Python documentation, the QR Code image for a URL can easily be generated and saved as a PNG using the next lines of code:

import qrcode as qr
img = qr.make("https://pypi.org/project/qrcode/")
img.save("Python QR Code Documentaion.png")
Python QR Code Documentation (Image by Writer)

This is a straightforward QR code that has been created using the make() function and saved as a PNG file using the save() function.

Advanced Functionality

For advanced image processing features, we are going to use the QRCode Class within the qrcode Python Package.

Classes and Objects are a useful concept in programming. Python classes provide a blueprint for the creation of objects that share similar features, their attributes (variables), and methods (functions). We’ll use the Python Class constructor to create QR codes as objects of that class.

Below is the generic code that enables us to create and save QR codes:

import qrcode
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)
qr.add_data('https://towardsdatascience.com/implementing-the-coffee-machine-project-in-python-using-object-oriented-programming/')
qr.make(fit=True)

img = qr.make_image(fill_color="black", back_color="white")
img.save("Understanding Classes and Objects.png")
Understanding Classes and Objects in Python (Image by Writer)

The above code has created and saved the QR code as a PNG. If you happen to scan the above code, you’ll land on an interesting Python Tutorial that explores how the concept of Python classes and objects is implemented in real-world projects.

Now, allow us to deep dive into the generic code above and explore the functions and play together with their variations.

Object Creation

The primary line of code after importing the qrcode library creates the item, with its attributes and methods enclosed throughout the round brackets.

qr = qrcode.QRCode(
    ...
    ...
    ...
    ...
    ...
)

Here, qrcode refers back to the Python package and QRCode() refers back to the Class.

Defining the Version

Next is to define the version. We are able to set the integer from 1 to 40, and it will result in several sizes of the QR Code.

import qrcode
qr = qrcode.QRCode(
    version=1,
    ...
    ...
    ...
    ...
)

Let’s create a QR Code with the version variable set to five.

Version Attribute set to five (Image by Writer)

Now allow us to set the version parameter to fifteen:

Version Attribute set to fifteen (Image by Writer)

As might be seen within the two QR Codes above, the version attribute determines the scale of the QR Code. The smallest version 1 outputs a QR Code as a 21×21 grid.

Error Correction

The subsequent attribute that we’ll undergo is error_correction. The Error Correction attribute deals with the information redundancy, in order that even when the QR Code is broken, it still stays scannable. There are 4 different levels of error_correction:

  • Error Correct L: This provides the bottom level of error correction, that’s 7%
  • Error Correct M: This provides a moderate level of knowledge correction, 15% or less, thus providing a balance between error correction and data size
  • Error Correct Q: This provides 25% or less of error correction
  • Error Correct H: This provides a high level of error correction and is suitable for applications which will have serious damage, and where data size will not be a priority.
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    ...
    ...
)

The more the proportion value of error_correction, the more easily it becomes scannable, even when parts of it are damaged. On the flip side, the QR Codes change into larger in size, and this poses an issue when data compression is a foremost requirement.

Allow us to create QR Codes with different error_correction types.

Error Correction Type L (Image by Writer)
Error Correction Type M (Image by Writer)
Error Correction Type Q (Image by Writer)
Error Correction Type H (Image by Writer)

As might be seen from the range of the QR Codes generated above, because the error_correction increases, the complexity of the QR Codes increases, meaning the information size increases, while the information redundancy also increases.

Box Size

The subsequent attribute we are going to explore and play with is the box_size. The box_size within the Python qrcode library refers back to the variety of pixels the QR Code could have.

qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    ...
)

Allow us to see how our QR Code changes with different values of the box_size:

Box Size = 1 (Image by Writer)
Box Size = 100 (Image by Writer)
Variation of box_size (Image by Writer)

The above images show the difference when the pixel values changes, although they could be negligible to the naked eye in terms of small differences.

Border

The last attribute that we want to define to create the item is the border. This refers to the encircling box across the code. The minimum value is 4, and we will increase it as much as we like. Allow us to see how the code changes with changes on this attribute:

Border = 4 (Image by Writer)
Border = 10 (Image by Writer)

We are able to see the difference within the border of the above images, which might easily be customised with the border variable.

Adding Data

Once our object has been created, with particular values of version, error_correction type, box_size and border, we are going to now add the information that should be encoded as QR Code. This data is usually a string, a URL, a location, contact information, etc. This might be easily done through the add_data() approach to this class.

import qrcode
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=1,
    border=10,
)
qr.add_data('https://towardsdatascience.com/building-a-facial-recognition-model-using-pca-svm-algorithms-c81d870add16/')
qr.make(fit=True)

The last line of code above calls qr.make(fit=True). This robotically suits the QR Code to the information that has been given, after analyzing it. It uses the smallest possible QR Code to accommodate the information, and doesn’t require us to manually set the sizing attributes.

Generating the Image Object

Once the QR Code object is created, we are going to use PIL to generate the image while defining its colours, in addition to saving that image in an acceptable way. In the next example, we are going to set the background to black and fill color to pink in our QR Code, as might be seen within the code below:

import qrcode
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=1,
    border=10,
)
qr.add_data('https://towardsdatascience.com/using-python-to-build-a-calculator/')
qr.make(fit=True)

img = qr.make_image(fill_color="pink", back_color="black")
img.save("calc.png")
Color Setting for QR Code (Imae by Writer)

Conclusion

In this text, we explored the Python package QR Code, which incorporates the blueprint for creating QR codes and saving them in several file formats. It also includes advanced customisation of the QR code generation, which now we have undergone with the understanding of classes and objects. This was a straightforward and beginner-friendly Python Tutorial that required some surface-level knowledge of classes and objects.

ASK ANA

What are your thoughts on this topic?
Let us know in the comments below.

0 0 votes
Article Rating
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Share this article

Recent posts

0
Would love your thoughts, please comment.x
()
x