pythonpython-imaging-libraryaiogrambytesio

convert PIL.Image to IOBase class


I have a bot that creates a qr code and I want it to send qr code to the user without saving it to the hard drive

I create qr code like this:

import qrcode
qr_code_img = qrcode.make('some data')   # in handler used # qrcode.make(message.text')
print(type(qr_code_img))                 # <class 'qrcode.image.pil.PilImage'>
print(type(qr_code_img.get_image()))     # <class 'PIL.Image.Image'>

I think I need to get <class '_io.BytesIO'>

with information about qr code

class aiogram.types.input_file.InputFile(path_or_bytesio: Union[str, IOBase, Path, _WebPipe], filename=None, conf=None)

docs: https://docs.aiogram.dev/en/latest/telegram/types/input_file.html

file = InputFile(path_or_bytesio = ?)    #need to convert qr code to something
await bot.send_photo(chat_id = message.from_user.id, photo = file)

thanks a lot

qr_code_img = qrcode.make(message.text)
await bot.send_photo(chat_id = message.from_user.id, photo = qr_code_img)

if I just send a qrcode i'll get error

TypeError: Can not serialize value type: <class 'qrcode.image.pil.PilImage'>
 headers: {}
 value: <qrcode.image.pil.PilImage object at 0x000001C741E4CE10> ````

Solution

  • Your question isn't great, but I think you just want to save to a BytesIO object.

    Something like:

    from io import BytesIO
    
    import qrcode
    import aiogram
    
    def make_qrcode(text):
        buf = BytesIO()
        qrcode.make(text).save(buf, format='PNG')
        buf.seek(0)
        return aiogram.types.InputFile(buf, "qrcode.png")
    
    bot.send_photo(chat_id=message.from_user.id, photo=make_qrcode("example text"))
    

    Would hopefully do what you want.