October 13, 2024

Generating a QR Code using Python

QR codes are widely used for storing and sharing information. In Python, you can generate QR codes using the qrcode library. Below, you’ll find a step-by-step guide on how to install the library and create a QR code.

1. Install the `qrcode` Library

First, you need to install the qrcode library and the Pillow library (which qrcode uses for image processing). You can install these libraries using pip:

pip install qrcode[pil]

2. Generate a QR Code

Once the libraries are installed, you can use the following code to generate a QR code:

import qrcode

# Data to encode
data = "https://www.example.com"

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

# Add data to the QR code
qr.add_data(data)
qr.make(fit=True)

# Create an image from the QR code instance
img = qr.make_image(fill='black', back_color='white')

# Save the image
img.save("qrcode_example.png")

# Optionally, display the image
img.show()
    

3. Explanation

  • qrcode.QRCode(): Creates a new QR code instance with parameters such as version, error correction level, box size, and border size.
  • add_data(data): Adds the data that will be encoded in the QR code.
  • make(fit=True): Generates the QR code with the specified data and settings.
  • make_image(): Creates an image from the QR code. You can specify colors for the QR code foreground and background.
  • save(): Saves the generated QR code image to a file.
  • show(): Opens the QR code image in the default image viewer (optional).

4. Conclusion

Generating QR codes in Python is straightforward using the qrcode library. This tool allows you to create QR codes for URLs, text, and other types of data, making it useful for various applications such as links, contact information, and more.