LoginSignup
1
1

More than 3 years have passed since last update.

[備忘録]pythonでQRコードと説明を同じ画像に書く方法

Last updated at Posted at 2021-01-11

出来上がるもの

qr.png

準備

colab上で動作させるために必要なものをインストールします。

必要なライブラリのインストール


pip install qrcode pillow

用意したサンプルで日本語の文字列を画像に書き込むためフォントをインストール


!apt-get -y install fonts-ipafont-gothic

スクリプト実部


import qrcode
import PIL.Image
import PIL.ImageDraw
import PIL.ImageFont

imgpath  = "qr.png" # 画像の保存場所とファイル名
text     = "もどる" # QRコードに組み込みたい情報
# 今回は日本語の表記を追加したいので日本語フォントを用意
fontname = "/usr/share/fonts/opentype/ipafont-gothic/ipag.ttf"
# 表記する文字のサイズ
fontsize = 36

# 表記する文字サイズを取得する関数
def getTextSize(_text="test", _fontname="", _fontsize=36):
  canvasSize    = (1, 1)
  backgroundRGB = (255, 255, 255)
  img  = PIL.Image.new("RGB", canvasSize, backgroundRGB)
  draw = PIL.ImageDraw.Draw(img)
  font = PIL.ImageFont.truetype(_fontname, _fontsize)
  textWidth, textHeight = draw.textsize(_text, font=font)
  return textWidth, textHeight

# QRコードを作成し、文字表記を下部中央に追記する
def makeQRimg(_imgpath, _text, _fontname="", _fontsize=36):
  # 誤り訂正レベルを最大に、余白は仕様上の最小幅
  qr = qrcode.QRCode(
      error_correction=qrcode.constants.ERROR_CORRECT_H,
      border=4,
  )
  qr.add_data(_text)
  qr.make()
  img = qr.make_image().convert("RGB")

  textSize    = getTextSize(_text, _fontname, _fontsize)
  textTopLeft = (img.size[0]/2 - textSize[0]/2, img.size[1] - textSize[1])
  draw = PIL.ImageDraw.Draw(img)
  font = PIL.ImageFont.truetype(_fontname, _fontsize)
  draw.text(xy=textTopLeft, text=_text, fill=(0, 0, 0), font=font)

  # QRコードを保存
  img.save(_imgpath)

# 実行
makeQRimg(imgpath, text, fontname, fontsize)
# 作成したQRコードをIPython上で表示
from IPython.display import Image, display_png
display_png(Image(imgpath))
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1