volkovik
volkovik

Reputation: 67

Error decode byte when send image in discord

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

Upvotes: 0

Views: 2120

Answers (1)

volkovik
volkovik

Reputation: 67

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

Upvotes: 3

Related Questions