Notebook

これは日々の作業を通して学んだことや毎日の生活で気づいたことをを記録しておく備忘録である。

HTML ファイル生成日時: 2024/12/21 11:44:57.596 (台灣標準時)

Python を使って QR コードを生成する方法

qrcode とい うモジュールを使うと、 Python を使って簡単に QR code を生成できるよう なので試してみたでござる。 qrcode module の使い方については、 https://github.com/lincolnloop/python-qrcode を見ればわかるでござる。

まず、簡単な使い方を試してみるでござる。以下のようなスクリプトを作って みたでござる。


#!/usr/pkg/bin/python3.10

#
# Time-stamp: <2023/08/03 13:30:34 (CST) daisuke>
#

# importing qrcode module
import qrcode

# string to convert into QR code
string = 'https://github.com/kinoshitadaisuke'

# output file name
file_output = 'test_qrcode_00.png'

# generating QR code
img = qrcode.make (string)

# saving QR code image into a file
img.save (file_output)

上のスクリプトを実行してみると、以下の画像が生成されたでござる。

fig_202308/test_qrcode_00.png

次に、もう少し高度な使い方として解説されているものを試してみたでござる。 以下のようなスクリプトを作ってみたでござる。


#!/usr/pkg/bin/python3.10

#
# Time-stamp: <2023/08/03 13:30:40 (CST) daisuke>
#

# importing qrcode module
import qrcode
import qrcode.image.styledpil
import qrcode.image.styles.moduledrawers.pil

# string to convert into QR code
string = 'https://github.com/kinoshitadaisuke'

# output file name
file_output = 'test_qrcode_01.png'

# constructing "QRCode" object
qr = qrcode.QRCode (
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_M,
    box_size=40,
    border=4,
    )

# string to be converted into QR code
qr.add_data (string)

# style
style = qrcode.image.styledpil.StyledPilImage

# drawer
drawer = qrcode.image.styles.moduledrawers.pil.CircleModuleDrawer ()

# generating QR code
img = qr.make_image (fill_color="black", back_color="white", \
                     image_factory=style, module_drawer=drawer)

# saving QR code image into a file
img.save (file_output)

上のスクリプトを実行して生成された画像が以下のものでござる。

fig_202308/test_qrcode_01.png

以上を踏まえて、便利に使えるスクリプトを作ってみたでござる。


#!/usr/pkg/bin/python3.10

#
# Time-stamp: <2023/08/03 14:04:26 (CST) daisuke>
#

# importing argparse module
import argparse

# importing sys module
import sys

# importing pathlib module
import pathlib

# importing qrcode module
import qrcode
import qrcode.image.styledpil
import qrcode.image.styles.moduledrawers.pil

# constructing parser object
descr  = 'QR code generator'
parser = argparse.ArgumentParser (description=descr)

# choices
choices_error_correction = ['L', 'M', 'Q', 'H']
choices_drawer = ['Square', 'GappedSquare', 'Circle', \
                  'Rounded', 'VerticalBars', 'HorizontalBars']

# adding arguments
parser.add_argument ('-b', '--background', default='white', \
                     help='background colour (default: white)')
parser.add_argument ('-c', '--correction', default='M', \
                     choices=choices_error_correction, \
                     help='error correction parameter (default M)')
parser.add_argument ('-d', '--drawer', default='Square', \
                     choices=choices_drawer, \
                     help='choice of drawer (default: Square)')
parser.add_argument ('-f', '--foreground', default='black', \
                     help='foreground colour (default: black)')
parser.add_argument ('-q', '--qrcodeversion', type=int, default=1, \
                     help='QR code version (default: 1)')
parser.add_argument ('-s', '--size', type=int, default=40, \
                     help='box size (default: 40)')
parser.add_argument ('-o', '--output', default='qrcode.png', \
                     help='output file name (default: qrcode.png)')
parser.add_argument ('-w', '--border', type=int, default=4, \
                     help='width of border (default: 4)')
parser.add_argument ('string', nargs=1, default=None, \
                     help='string to convert into QR code (default: None)')

# command-line argument analysis
args = parser.parse_args ()

# input parameters
bg_colour        = args.background
error_correction = args.correction
drawer           = args.drawer
fg_colour        = args.foreground
qrcode_version   = args.qrcodeversion
size             = args.size
file_output      = args.output
border           = args.border
string           = args.string[0]

# making pathlib object for output file
path_output = pathlib.Path (file_output)

# if output file already exists, then stop script
if (path_output.exists ()):
    # printing message
    print (f'ERROR: output file "{file_output}" exists!')
    # stopping script
    sys.exit (0)

# error correction parameter
if (error_correction == 'L'):
    error_correction_parameter = qrcode.constants.ERROR_CORRECT_L
elif (error_correction == 'M'):
    error_correction_parameter = qrcode.constants.ERROR_CORRECT_M
elif (error_correction == 'Q'):
    error_correction_parameter = qrcode.constants.ERROR_CORRECT_Q
elif (error_correction == 'H'):
    error_correction_parameter = qrcode.constants.ERROR_CORRECT_H
else:
    # printing message
    print (f'ERROR: something is wrong with error correction parameter!')
    # stopping script
    sys.exit (0)

# drawer
if (drawer == 'Square'):
    module_drawer \
        = qrcode.image.styles.moduledrawers.pil.SquareModuleDrawer ()
elif (drawer == 'GappedSquare'):
    module_drawer \
        = qrcode.image.styles.moduledrawers.pil.GappedSquareModuleDrawer ()
elif (drawer == 'Circle'):
    module_drawer \
        = qrcode.image.styles.moduledrawers.pil.CircleModuleDrawer ()
elif (drawer == 'Rounded'):
    module_drawer \
        = qrcode.image.styles.moduledrawers.pil.RoundedModuleDrawer ()
elif (drawer == 'VerticalBars'):
    module_drawer \
        = qrcode.image.styles.moduledrawers.pil.VerticalBarsModuleDrawer ()
elif (drawer == 'HorizontalBars'):
    module_drawer \
        = qrcode.image.styles.moduledrawers.pil.HorizontalBarsModuleDrawer ()
else:
    # printing message
    print (f'ERROR: something is wrong with choice of drawer!')
    # stopping script
    sys.exit (0)

# constructing "QRCode" object
qr = qrcode.QRCode (
    version=qrcode_version,
    error_correction=error_correction_parameter,
    box_size=size,
    border=border,
    )

# string to be converted into QR code
qr.add_data (string)

# style
style = qrcode.image.styledpil.StyledPilImage

# generating QR code
img = qr.make_image (fill_color=fg_colour, back_color=bg_colour, \
                     image_factory=style, module_drawer=module_drawer)

# saving QR code image into a file
img.save (file_output)

このスクリプトは、以下のように実行するでござる。


% ./test_qrcode_02.py -h
usage: test_qrcode_02.py [-h] [-b BACKGROUND] [-c {L,M,Q,H}] [-d {Square,GappedSquare,Circle,Rounded,VerticalBars,HorizontalBars}] [-f FOREGROUND] [-q QRCODEVERSION] [-s SIZE] [-o OUTPUT] [-w BORDER] string

QR code generator

positional arguments:
  string                string to convert into QR code (default: None)

options:
  -h, --help            show this help message and exit
  -b BACKGROUND, --background BACKGROUND
                        background colour (default: white)
  -c {L,M,Q,H}, --correction {L,M,Q,H}
                        error correction parameter (default M)
  -d {Square,GappedSquare,Circle,Rounded,VerticalBars,HorizontalBars}, --drawer {Square,GappedSquare,Circle,Rounded,VerticalBars,HorizontalBars}
                        choice of drawer (default: Square)
  -f FOREGROUND, --foreground FOREGROUND
                        foreground colour (default: black)
  -q QRCODEVERSION, --qrcodeversion QRCODEVERSION
                        QR code version (default: 1)
  -s SIZE, --size SIZE  box size (default: 40)
  -o OUTPUT, --output OUTPUT
                        output file name (default: qrcode.png)
  -w BORDER, --border BORDER
                        width of border (default: 4)
% ./test_qrcode_02.py -d GappedSquare -o test_qrcode_02.png https://github.com/kinoshitadaisuke
% ls -lF test_qrcode_02.png 
-rw-r--r--  1 daisuke  taiwan  11036 Aug  3 14:23 test_qrcode_02.png

できた画像は、以下のものでござる。

fig_202308/test_qrcode_02.png

参考文献



Frequently accessed files

  1. Computer___Python/20220518_0.html
  2. Computer___Network/20230726_00.html
  3. Misc___Taiwan/20240207_00.html
  4. Computer___Network/20230516_00.html
  5. Computer___FreeBSD/20220621_0.html
  6. Computer___Python/20220715_0.html
  7. Computer___Network/20230508_00.html
  8. Food___Taiwan/20220429_0.html
  9. Computer___Network/20240130_00.html
  10. Computer___NetBSD/20220817_3.html
  11. Computer___Python/20220410_0.html
  12. Computer___Network/20240416_00.html
  13. Computer___NetBSD/20230119_00.html
  14. Computer___Debian/20210223_1.html
  15. Computer___Python/20221013_0.html
  16. Computer___Python/20210124_0.html
  17. Computer___NetBSD/20220428_0.html
  18. Computer___NetBSD/20220818_1.html
  19. Computer___NetBSD/20240101_02.html
  20. Science___Math/20220420_0.html
  21. Computer___Python/20240101_00.html
  22. Computer___NetBSD/20220808_0.html
  23. Computer___TeX/20230503_00.html
  24. Science___Astronomy/20220503_0.html
  25. Computer___NetBSD/20230515_00.html
  26. Computer___Network/20220413_1.html
  27. Computer___NetBSD/20210127_0.html
  28. Computer___TeX/20231107_00.html
  29. Computer___Python/20220816_1.html
  30. Computer___Python/20230717_01.html


HTML file generated by Kinoshita Daisuke.