对于我的电报机器人(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
提前致谢:)圣诞快乐
锁定 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)
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()
return img_bytes
img_bytesio = pilGen.generateImg()
result = await message.answer_photo(
types.BufferedInputFile(
img_bytesio.read(),
filename="image from buffer.jpg"
),
caption="Opisanie"
)