Make beautiful QR codes in Python
Encourage human interactions with the creative use of QR codes
--
Most people think about “industrial” applications like warehouse management or product labelling when you mention QR codes to them, but this article is very much about personal and social uses for QR codes, and the human interactions they can facilitate.
Fun Fact
Did you know that “Quick Response” (QR) codes were invented almost 30 years ago in 1994, but there’s been a widely reported resurgence in their use for “non-contact” purposes due to COVID?
My sudden interest in QR codes
Despite being aware of QR codes for decades now, I only really became interested in them this November as we started what I call the “Social Season”.
For me and many others in the Northern Hemisphere, the last two months of the year are characterised by celebrations and a constant stream of house visitors for festive drinks and nibbles, chasing away the cold and the long Winter nights.
A few select friends celebrate Thanksgiving, Diwali, and Hanukkah, and almost everyone in the UK comes together for Halloween, Guy Fawkes’ Night, Christmas, and New Year. In my family, you can also add numerous birthdays which I’m convinced are due to November being nine months on from Valentine’s Day (February the 14th).
I think you know what I’m getting at?
Anyway, this Social Season prompted me to think about two particular jobs that were screaming out for automation:
- I wanted to include a video message inside hand-written Christmas cards but it just seemed wrong to write something like “https://youtu.be/px6FeOKD3Zc” and expect people to slavishly type that into their phones or computers.
- It was taking a crazy amount of time telling house guests our WIFI login details, which they’d usually type very slowly and very “creatively” (i.e. incorrectly) several times before finally getting connected.
QR codes were an obvious solution. It’s great they can be scanned by pretty much any phone using the default photo app, but equally great that scanning them also triggers some kind of action depending on their context.
For example a QR code containing a URL allows you to open it in your browser. A QR code containing Wifi login details allows you to connect immediately. A QR code with contact details allows you to create a new contact in your address book. A QR code with geo-coordinates allows you to find a location on a map. This makes life extremely easy for the person doing the scanning, and takes the giver of the information out of the equation entirely… they no longer need to be present in order for an interaction to happen.
Getting Started
I did a little research before jumping in, and chose the segno
module in Python due to it’s comprehensive list of features and nice documentation. It doesn’t appear at the top of a Google search for QR codes in Python, and doesn’t even have “QR” in the module name, but don’t let this put you off — it’s an awesome tool!
So let’s start by creating the simplest possible QR code with the .make()
method. It just contains raw data that can be copied or transferred, and since the content is very short, segno
creates a fun sized “micro QR” code by default:
pip install segno
import segno
price_tag = segno.make("£9.99")
price_tag.save("Price Tag.png")
Instead of using .save to create a file, then navigate to it, then display it, then delete it after use, you can also use the handy .show method. This creates a temporary image file and opens it in your default image viewer automatically. Great for debugging or testing, particularly if you start experimenting with different colours and background images and want to confirm the QR code still scans properly.
QR Codes for URL sharing
Using the same method with a slightly larger payload, the Python code for my first task (sharing a video message) was trivial:
import segno
video = segno.make('https://youtu.be/px6FeOKD3Zc')
video.save('Video.png', scale=4)
With just one extra line of code I was able to create a much more colourful QR code, in this case for a favourite picture of mine which is actually a “Hello World” script written in the Piet programming language:
pip install qrcode-artistic
import segno
piet = segno.make('https://esolangs.org/wiki/Piet', error='h')
piet.to_artistic(background="background.png", target='Piet.png', scale=16)
QR Codes for WIFI details
The Python code for my second task (WIFI login details) was just as straightforward, but I customised the colours and made the output larger:
import segno
wifi_settings = {
"ssid": '(Wifi Name)',
"password": '(Wifi Password)',
"security": 'WPA',
}
wifi = segno.helpers.make_wifi(**wifi_settings)
wifi.save("Wifi.png", dark="yellow", light="#323524", scale=8)
If you haven’t come across
**
in Python before, it’s a lovely bit of so-called syntactic sugar that unpacks a dictionary into a series of keyword arguments e.g.ssid=”(Wifi Name)”, password=”(Wifi Password)”, security=”WPA”
. By creatingwifi-settings
as a dictionary first and formatting it with one key:value pair per line, it’s much easier to edit and add to in future, and the function in the following line (wifi=
) is also much more concise and readable as a consequence.
QR Codes for Contact Details
Encouraged by these quick successes, I decided to create a QR code for a friend’s arts and crafts business:
import segno
vcard = segno.helpers.make_vcard(
name='Pxxx;Jxxx',
displayname='Times Tables Furniture',
email=('jxxxpxxx@timestables.furniture'),
url=[
'https://www.etsy.com/uk/shop/TimesTablesFurniture',
'https://www.facebook.com/profile.php?id=100083448533180'
],
phone="+44xxxxxxxxxx",
)
img = vcard.to_pil(scale=6, dark="#FF7D92").rotate(45, expand=True)
img.save('Etsy.png')
For my own vCard I chose to add my company logo as a background:
import segno
awsom = segno.helpers.make_vcard(
name='Fison;Pete',
displayname='AWSOM Solutions Ltd.',
email=('pxxxfxxx@awsom.solutions'),
url=[
'https://twitter.com/awsom_solutions',
'https://medium.com/@petefison',
'https://github.com/pfython'
],
phone="+44xxxxxxxxxx",
)
awsom.to_artistic(
background="logo.png",
target='AWSOM.png',
scale=6,
quiet_zone="#D29500"
)
QR Codes for other purposes
The segno
API also allows you to do the following:
segno.helpers.make_email : Send an email with pre-prepared subject and content. Great for subscribing to newsletters, registering your arrival somewhere, or triggering any number of possible actions from a mail server.
segno.helpers.make_epc_qr : Initiate an electronic payment.
segno.helpers.make_geo : Open the default mapping app at a particular Latitude and Longitude.
segno.make_sequence : Create a sequence of QR codes using the “Structured Append” mode.
Keeping everything in memory
If you prefer to keep all your processing “in memory” rather than creating files on your hard drive or server, you can either create a PIL image object or save a file-like object using BytesIO:
import segno
beatle = segno.make('Paul McCartney')
beatle = qrcode.to_pil()
import segno
import io
beatle = segno.make('Paul McCartney')
buff = io.BytesIO()
beatle.save(buff, kind='svg')
Similarly if you prefer to load background images from their URLs directly into memory without creating a file on your hard drive or server first, you can use the urlopen method:
from urllib.request import urlopen
import segno
beatle = segno.make('Ringo Starr', error='h')
url = 'https://media.giphy.com/media/HNo1tVKdFaoco/giphy.gif'
bg_file = urlopen(url)
beatle.to_artistic(background=bg_file, target='ringo.gif', scale=10)
Creative, homely ideas for QR codes
Hopefully this short article has given you an appetite for using QR codes not just for “industrial” projects but for personal and social projects too. There are plenty of free articles online suggesting creative uses for QR codes for business and marketing, so I’d like to end this article by sharing a few “homely” ideas of my own that might appeal to you:
- Information about your local council’s collection days and recycling rules on the side of your rubbish bins
- Trigger an email to loved ones saying you’ve arrived home safely.
- Trigger an update saying you’ve left the house.
- Treasure hunts around your local town or country paths; link to your own website with local information, social media groups, current geo-location etc.
- Treasure hunts around your house for younger children, or dinner parties.
- Stick a QR code on a postcard so family and friends go directly to the latest entry in your travel diary, photo diary, or Blog.
- Appliance instructions for things like the washing-machine, microwave, oven, printer, boiler, 3D printer, laser-cutter, or even the car.
- Sticker for your coal shed, wood shed, or oil tank for re-ordering fuel.
- Your family tree or history, or property information saved for posterity.
- An online guest book where visitors can record their stay and leave a personal message.
- Sticker on the fridge linking to the latest household shopping list.
- List of weekly chores for each family member.
- “If lost, please return to…” stickers for laptops, phones, cameras, drones etc.
- Electronic “swear jar”; the offender makes a (small) payment every time they’re caught cursing.
- Honesty Box — for people to pay as they use/consume/buy something e.g. food and drink from a shared fridge, eggs for sale outside a farm.
- Manage TV/Internet/Gaming privileges by booking in/out.
- Emergency contact details for baby-sitters or pet-sitters.
- Emergency contacts for you in case of outages — water, electricity, gas.
- Local food delivery companies for anyone house-sitting for you.
- Personal video messages/reminders.
- Information about your favourite ornaments or works of art around the house.
- Tasting notes for your wine rack/wine cellar.
- Labels for garden plants and trees — details of species, watering, age etc.
Happy QRing, if that’s a thing (!) and if you’re interested in learning more about the history of QR codes, there’s a great series of articles here.