QR Code Generation with Python
To generate a QR code in Python, you can use the qrcode library.
Steps to Generate a QR Code with qrcode
1. Install the qrcode
Library
To get started, we need to install the qrcode library. If you don’t have it installed yet, you can easily do so using pip
.
We’ll also install the pillow library, which is used for working with images.
Open your terminal and run:
pip install qrcode[pil]
2. Python Code to Generate a QR Code
Now, let’s create a Python script to generate a QR code.
import qrcode
# Data for the QR code
data = "https://www.djc.pe/" # Link or text you want to encode
# Create the QR object
qr = qrcode.QRCode(
version=1, # Controls the size of the QR (1 to 40)
error_correction=qrcode.constants.ERROR_CORRECT_L, # Error correction level
box_size=10, # Size of each square in the QR code
border=4, # Border thickness
)
qr.add_data(data)
qr.make(fit=True)
# Create the QR image
img = qr.make_image(fill_color="black", back_color="white")
# Save the image
img.save("codigo_qr.png")
print("QR code generated and saved as 'codigo_qr.png'!")
Code Explanation
- Data to encode: In the
data
variable, we place the URL or text we want to encode. You can change this to any other data. - Create the QR object: We use
qrcode.QRCode()
to create a QR object. Parameters likeversion
,error_correction
,box_size
, andborder
allow us to customize the size, error correction level, and appearance of the QR code. - Add the data: The
add_data()
method is where we add the information to be encoded. Themake(fit=True)
method adjusts the QR code according to the provided data. - Generate the image: We use
make_image()
to create the QR code image. Here, you can specify the QR colors (fill
for the squares,back_color
for the background). - Save and display the image: Finally, the image is saved with
img.save("codigo_qr.png")
and displayed usingimg.show()
.
QR Code Customization
- Size: The
version
parameter determines the size of the QR code. The larger the value, the bigger the code. Valid values range from 1 to 40. -
Error correction: The error correction level can be adjusted with the
error_correction
parameter. Available levels are: -
ERROR_CORRECT_L
: 7% error correction ERROR_CORRECT_M
: 15% error correctionERROR_CORRECT_Q
: 25% error correctionERROR_CORRECT_H
: 30% error correction- Colors: You can customize the QR code colors using the
fill
parameter for the squares and theback_color
parameter for the background.