【发布时间】:2020-02-28 01:46:08
【问题描述】:
我在发送不和谐的图像时遇到了一些问题。我决定使用 Pillow 库来创建图像,我想发送由该库创建的图像不保存。我发现我可以将 Image 对象转换为二进制数据并放入 fp 参数。但它引发了编码错误。
代码:
image = Image.open("test.png")
image_binary = BytesIO()
image.save(image_binary, "PNG")
image_binary = image_binary.getvalue()
await ctx.send(file=discord.File(fp=image_binary))
错误:
Traceback (most recent call last):
File "D:\Projects\Python\phoenix\venv\lib\site-packages\discord\ext\commands\core.py", line 79, in wrapped
ret = await coro(*args, **kwargs)
File "D:\Projects\Python\phoenix\modules\welcome.py", line 25, in test_image
await ctx.send(file=discord.File(fp=image_binary))
File "D:\Projects\Python\phoenix\venv\lib\site-packages\discord\file.py", line 68, in __init__
self.fp = open(fp, 'rb')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
【问题讨论】:
-
我根本不知道
discord,但是您在代码的最后一行传递给它的image_binary参数不是文件指针——它是一个包含全部内容的缓冲区(已读取)来自 PNG 图像文件。 -
@MarkSetchell 那么我应该在文件名参数中写入任何名称吗?这是关于
discord.File- discordpy.readthedocs.io/en/latest/…的文档 -
不,这完全不是文件????您需要将 buffer 而不是 fils 传递给
ctx.send(),但我也不知道记录在哪里,并且您已经删除了import语句,所以我不知道它来自哪里来自。 -
但是我应该在聊天中发送文件,不是吗?函数
send不支持缓冲区,需要转换文件对象。否则没关系,我找到了解决方案。感谢您尝试帮助我!
标签: python python-imaging-library discord.py discord.py-rewrite bytesio