問題描述
我正在嘗試為 Discord 機(jī)器人實現(xiàn)一個系統(tǒng),該系統(tǒng)可以動態(tài)修改圖像并將它們發(fā)送給機(jī)器人用戶.為此,我決定使用 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)
這會導(dǎo)致我的機(jī)器人發(fā)出以下消息:
This results in the following message from my bot:
這行得通;但是,我想省略將圖像保存到硬盤驅(qū)動器并再次加載它的步驟,因為這似乎相當(dāng)?shù)托也槐匾?經(jīng)過一番谷歌搜索后,我遇到了以下解決方案;但是,它似乎不起作用:
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'))
這會導(dǎo)致以下錯誤消息:
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
參數(shù).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 文檔中的常見問題解答部分.
這篇關(guān)于從內(nèi)存中發(fā)送圖像的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!