Generate QR codes from images using Python

Kevin
Geek Culture
Published in
3 min readAug 24, 2022
Photo by Sheilalau from Wikimedia Commons

Quick Response Code (QR for short) origins date back to the 90s but haven’t gained much mainstream adoption until recently. Thanks to smartphones, social distancing, and Coinbase commercials, QR codes are now a regular part of our lives.

QR codes are pretty useful—they can store all sorts of data such as text, identification numbers, binary data, and URL addresses. Visually, however, most QR codes are pretty dull. They end up looking something like this:

QR code to deepnote.com. Image by author.

But QR codes have a powerful built-in error correction mechanism with redundancy. This allows us to spice things up a bit by adding visual elements:

QR code with logo. Image by author.

While both QR codes do the same thing (both take you to deepnote.com), the QR code with an image is a lot more fun!

The QR code with the logo above was created with just a few lines of Python in a Deepnote notebook. Here’s how you can do the same:

How to generate a QR code from an image

Step 1: Pick an image

We can find any image for this step, but we found it best to use an image that’s close in size to a 1:1 aspect ratio (same width and height) because we’ll have to resize it to fit a square.

Step 2: Pick a URL

Text for our QR code is limited to 100 characters. You can use a URL shortener if you need to use a longer URL. (By the way, we don’t need to use a URL here, any text can be encoded into the resulting QR code.)

Step 3: Download and process your image

For this step, we’ll use Python’s requests library to download the image from the URL and open it in PIL for further processing. We’ll need to resize it into 2 sizes: 93x93px and 186x186px. And we’ll use both sizes later in the process.

Step 4: Generate the QR code

We are using https://github.com/xyzzy/qrpicture to generate the code. Creating a photo QR is a two-part process.

First, we need to create a 93x93 pixel-dithered monochrome image. This image is overlaid with mandatory QR pixels to ensure that the resulting image is a valid QR code.

The output is saved as a file directly in the filesystem. Here’s what it looks like:

Step 5: Add a touch of color

Now, we apply a 186x186 dithered color image on the QR code using Spacial Color Quantification. We can pick the number of colors to use. This is helpful if we want to keep the result simple or if we want to save costs on printing.

And voila! We have our QR code with an image background.

Credits

This work is based on https://github.com/xyzzy/qrpicture. If you want to modify the source code or recompile the binaries, you can do this using these commands:

--

--