从内存中发送图像

问题描述

我正在尝试为 Discord 机器人实现一个系统,该系统可以动态修改图像并将它们发送给机器人用户.为此,我决定使用 Pillow (PIL) 库,因为它对我的目的来说看起来简单明了.

I am trying to implement a system for a Discord bot that dynamically modifies images and sends them to the bot users. To do that, I decided to use the Pillow (PIL) library, since it seemed simple and straightforward for my purposes.

这是我的工作代码示例.它加载一个示例图像,作为测试修改,在其上绘制两条对角线,并将图像作为 Discord 消息输出:

Here is an example of my working code. It loads an example image, as a test modification, draws two diagonal lines on it, and outputs the image as a Discord message:

# Open source image
img = Image.open('example_image.png')

# Modify image
draw = ImageDraw.Draw(img)
draw.line((0, 0) + img.size, fill=128)
draw.line((0, img.size[1], img.size[0], 0), fill=128)

# Save to disk and create discord file object
img.save('tmp.png', format='PNG')
file = discord.File(open('tmp.png', 'rb'))

# Send picture as message
await message.channel.send("Test", file=file)

这会导致我的机器人发出以下消息:

This results in the following message from my bot:

这行得通;但是,我想省略将图像保存到硬盘驱动器并再次加载它的步骤,因为这似乎相当低效且不必要.经过一番谷歌搜索后,我遇到了以下解决方案;但是,它似乎不起作用:

This works; however, I would like to omit the step of saving the image to the hard drive and loading it again, since that seems rather inefficient and unnecessary. After some googling I came across following solution; however, it doesn't seem to work:

# Save to disk and create discord file object
# img.save('tmp.png', format='PNG')
# file = discord.File(open('tmp.png', 'rb'))

# Save to memory and create discord file object
arr = io.BytesIO()
img.save(arr, format='PNG')
file = discord.File(open(arr.getvalue(), 'rb'))

这会导致以下错误消息:

This results in the following error message:

Traceback (most recent call last):
    File "C:Users<username>AppDataLocalProgramsPythonPython38-32libsite-packagesdiscordclient.py", line 270, in _run_event
        await coro(*args, **kwargs)
    File "example_bot.py", line 48, in on_message
        file = discord.File(open(arr.getvalue(), 'rb'))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte


解决方案

discord.File 支持传递 io.BufferedIOBase 作为 fp 参数.
io.BytesIO 继承自 <代码>io.BufferedIOBase.
这意味着您可以直接将 io.BytesIO 的实例作为 fp 来初始化 discord.File,例如:

discord.File supports passing io.BufferedIOBase as the fp parameter.
io.BytesIO inherits from io.BufferedIOBase.
This means that you can directly pass the instance of io.BytesIO as fp to initialize discord.File, e.g.:

arr = io.BytesIO()
img.save(arr, format='PNG')
arr.seek(0)
file = discord.File(arr)

另一个例子可以在 如何上传图片?discord.py 文档中的常见问题解答部分.

相关文章