猿问

如何通过电报机器人发送 PIL 图像而不将其保存到文件

对于我的电报机器人(python-telegram-bot),我生成了一个 PIL.Image.Image 并且我想将它直接发送给用户。


有效的是从文件中将图像作为 bufferedReader 发送,但我不想保护图像。之后我不再需要它,我可能会同时生成很多不同的图像,所以保存有点混乱。


bot.send_photo(chat_id=update.message.chat_id,

               photo=open(img_dir, 'rb'),

               caption='test',

               parse_mode=ParseMode.MARKDOWN)

因为是我自己生成的,所以不能使用 URL 或 file_id。我认为可以将图像转换为 bufferedReader,但我只设法从中获取了一个字节对象,这不起作用。


图像生成如下:


images = [Image.open(i) for i in dir_list]

widths, heights = zip(*(i.size for i in images))

total_width = sum(widths)

max_height = max(heights)

new_im = Image.new('RGBA', (total_width, max_height))


x_offset = 0

for im in images:

    new_im.paste(im, (x_offset, 0))

    x_offset += im.size[0]

return new_im                 # returns a PIL.Image.Image

提前致谢:) 圣诞快乐


喵喵时光机
浏览 201回答 2
2回答
随时随地看视频慕课网APP

相关分类

Python
我要回答