When generating a QR code and returning it with API etc. or sending an email The process of saving to a file once and reading it is included. This process causes speed issues in I / O and problems in parallel processing.
With the BytesIO
module, you can generate an image in-memory without having to spit it out into a file once.
Requires qrcode and Pillow libraries.
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")
Just generate a binary stream with BytesIO ()
and do make, read and save like a file stream.
StringIO etc. also exist and can store strings. It also supports the with syntax.
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()
Let's say goodbye to intermediate files.
Recommended Posts