LoginSignup
1
2

More than 3 years have passed since last update.

【Python】QRコードをインメモリに生成

Posted at

QRコードを生成しAPI等で返したり、メール送信する場合、
一度ファイルにセーブし、それを読み出ししたりする処理が入ります。
この処理の場合、I/Oでの速度的問題や、並列処理時に問題が生じます。

BytesIOモジュールを使えば、一度ファイルに吐き出すことなく、インメモリに画像を生成出来ます。

環境

  • Python 3.7.4
  • qrcode 6.1
  • Pillow 7.0.0

qrcodeおよびPillowライブラリが必要です。

pip install qrcode pillow

生成

from io import BytesIO
import base64
import qrcode


class QRImage():

    @staticmethod
    def to_bytes(text: str) -> bytes:
        stream = BytesIO()
        img = qrcode.make(text)
        img.save(fp, "PNG")
        stream.seek(0)
        byte_img = stream.read()
        stream.close()
        return byte_img

    @classmethod
    def to_b64(cls, text: str) -> bytes:
        byte = cls.to_bytes(text)
        return base64.b64encode(byte).decode("utf-8")

if __name__ == "__main__":
    binary = QRImage.to_bytes(text="some_text")
    base64_encoded = QRImage.to_b64(text="some_text")

BytesIO()でバイナリストリームを生成、ファイルストリームのようにmakeやread、saveを行うだけです。

StringIO等も存在し、stringを格納することが出来ます。
また、with構文もサポートしています。

from io import StringIO

def main():
    with StringIO() as fp:
        fp.write("Hello")
        print(fp.closed)     # True
        print(fp.getvalue()) # Hello
    print(fp.closed)         # False

main()

これで中間ファイルとはおさらばしましょう。

1
2
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
2