在Discord上发送Pillow图像,无需保存图像。

4
from PIL import Image, ImageDraw, ImageFont

@client.command()
async def test(ctx):
   image = Image.open('background.png')
   font = ImageFont.truetype('arial.ttf', size=35)
   draw.text((0, 0), f"Example", fill="white", font=font)

   draw.save("image.png")
   await ctx.send(File=discord.File("image.png"))

如何在不先保存图像的情况下发送使用Pillow.py创建的图像。我已经试图在Stack Overflow上搜索可用的解决方案,但是没有找到任何可行的方法。感谢任何帮助!之前我尝试使用IO解决此问题,但最终只会发送空文件。


你将图像转换为base64,然后使用fpio读取器读取它。 - Saddy
是的,就像那样。我的版本略有不同,但如果它能工作,那就行了。 - Saddy
我建议你去查看StringIO和BytesIO,找到最适合你的。在文档中阅读更多。 - Mensch
discord.File(fp=BytesIO(x)) 中的 x 是通过对 File 上的 fp.read() 创建的对象。 - Saddy
如何将图像保存到BytesIO中:with io.BytesIO() as output:\n image.save(output, format=[...]), 需要指定格式。 - Mensch
显示剩余7条评论
1个回答

6
with io.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,它可以正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接