DEV Community

Cover image for Python - Read and Generate Qrcodes Under 10 Lines.
Pratik Mishra
Pratik Mishra

Posted on

2 2

Python - Read and Generate Qrcodes Under 10 Lines.

Let's make a Qrcode Generator and reader in Python.
First Install all the dependencies, we'll be using qrcode module for generatin the qrcode and Pillow library as it used by qrcode.

pip install qrcode pillow
Enter fullscreen mode Exit fullscreen mode

First create a folder for your project as in this way all of your things will be properly organised.
Now inside your folder create a python file and name it anything you want to I have named mine as "main.py"
Alt Text

Now let's begin with coding, First import all the required modules:

import qrcode
from PIL import Image
Enter fullscreen mode Exit fullscreen mode

Now create a variable to take input from the user:

text = input('Please enter a text:')
Enter fullscreen mode Exit fullscreen mode

since we have the text ready to be encoded let's create a qrcode from the text:

encoded_text = qrcode.make(text)
# You can name your file to anything you like here in the save method.
encoded_text.save('./qrcode.png')
Enter fullscreen mode Exit fullscreen mode

Alt Text
Alt Text

Alt Text

And there you go you have a your own qrcode ready in just under 10 line of python code.

Now, Let's decode a qrcode in python.
Install the required modules:

pip install pyzbar
Enter fullscreen mode Exit fullscreen mode

Import all the required modules:

from pyzbar.pyzbar import decode
from PIL import Image
Enter fullscreen mode Exit fullscreen mode

Now let's write the remaining code:

#Open your Image in Python using Pillow's Image.open() method.
img = Image.open('./qrcode.png') 
decoded_img = decode(img)

print(decoded_img[0][0].decode())
Enter fullscreen mode Exit fullscreen mode

Alt Text

That's it Now you can create your own qrcodes as well as decode them in Python :)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay