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

Deo*_*cid 7 python type-conversion python-imaging-library python-3.x python-telegram-bot

对于我的电报机器人(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)
Run Code Online (Sandbox Code Playgroud)

因为是我自己生成的,所以不能使用 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
Run Code Online (Sandbox Code Playgroud)

提前致谢:) 圣诞快乐

Pau*_*rtz 7

锁定来自包 github wiki 的此代码片段

发一张记忆中的图片

在这个例子中,image 是一个 PIL(或 Pillow)Image 对象,但它对所有媒体类型的工作方式都是一样的。

from io import BytesIO
bio = BytesIO()
bio.name = 'image.jpeg'
image.save(bio, 'JPEG')
bio.seek(0)
bot.send_photo(chat_id, photo=bio)
Run Code Online (Sandbox Code Playgroud)