从内存发送图像

时间:2020-01-31 15:26:34

标签: python byte python-imaging-library discord.py

我正在尝试为Discord bot实现一个系统,该系统可以动态修改图像并将其发送给bot用户。为此,我决定使用Pillow(PIL)库,因为它对我而言似乎很简单明了。

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

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

这会导致我的机器人收到以下消息:

Discord message with the edited image as result

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

# 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'))

这将导致以下错误消息:

Traceback (most recent call last):
    File "C:\Users\<username>\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.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

1 个答案:

答案 0 :(得分:4)

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

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

另一个示例可以在How do I upload an image? section of the FAQ in discord.py's documentation中看到。