Master QR Code Creation and Customization with Python

harikrishnan1077264 Last Updated : 19 Nov, 2024
8 min read

QR codes can be seen everywhere . Especially on restaurants , petrol pumps , shops mainly for making payments. There are multiple other applications also. The main reason is it is an easy way to store information in the form of a small, easy-to-scan image . In this guide, I will help you mastering QR codes and how QR codes work and walk you through creating them using python.

Learning Outcomes

  • Understand the fundamentals of QR codes and their functionality.
  • Mastering QR Codes enables you to efficiently create, customize, and apply QR codes in various real-world scenarios using Python.
  • Learn how to generate and customize QR codes using Python.
  • Explore the history and advantages of QR codes in various applications.
  • Gain hands-on experience by creating a Wi-Fi QR code for easy network access.
  • Discover real-world uses for QR codes, including in public spaces and businesses.

This article was published as a part of the Data Science Blogathon.

What are QR Codes?

Quick Response(QR) codes are actually two-dimensional matrix barcode that can store various types of data, such as URLs, text, contact information, or Wi-Fi credentials .Quick Response indicating that The code contents should be decoded very quickly at high speed .Usually the code consists of black modules arranged in a square pattern on a white background. Unlike traditional barcodes, which only hold information in one direction (horizontally). QR codes can store data both horizontally and vertically. Allowing for much greater storage capacity.

History of QR Codes

It was invented by Denso Wave in 1994 for Toyota Group .The purpose was to track automotive parts during manufacturing. Their ability was to store a significant amount of data and can be scanned quickly made them popular in various industries over time.

Why Use QR Codes?

QR codes have several advantages:

  • Easy to Use : It can be scanned with a smartphone camera or a dedicated QR scanner.
  • Versatile : can store different types of data, including URLs, text, and more.
  • Fast Access : quickly provides information with just a scan.
  • Contactless : useful for contactless transactions and sharing.

QR Codes with Python

In this section, I will explain how to generate QR codes using python. We will cover different examples to demonstrate the process.Starting from creating a simple QR code to customizing it further. We’ll use the qrcode library, which provides a straightforward way to create QR codes. To begin, make sure you have the library installed:

pip install qrcode[pil]

Example1 : Generating a Simple QR Code

In this first example, create a basic QR code with default settings. Here’s the code:

import qrcode
from PIL import Image

#Data to be encoded
data = "Welcome to QR Code Tutorial"

#Create a QR code object
qr = qrcode.QRCode(
    version=1,    # Size of the QR code
    box_size=10,  # Size of each box in the QR code grid
    border=4      # Border thickness
)
qr.add_data(data)
qr.make(fit=True)

#Generate QR code image
img = qr.make_image(fill='black', back_color='white')
img.show()
img.save('simple_qr_code.png')

Here’s a explanation for the parameters used in the code:

  • version: It will controls the code’s complexity and size.
  • box_size: size of each box in the QR code.
  • border: the thickness of the outer white space.

The above code will generate a simple QR code encoding the text “Welcome to QR Code Tutorial.” The following will be the result ,simply scan the code to view the output.

QR code1

Example2: Generating a QR Code with Custom Colors

Here  what we are doing is make the  QR code more visually appealing.Inorder to attain this we have to either change foreground color or background color or change both.In this example i hvae changed both foreground and background colors.You can tryout the code with different color combinations.

import qrcode
from PIL import Image

#Data to be encoded
data = "Welcome to QR Code Tutorial"

#Create a QR code object
qr = qrcode.QRCode(
    version=1,    # Size of the QR code
    box_size=10,  # Size of each box in the QR code grid
    border=4      # Border thickness
)
qr.add_data(data)
qr.make(fit=True)

#Create a QR code with custom colors
img_colored = qr.make_image(fill_color='darkgreen', back_color='lightyellow')
img_colored.show()
img_colored.save('custom_color_qr_code.png')

The above code will generate a QR  code with a dark green foreground and light yellow background. Scan the code to view the output with these custom colors.

Mastering QR code

Example3: QR Code Generation from Analytics Vidhya URL

In this example, creating a QR code that encodes the URL of Analytics Vidhya. This allows anyone who scans the code to directly visit the website. Here’s the code:

import qrcode
from PIL import Image

#Create the QR code as usual
qr = qrcode.QRCode(
    version=5,    # Version adjusted to include the logo
    box_size=10,
    border=4
)
qr.add_data("https://www.analyticsvidhya.com/")
qr.make(fit=True)

#Generate the QR code image
img = qr.make_image(fill='black', back_color='white')

#Save and show the result
img.save('QR_code_AnalyticsVidhya.png')
img.show()

Just scan it. The QR will direct you towards official page of Analytics Vidhya

QR code Generation

Example4: QR Code with Embedded Logo and URL Combined

Here we will tryout a personalized QR code that not only links to the Analytics Vidhya website but also features a custom logo embedded right in the center.It can give  a distinctive and branded appearance. Let’s dive into the code example 

import qrcode
from PIL import Image

# Create the QR code as usual
qr = qrcode.QRCode(
    version=5,  # Version adjusted to include a logo
    box_size=10,
    border=4
)
qr.add_data("https://www.analyticsvidhya.com/")
qr.make(fit=True)

# Generate the QR code image
img = qr.make_image(fill='black', back_color='white')

# Open the logo image
logo = Image.open('AV_logo.png')

# Calculate the size for the logo
logo_size = 100  # Set this according to your needs
logo = logo.resize((logo_size, logo_size), Image.Resampling.LANCZOS)  # Use LANCZOS for high-quality downsampling

# Paste the logo onto the QR code
pos = ((img.size[0] - logo_size) // 2, (img.size[1] - logo_size) // 2)
img.paste(logo, pos, mask=logo)

# Save and show the result
img.save('QR_code_with_AnalyticsVidhya_Logo.png')
img.show()

The following cropped image is an example that you can try with your code:

AV Logo

This version of code adds a touch of excitement and emphasizes the unique, branded aspect of the QR code.

Mastering QR Code: AV

Example5: Reading QR Codes from an Image

Here, I will show how to read and decode a QR code from an image using OpenCV. This is useful when you need to extract data from a QR code that’s already been created or shared in an image file. Here’s the code:Just take the previous output QR Code image as new input,then try out the following code

# !pip install opencv-python
import cv2

# Read the image file
image = cv2.imread('/home/Tutorials/Analytics Vidya/QR_code_with_AnalyticsVidhya_Logo.png')

# Initialize the QR code detector
detector = cv2.QRCodeDetector()

# Detect and decode the QR code
data, vertices_array, _ = detector.detectAndDecode(image)

if vertices_array is not None:
    print(f"Decoded Data: {data}")
else:
    print("QR code not detected.")

The output will be:

"   Decoded Data: https://www.analyticsvidhya.com/   "

Mini-Project : Creating a Wi-Fi QR Code

QR code is a easy way to allow users to connect with a network. By just scanning the code. Using this we can avoid manually typing wifi name or password . We can implement a qr code that contains all the necessary information.

In this mini project ,I will guide you  to build a QR code to store wifi details.It can be much useful in public places, offices as well as for personal use.The generated qr code will store wifi credentials, such as the network name (SSID), password, and security type (in my case WPA2) ,allowing devices to connect with ease.

Inorder to tryout this mini project,1st you have to findout your Wi-Fi SSID,Wi-Fi Security Type and Password using following linux commands in the terminal.Remember , try one after another

#1 Find the Wi-Fi SSID (Network Name)
nmcli -t -f active,ssid dev wifi | grep '^yes'

#2 Get Wi-Fi Security Type
# here my SSID Name is RAGAI_4G

nmcli -f ssid,security dev wifi | grep "RAGAI_4G" 

#3Get Password
sudo grep -r "psk=" /etc/NetworkManager/system-connections/

Code Implementation

Let us now implement the code below:

# Import the necessary library
import qrcode

# Define Wi-Fi credentials
wifi_ssid = "RAGAI_4G"#replace with your SSID Name
wifi_password = "PASSWORD" #Ur PASSWORD
wifi_security = "WPA2"  # Can be 'WEP', 'WPA', or 'nopass' (no password)

# Create the QR code data in the format that encodes Wi-Fi information
wifi_data = f"WIFI:T:{wifi_security};S:{wifi_ssid};P:{wifi_password};;"

# Create a QR code object with desired settings
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4
)

# Add the Wi-Fi data to the QR code object
qr.add_data(wifi_data)
qr.make(fit=True)

# Generate the QR code image
img = qr.make_image(fill='black', back_color='white')

# Save the QR code image to a file
img.save('wifi_qr_code.png')

# Display the QR code image (for testing)
img.show()

print("Wi-Fi QR code saved successfully")

Scanning the QR Code

Expecting you have successfully tried out the code i have shared.Now  you have the output QR code image.Just can scan it with a smartphone or scanner to connect to the wifi network. Follow the steps one by one:

  • Open the camera app or QR scanner on your phone.
  • Point the camera at the QR code.
  • Android phones will display the Wi-Fi network name and prompt to connect automatically.

Remember ,if your phone doesnot have inbuilt applications,you can download any scanner applications from playstore.

Practical Use Cases for QR Codes

This Wi-Fi QR code can be especially helpful in:

  • Public Spaces: In cafes, libraries,pumps or hotels where visitors can simply scan the code to connect without needing to ask for the credentials.
  • Home Networks: Giving friends and family an easy way to connect to your network without sharing your password.
  • Business Settings: Sharing network access with guests or employees without compromising security.

Conclusion

The examples in this article  can help you  for various purposes and both in your hobby projects and real time projects.If any functions occur in your home you can invite your friends by saring the location information with the help of a qr code.If you are at office or school the same can be utilized for event scheduling and form filling.

Here is the Github link.

Key Takeaways

  • QR codes are versatile tools that store various data types, from URLs to Wi-Fi credentials.
  • Python’s qrcode library simplifies the process of creating and customizing QR codes.
  • QR codes enhance user experience by enabling fast, contactless information sharing.
  • Customizing QR codes with colors or logos can improve branding and visual appeal.
  • Wi-Fi QR codes provide a seamless way to connect devices to a network without manual entry.
  • Mastering QR Codes unlocks the potential to streamline data sharing, enhance user experiences, and improve access to information quickly and effectively.

Frequently Asked Questions

Q1. What is a QR code?

A. A QR code is a two-dimensional barcode that stores information such as URLs, text, or Wi-Fi credentials, and can be scanned quickly by a camera or scanner.

Q2. How do I generate a QR code using Python?

A. You can use the qrcode library in Python to generate QR codes by installing it with pip install qrcode[pil] and creating a QR code object with your data.

Q3. Can I customize the appearance of a QR code?

A. Yes, you can change the foreground and background colors, and even embed logos within the QR code for a more personalized look.

Q4. What is a Wi-Fi QR code?

A. A Wi-Fi QR code stores network credentials (SSID, password, and security type) so users can connect to a network by simply scanning the code.

Q5. Can QR codes be used for purposes other than payment?

A. Yes, QR codes serve various applications, such as sharing URLs, contact information, event details, and even Wi-Fi credentials.

Q6. What is the significance of mastering QR codes?

A. Mastering QR codes allows you to easily create and customize codes for various purposes, such as sharing URLs, Wi-Fi credentials, and more, enhancing convenience and accessibility in digital interactions.

The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.

Responses From Readers

Clear

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details