QR Codes are two-dimensional codes that can contain information such as URLs, text, phone numbers, and much more. In this article, we’ll see how to generate them easily using Python.
Requirements
To generate a QR Code in Python, we’ll use the qrcode
library. You can install it with the pip
package manager:
pip install qrcode[pil]
This command also installs image support via the Pillow
library.
Generating a Basic QR Code
The following example shows how to generate a QR Code containing a simple URL:
import qrcode
# Data to encode
data = "https://www.example.com"
# Create the QR Code object
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
# Add data
qr.add_data(data)
qr.make(fit=True)
# Create the image
img = qr.make_image(fill_color="black", back_color="white")
# Save to file
img.save("qrcode.png")
Generating a Simplified QR Code
For simple cases, you can use the qrcode.make()
function, which automates many steps:
import qrcode
img = qrcode.make("https://www.example.com")
img.save("qrcode_simple.png")
Customizations
You can customize the QR Code by changing the color, size, and error correction level parameters. Here’s an example with custom colors:
img = qr.make_image(fill_color="blue", back_color="white")
img.save("qrcode_colored.png")
Conclusions
With just a few simple steps, Python makes it easy to generate QR Codes for many different applications. The qrcode
library is flexible and easy to use, perfect for both quick solutions and more advanced use cases.