Python Program to Generate QR Code Easily
qrcode library in Python to generate a QR code by calling qrcode.make('your text') and saving it as an image with .save('filename.png').Examples
How to Think About It
Algorithm
Code
import qrcode # Data to encode data = "https://www.example.com" # Generate QR code img = qrcode.make(data) # Save as PNG file img.save("qrcode.png") print("QR code generated and saved as qrcode.png")
Dry Run
Let's trace generating a QR code for 'https://www.example.com' through the code
Import qrcode library
The program loads the qrcode module to access QR code functions.
Set data to encode
The variable data is set to 'https://www.example.com'.
Generate QR code image
qrcode.make(data) creates an image object representing the QR code.
Save image to file
The image is saved as 'qrcode.png' on disk.
Print confirmation
The program prints 'QR code generated and saved as qrcode.png'.
| Step | Action | Value |
|---|---|---|
| 1 | Import qrcode | qrcode module loaded |
| 2 | Set data | 'https://www.example.com' |
| 3 | Generate QR code | Image object created |
| 4 | Save image | 'qrcode.png' file created |
| 5 | Print message | QR code generated and saved as qrcode.png |
Why This Works
Step 1: Importing the library
The qrcode library provides easy functions to create QR codes from text.
Step 2: Creating the QR code
Calling qrcode.make(data) converts the text into a QR code image object.
Step 3: Saving the image
The image object has a .save() method to write the QR code as a PNG file.
Alternative Approaches
import qrcode qr = qrcode.QRCode(version=1, box_size=10, border=4) qr.add_data('Hello QR') qr.make(fit=True) img = qr.make_image(fill_color='black', back_color='white') img.save('custom_qrcode.png') print('Custom QR code saved as custom_qrcode.png')
import segno qr = segno.make('https://www.example.com') qr.save('segno_qrcode.png') print('QR code generated with segno and saved as segno_qrcode.png')
Complexity: O(n) time, O(n) space
Time Complexity
The time depends on the length of the input text n, as encoding longer data takes more processing.
Space Complexity
The space used is proportional to the size of the QR code image generated, which depends on the data length.
Which Approach is Fastest?
Using qrcode.make() is simple and fast for most uses; the QRCode class offers more control but is slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| qrcode.make() | O(n) | O(n) | Quick and simple QR code generation |
| qrcode.QRCode class | O(n) | O(n) | Customizable QR codes with size and color options |
| segno library | O(n) | O(n) | Lightweight alternative with fast generation |
pip install qrcode[pil] to handle images.