Mass generation of QR code with character display by Python

Article summary

QR code is automatically generated using Python's qrcode. I want to write the identification number on the QR code at the same time, so I also use pillow and other tools to insert the characters.

Tool installation

Use qrcode to generate the QR code.

https://pypi.org/project/qrcode/

Please install qrcode.

pip install qrcode

Pillow is used to process the image.

https://pypi.org/project/Pillow/

Please install pillow.

pip install Pillow

QR code generation

import qrcode
from PIL import Image

img = qrcode.make("Hello World!")
img.save('test.png')

img.show()
test.png

You can check if the generated QR code can be read correctly by reading it at http://qrcode.red/.

qrコード読み取り結果.png

QR code generation (detailed settings)

You can also make detailed settings.

import qrcode
from PIL import Image

qr = qrcode.QRCode(
    version=3,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=2,
)
qr.add_data('Hello World!')
qr.make(fit=True)

img = qr.make_image(fill_color="black", back_color="white")
img.save('test.png')

img.show()

Add margin

The function add_margin published in note.nkmk.me is convenient for adding and deleting margins to images.

Add margins to the top, bottom, left, and right of the image and resize with Python, Pillow

See the blog above for details on the function. This time I want to make a margin to display characters under the QR code, so add the size downward. The background color is white (#ffffff).

from PIL import Image
img = Image.open('test.png') #Load the image saved earlier
img_new = add_margin(img, 0, 0, 100, 0, '#ffffff')

img_new.show()

This function is useful for adjusting the image size because you can reduce the size by entering a negative number.

Change image size

I'll show you how to scale the image size for later use. You can scale the image with resize.

from PIL import Image, ImageDraw, ImageFont
img = Image.open('test.png') #Loading images
img_resize = img.resize((int(img .width / 2), int(img .height / 2)), Image.LANCZOS)

img_resize.show()

'Image.LANCZOS' is a parameter that specifies the compression filter. Select from the following. In general, the lower one has a lower compression ratio, but the image is cleaner. This parameter is optional, otherwise NEAREST will be applied automatically.

Insert characters

I tried to insert characters by the method introduced in Image processing cheat sheet using Pillow that can edit images at once with Python.

from PIL import Image, ImageDraw, ImageFont
img = Image.open('test.png')
img_new = add_margin(img, 0, 0, 100, 0, '#ffffff')

draw = ImageDraw.Draw(img_new) 
font = ImageFont.truetype("./fonts/arial.ttf", 55) 
draw.text((10, 320), 'Hello! 12345', font=font, fill='#000000') 
img_new.save('test.png')

img_new.show()
bad_test.png

You can change the font type. Please refer to the following to select. https://helpx.adobe.com/jp/x-productkb/global/cq08041028.html

When the image resolution of characters is rough

For small size QR codes, the characters inserted by the above method have the disadvantage of being rough. Therefore, save the high-resolution image enlarged by resize and size it appropriately with the tool that reduces the image size.

First, magnify the image with margins 10 times and insert large characters there.

from PIL import Image, ImageDraw, ImageFont
img = Image.open('test.png')
img_add = add_margin(img, 0, 0, 100, 0, '#ffffff')

img_resized = img_add.resize((int(img_add.width*10), int(img_add.height*10)), resample=Image.LANCZOS)

draw = ImageDraw.Draw(img_resized)
font = ImageFont.truetype("./fonts/arial.ttf", 530) 
draw.text((190, 3200), 'Hello! 12345', font=font, fill='#000000') 
img_resized.save('test.png')

img_resized.show()

I used the free software Fuji -Resizer- to reduce the image. Even hundreds of images can be reduced at once by dragging and dropping them onto the icon.

https://pcgenki.com/soft/resizer.htm

画像縮小.png

The characters are displayed neatly.

test_s.png

If you check it with image editing software, you can see that the resolution is not a problem even if you print it.

qrコード画像解像度結果.png

Mass production

By converting the existing code into a function, you can generate a large number of QR codes with serial numbers.

The automatic creation of the folder imitated the following article. Create Python folder Check if it already exists

import os
import qrcode
from PIL import Image, ImageDraw, ImageFont

def add_margin(pil_img, top, right, bottom, left, color):
    #Please copy the code from the article introduced earlier.
    return result

def qr_generator(number):
    qr = qrcode.QRCode(
        version=2,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=9,
        border=4,
    )
    qr.add_data('Hello!' + number)
    qr.make(fit=True)

    img = qr.make_image(fill_color="black", back_color="white")
    img.save('./my_qr_code/' + number + '.png')

    img = Image.open('./my_qr_code/' + number + '.png')
    img_add = add_margin(img, -15, -15, 45, -15, '#ffffff')
    img_resized = img_add.resize((int(img_add.width*10), int(img_add.height*10)), resample=Image.LANCZOS)
    
    draw = ImageDraw.Draw(img_resized)
    font = ImageFont.truetype("./fonts/arialbd", 450)
    num = number
    draw.text((200, 2550), 'Hello!' + num, font=font, fill='#000000') 
    img_resized.save('./my_qr_code/' + number + '.png', quality=95)

    #img_resized.show()


def main(total_num):
    new_path = "my_qr_code"#Folder name
    if not os.path.exists(new_path):#Check for directory
        os.mkdir(new_path)
    
    for number in range(total_num):
        qr_generator(str(1000+number))    
    
main(100) 

Use Fuji -Resizer- to reduce the images created above to complete the process.

Recommended Posts

Mass generation of QR code with character display by Python
Convert the character code of the file with Python3
2.x, 3.x character code of python
[Python] Get the character code of the file
python character code
QR code display
[Python] [chardet] Automatic detection of character code of file
Links and memos of Python character code strings
Static analysis of Python code with GitLab CI
[Blender x Python] Think of code with symbols
About Python3 character code
Read QR code from image file with Python (Mac)
JPEG image generation by specifying quality with Python + OpenCV
Memo of "Cython-Speeding up Python by fusing with C"
Display Matsuya coupon (QR code) with Pythonista for iOS
Get country code with python
Python with VS Code (Windows 10)
Let's run jupyter natively supported by VS Code with python3.8
[Python] How to make a list of character strings character by character
Generation of junk character MNIST (KMNIST) with cGAN (conditional GAN)
Debug Python with VS Code
Generate QR code in Python
Character code learned in Python
Document Python code with Doxygen
I couldn't use tkinter with python installed by pyenv of anyenv
[Let's play with Python] Aiming for automatic sentence generation ~ Completion of automatic sentence generation ~
Let's summarize the degree of coupling between modules with Python code
Addicted to character code by inserting and extracting data with SQLAlchemy
Decrypt the QR code with CNN
Expansion by argument of python dictionary
Prime number generation program by Python
Waveform display of audio in Python
Getting Started with Python Basics of Python
Life game with Python! (Conway's Game of Life)
10 functions of "language with battery" python
[Beginner] Extract character strings with Python
Separate display of Python graphs (memo)
Password generation in texto with python
Behavior of python3 by Sakura's server
Implementation of Dijkstra's algorithm with python
CSRF countermeasure token generation with Python
Coexistence of Python2 and 3 with CircleCI (1.0)
Example of code rewriting by ast.NodeTransformer
Story of power approximation by Python
Install python with mac vs code
Feature generation with pandas group by
Basic study of OpenCV with Python
Gradation image generation with Python [1] | np.linspace
Immediate display, forced display, flash of print output result with python (mainly jupyter)
Derivation of multivariate t distribution and implementation of random number generation by python
[Python] Summary of conversion between character strings and numerical values (ascii code)
I tried to get the authentication code of Qiita API with Python.
Source code of sound source separation (machine learning practice series) learned with Python
Python code to train and test with Custom Vision of Cognitive Service
Installation of Visual studio code and installation of python
Explanation of production optimization model by Python
Basics of binarized image processing with Python
Get property information by scraping with python
[Python] Calendar-style heat map (with holiday display)
[Examples of improving Python] Learning Python with Codecademy
Calculate and display standard weight with python