【问题标题】:Error decode byte when send image in discord发送不和谐图像时错误解码字节
【发布时间】: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


【解决方案1】:
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"))

【讨论】:

  • 请避免仅使用代码回答。带有解释文字的答案对未来的读者更有帮助,更有可能被点赞
  • 我猜测需要 Seek 才能将指针移回流的开头。如果没有文件名参数,它将被发送到 Discord,但 Discord 不知道如何处理它。文件名不需要在其他任何地方引用,但您需要它带有图形扩展名(例如 PNG),因此它知道它是可以内联显示的图像数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-12
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
  • 2019-12-10
  • 1970-01-01
相关资源
最近更新 更多