【问题标题】:How to send an PIL Image via telegram bot without saving it to a file如何通过电报机器人发送 PIL 图像而不将其保存到文件中
【发布时间】:2018-12-24 23:49:16
【问题描述】:

对于我的电报机器人 (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

提前感谢 :) 圣诞快乐

【问题讨论】:

标签: python python-3.x type-conversion python-imaging-library python-telegram-bot


【解决方案1】:

从包 github wiki 锁定 code snippet

张贴记忆中的图片

在本例中,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)

【讨论】:

  • 我实际上一直在那个确切的页面上而没有注意到它。无论如何,它就像一个魅力,而且比以前快得多(显然)。非常感谢。
【解决方案2】:

不知道你是否对发送动画 GIF 感兴趣,但这段代码 sn-p 应该对那些愿意的人有所帮助:

from telegram import Update, ForceReply
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext

def echo_gif(update: Update, context: CallbackContext) -> None:
    """ Echo to /gif command """
    
    context.bot.sendAnimation(chat_id=update.message.chat_id,
               animation=open("URuEc5hnbNIGs.gif", 'rb').read(), ## some local file name
               caption='That is your gif!',
               )
    return    

def main() -> None:
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    updater = Updater(TOKEN)

    # Get the dispatcher to register handlers
    dispatcher = updater.dispatcher

    # on different commands - answer in Telegram
    dispatcher.add_handler(CommandHandler("gif", echo_gif))
    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 2017-06-16
    • 1970-01-01
    • 2019-06-02
    相关资源
    最近更新 更多