从内存发送图像 [英] Send image from memory
问题描述
我正在尝试为Discord bot实现一个系统,该系统可以动态修改图像并将其发送给bot用户.为此,我决定使用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>\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
推荐答案
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)
有关此问题的另一个示例,请参见.
Another example of this can be seen in the How do I upload an image? section of the FAQ in discord.py's documentation.
这篇关于从内存发送图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!