lincolnloop / python-qrcode

Python QR Code image generator
https://pypi.python.org/pypi/qrcode
Other
4.34k stars 664 forks source link

Convert to data URI #222

Closed EricOuma closed 3 years ago

EricOuma commented 3 years ago
import qrcode
img = qrcode.make('Some data here')

Any leads on how I can convert the img object returned here to a data uri NB: I don't want to save the image to a file.

EmperorArthur commented 3 years ago

Answer

Data URLs are described here. The trick is to write the image data to a buffer instead of a real file.

import qrcode
from io import BytesIO
from base64 import b64encode

buffer = BytesIO()
img = qrcode.make('Some data here')
img.save(buffer)
encoded_img = b64encode(buffer.getvalue()).decode()

data_uri = "data:image/png;base64,{}".format(encoded_img)

data_uri has the value you want. Note that b64encode returns bytes, so decode() was used to convert it to a string.