在不和谐中发送图像时错误解码字节

Error decode byte when send image in discord

我在发送不和谐的图像时遇到了一些问题。我决定使用 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
image = Image.open("test.png")

with BytesIO() as image_binary:
    image.save(image_binary, "PNG")
    image_binary.seek(0)
    await ctx.send(file=discord.File(fp=image_binary,filename="image.png"))