Define data to encode
QR codes have become ubiquitous in our daily lives. These scannable square barcodes can be found everywhere from product packaging to restaurant menus to advertising billboards. With just a quick scan using your smartphone camera, a QR code can instantly take you to a website, provide contact details, open an app, or reveal a hidden message.
As a Python developer, did you know you can easily generate your own custom QR codes with just a few lines of code? In this comprehensive tutorial, we‘ll walk through exactly how to create QR codes in Python step-by-step. Whether you want to create QR codes for your personal projects or business needs, Python provides a quick and flexible way to generate them programmatically.
What are QR Codes?
Before we dive into the code, let‘s start with the basics. QR stands for "Quick Response". A QR code is a two-dimensional barcode that consists of black square dots arranged in a square grid on a white background. Unlike standard barcodes that you might find on a product‘s UPC label which can only be read in one direction, a QR code can be scanned both vertically and horizontally to retrieve information.
QR codes can store up to 4296 characters of alphanumeric data. When scanned with a QR code reader (which is built into most modern smartphone cameras), this data is rapidly decoded and typically launches an action such as opening a website URL, adding contact details, connecting to a WiFi network, opening an app, or revealing a text message.
The structure of a QR code includes these key elements:
-
Finder Pattern – The large square marks in three corners that enable the scanner to locate and orient the code.
-
Alignment Pattern – A smaller square used in larger QR codes for orientation.
-
Timing Pattern – An L-shaped line between the finder patterns used to determine the size of the data matrix.
-
Version Information – Info about the QR code version used.
-
Format Information – Decoding details such as error correction level and mask pattern.
-
Data – The actual encoded data which can include numeric, alphanumeric, or binary content. Error correction bits are also included to restore data if the code is damaged.
-
Quiet Zone – The white border around the QR code which should be at least 4 cells wide.
Benefits and Common Uses of QR Codes
So why use QR codes rather than a plain text URL or contact details? QR codes provide several key benefits:
-
Speed – QR codes can be scanned and decoded very quickly compared to manually typing in a URL or contact info.
-
Accuracy – QR code data is less prone to errors from manual data entry.
-
Versatility – QR codes can trigger many different actions and store various data types.
-
Trackability – Dynamic QR codes can track scanning metrics for marketing insights.
-
Contactless – QR codes are ideal for contactless transactions and information exchange.
Some of the most common use cases for QR codes include:
- Website URLs
- vCards and contact info
- WiFi access credentials
- App store links
- Digital coupons and discounts
- Social media profile links
- Event tickets and registrations
- Digital business cards
- Product tracking and authentication
The possibilities are nearly endless. Any time you need to provide quick access to data from a printed or on-screen format, a QR code is worth considering.
Creating QR Codes with Python
Now that we understand what QR codes are and why they are useful, let‘s see how we can create them using Python. We‘ll use two main Python libraries:
qrcode– for generating the QR code itselfPillow(Python Imaging Library) – for saving the QR codes as image files
First, make sure you have the latest versions of both libraries installed. You can install them using pip:
pip install qrcode Pillow
We‘ll start by creating a basic QR code with minimal customization:
import qrcode
data = "https://www.example.com"
qr = qrcode.QRCode()
qr.add_data(data)
qr.make(fit=True)
qr_img = qr.make_image(fill_color="black",
back_color="white")
qr_img.save("qr_code.png")
This code does the following:
-
Imports the qrcode library.
-
Defines a string variable called
datawith the information you want to encode. Here we‘re using a website URL but it could be anything. -
Creates an instance of the
QRCodeclass. -
Adds the data to the QR code instance using
add_data(). -
Generates the QR code matrix using
make()with thefitparameter set toTrue. This ensures the entire data will fit in the QR code. -
Creates a PIL (Python Imaging Library) image from the QR code instance using
make_image(). You can specify the foreground and background colors here. -
Saves the image as a PNG file named "qr_code.png" using
save().
That‘s it! With just those few lines of code, you will have generated a QR code for the specified data. You can now use this QR code image anywhere you‘d like – print it out, embed it on a website, place it in an ad, etc.
Customizing Your QR Code Design
While the default QR code design gets the job done, you may want to customize the appearance for your particular use case. The qrcode library provides options to change the error correction level, size, border, and colors.
Here‘s how you can tweak the code to set some of these parameters:
import qrcode
data = "https://www.example.com"
qr = qrcode.QRCode(
version=None,
error_correction=qrcode.constants.ERROR_CORRECT_M,
box_size=15,
border=4
)
qr.add_data(data)
qr.make(fit=True)
qr_img = qr.make_image(fill_color="blue",
back_color="yellow")
qr_img.save("custom_qr_code.png")
The key differences here:
-
We set the error correction level to medium (ERROR_CORRECT_M) using the qrcode constants. Valid values are ERROR_CORRECT_L, ERROR_CORRECT_M, ERROR_CORRECT_Q, ERROR_CORRECT_H for 7%, 15%, 25%, and 30% correction respectively.
-
The box_size parameter controls how many pixels each box of the QR code matrix is. The default is 10 pixels per box.
-
The border parameter sets how many boxes thick the border should be. The default is a border of 4 boxes.
-
We changed the foreground and background fill colors to blue and yellow just as an example. You can use any valid color strings or hex values here.
Play around with these settings to see how they impact the generated QR code appearance. Keep in mind that increasing the error correction or decreasing the box size will result in a more dense code that may be harder to scan. Always test your codes with multiple QR code scanning apps.
Decoding QR Codes
In addition to creating QR codes, Python can also decode them. The pyzbar library, a Python wrapper for the ZBar library, makes it easy to scan and decode QR codes from image files or a live camera stream.
To read a QR code from an image file:
from pyzbar import pyzbar
from PIL import Image
qr_img = Image.open("qr_code.png")
decoded_objs = pyzbar.decode(qr_img)
for obj in decoded_objs:
print(obj.data.decode())
This code does the following:
-
Imports the pyzbar and PIL Image modules.
-
Loads the QR code PNG image using PIL.
-
Decodes the image data using pyzbar‘s decode() function. This returns a list of decoded objects.
-
Prints the decoded data string for each decoded object. The raw bytes are decoded into a string.
If you have multiple QR codes in a single image, the decode() function will find and decode them all. The decoded results will be returned in the order the codes were detected.
To experiment further, try generating a QR code image, then use this decoding script to read and print its data.
Creating Dynamic QR Codes for URLs
While embedding static data in a QR code is useful, sometimes you may want to encode a URL that redirects to content that changes. For example, maybe you want to use a QR code to link to your most recent blog post. Rather than generating a new QR code each time the URL changes, you can create a dynamic QR code that always points to your latest content.
The key is to generate a QR code that links to a redirect URL you control. Your server can handle the redirect logic to send users to the appropriate destination URL.
Here‘s an example of how you could implement this in Python using the Flask web framework:
from flask import Flask, redirect
app = Flask(name)
url_map = {
"latest_post": "https://www.example.com/latest",
"featured_product": "https://www.example.com/product/featured"
}
@app.route("/qr/
if name == "main":
app.run()
To use this:
-
Generate a QR code encoding a URL like "http://yourdomain.com/qr/latest_post"
-
When that QR code is scanned, it will send a GET request to the /qr/latest_post route of your Flask app.
-
The app looks up the "latest_post" label in the url_map dictionary to get the corresponding URL string.
-
The app returns a HTTP 302 redirect to the client, sending them to the actual content URL.
-
You can update the url_map dictionary to change the redirect URLs without needing to change the QR code.
This approach gives you the flexibility to create "permanent" QR codes that link to resources that may change over time. It requires a bit more infrastructure than a static QR code, but offers a more dynamic solution.
Best Practices for QR Code Creation
When generating QR codes for public use, keep these tips in mind:
-
Test, test, test. Always verify your QR codes scan successfully on a variety of devices and scanning apps before publishing. Low contrast colors, dense codes, or blurry printing can cause scanning failures.
-
Include error correction. Adding at least 15-20% error correction bits will help your QR code still scan even if it gets smudged or torn.
-
Provide adequate quiet zone. Don‘t crowd the QR code. Give it ample white space so scanners can easily detect the edges.
-
Link to mobile-friendly content. Since most QR codes are scanned on smartphones, make sure the encoded URLs direct to mobile-optimized sites.
-
Offer value. Give users a compelling reason to scan your code, whether that‘s accessing exclusive content, claiming a discount, or learning more info.
-
Include a call-to-action. Printing a simple "Scan me!" next to the QR code provides a clear prompt for less tech-savvy users who may not be familiar with QR codes.
-
Track scans. If you‘re using QR codes for marketing, consider creating unique codes for different placements so you can measure which ones get the most engagement. Beware of shortened "tracking" links that may trigger security warnings though.
The Future of QR Codes
While QR codes may have seemed like a passing fad a few years ago, the technology has proven its staying power. The widespread adoption of QR code scanning capabilities in smartphone cameras and the sudden demand for contactless interactions due to COVID-19 have given QR codes new life.
As we move toward a more touchless, mobile-centric world, expect to see QR codes become even more common for payments, information access, ticketing, and more. With our Python skills, we have the power to create and deploy QR code solutions for all sorts of innovative use cases.
Some exciting QR code developments to watch include:
-
Payments – Apps like PayPal and Venmo now let you pay or request funds via QR code. Some countries like China have already adopted QR code payments as the norm.
-
Augmented Reality – QR codes can trigger interactive 3D content within a mobile AR experience, bringing print to life.
-
Authentication – Secure QR code-based authentication methods are being explored as alternatives to easily phished password logins.
-
Geolocation – QR codes can be used to encode location data, enabling features like location-aware special offers and content recommendations.
With a little creativity and coding, who knows what new QR-powered experiences Python developers will bring us in the years to come. The humble QR code is here to stay, and Python gives us the tools to unlock its full potential.