问题
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.
Code:
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))
Error:
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
回答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"))
来源:https://stackoverflow.com/questions/58664698/error-decode-byte-when-send-image-in-discord