Post

Generate a QR Code for URL

Generate a QR Code for URL using Python

QR Code generation Library

In this post, I will show you how to generate a QR Code for a URL using Python. We will use the qrcode library to generate the QR Code.

Prepare the workspace

Create a new folder in your workspace and navigate to it using the following commands:

1
2
mkdir generate_qr_code
cd generate_qr_code

Create a Virtual Environment

Create a new virtual environment using the following command:

1
python -m venv venv

Activate the virtual environment using the following command:

1
source venv/bin/activate

Install qrcode library

Install the qrcode library using the following command:

1
2
pip install qrcode
pip install pillow

Generate a QR Code for URL

Create a new Python script generate_qr_code.py and add the following code to generate a QR Code for a URL:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import qrcode
import sys

def generate_qr_code(url, filename):
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    qr.add_data(url)
    qr.make(fit=True)

    img = qr.make_image(fill_color="black", back_color="white")
    img.save(filename)

if __name__ == '__main__':
  # Read the url from CLI arguments and generate the QR Code
  url = sys.argv[1]
  filename = sys.argv[2]

  # validate the url before generating the QR Code
  if not url.startswith('http://') and not url.startswith('https://'):
    print('Invalid URL. Please provide a valid URL starting with http:// or https://')
    sys.exit(1)

  generate_qr_code(url, filename)

You can find the source code at generate_qr_code.py

Run the Python script

Run the Python script using the following command:

1
python generate_qr_code.py https://www.google.com google_qr_code.png
This post is licensed under CC BY 4.0 by the author.