Skip to content

Instantly share code, notes, and snippets.

@tatesuke
Created February 19, 2020 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tatesuke/dc1c7c5f60e2b6339b2f10ec3d56e854 to your computer and use it in GitHub Desktop.
Save tatesuke/dc1c7c5f60e2b6339b2f10ec3d56e854 to your computer and use it in GitHub Desktop.
テキストファイルを複数のQRコードに変換する
# coding: utf-8
#
# テキストファイルを複数のQRコードに変換する
# keepassのクレデンシャルを紙に印刷するときについでにxmlもQRコードとして残そうとした時に作ったもの
# 依存モジュールは以下の通り
#
# pip install pillow qrcode
#
import logging
import os
import qrcode
logging.basicConfig(level=logging.INFO)
# 1枚のQRコードに収める文字数
# 漢字・かな (Shift_JIS) 最大1,817文字
# ぎりぎり攻めると嵌りそうだからこれくらい
QR_MAX_STRING = 1800
textFileName = "credencials.xml"
outFileNameFormat = "credencials_{}.png"
logging.info("{}を読み込みます。".format(textFileName))
with open(textFileName, mode="r", encoding="utf-8") as f:
allString = f.read()
qrStrings = []
i = 0
while i < len(allString):
j = min(len(allString), i + QR_MAX_STRING)
qrStrings.append(allString[i:j])
i = j
logging.info("{}文字あったので{}個に分割します。".format(len(allString), len(qrStrings)))
logging.info("QRコード画像を生成します。")
for i, qrString in enumerate(qrStrings):
outFileName = outFileNameFormat.format(i)
logging.info("{}を生成します。".format(outFileName))
logging.debug(qrString)
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(qrString)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
img.save(outFileName)
logging.info("完了")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment