不一致发送图像时解码字节错误 [英] Error decode byte when send image in discord

查看:90
本文介绍了不一致发送图像时解码字节错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在发送图像不一致时遇到一些问题。我决定使用枕头库创建图像,并且我要发送由该库创建的图像不保存。我发现了可以将Image对象转换为二进制数据并放入fp参数的方法。但这会引起编码错误。

I have some problems with sending images in discord. I decide to use Pillow library for creating images and I want to send image which is created by this library without save. I found out what I can convert Image object to binary data and put in fp argument. But it raised encoding error.

代码:

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"))

这篇关于不一致发送图像时解码字节错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆