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

问题描述 投票:0回答:3

对于我的电报机器人(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
3个回答
16
投票

锁定 github wiki 包中的代码片段

根据记忆发布图像

在此示例中,图像是 PIL(或 Pillow)图像对象,但它对所有媒体类型的工作方式相同。

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

1
投票
不知道您是否有兴趣发送动画 GIF,但此代码片段应该对那些有兴趣的人有所帮助:

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()
    

0
投票
defgenerateImg(完整数据): imgBase = Image.new('RGB', (1200, 700), 颜色=COLBLACK) 绘制 = ImageDraw.Draw(imgBase) “……” img_bytes = BytesIO() imgBase.save(img_bytes, format='png') img_bytes.seek(0)

return img_bytes


@user_pr_addEv.message(AddEventState.discriptEvent, F.text) async def input_discriptEvent(消息: types.Message, 状态: AddEventState, 会话: AsyncSession):

img_bytesio = pilGen.generateImg() result = await message.answer_photo( types.BufferedInputFile( img_bytesio.read(), filename="image from buffer.jpg" ), caption="Opisanie" )
    
© www.soinside.com 2019 - 2024. All rights reserved.