如何在不保存图像的情况下将PIL图像对象上传到Discord聊天?

9
我正在尝试将PIL图像对象发送到Discord聊天中(但我不想保存文件)。我有一个函数从互联网收集图像,垂直拼接它们,然后返回一个PIL图像对象。
下面的代码在我的本地机器上从PIL图像对象创建文件图像,然后将其发送到Discord聊天。我不想每次发送请求时都不断重新创建和保存文件图像。如何仅发送PIL图像对象而无需保存图像?
from PIL import Image
from io import BytesIO
import requests
import discord

# Initializes Discord Client
client = discord.Client()

# List of market indexes
indexes = [ 
    'https://finviz.com/image.ashx?dow',
    'https://finviz.com/image.ashx?nasdaq',
    'https://finviz.com/image.ashx?sp500'
]


# Returns a vertical image of market indexes
def create_image():
    im = []
    for index in indexes:
        response = requests.get(index)
        im.append(Image.open(BytesIO(response.content)))

    dst = Image.new('RGB', (im[0].width, im[0].height + im[1].height + im[2].height))
    dst.paste(im[0], (0, 0))
    dst.paste(im[1], (0, im[0].height))
    dst.paste(im[2], (0, im[0].height + im[1].height))

    return dst


# Prints when bot is online
@client.event
async def on_ready():
    print('{0.user} is online'.format(client))


# Uploads vertical image of market indexes when requested
@client.event
async def on_message(message):
    if message.content.startswith('^index'):
        create_image().save('index.png')
        await message.channel.send(file=discord.File('index.png'))

解决方案:

@client.event
async def on_message(message):
    if message.content.startswith('^index'):
        with BytesIO() as image_binary:
            create_image().save(image_binary, 'PNG')
            image_binary.seek(0)
            await message.channel.send(file=discord.File(fp=image_binary, filename='image.png'))

我爱你,谢谢这个 :) - Daniel Tam
1
刚看到这条消息,不用谢!希望你的项目进展顺利。 - leecharles_
1
如果解决方案有效,您可以将其发布为答案并接受它。 - Ceres
1个回答

4
发布我的解决方案作为单独的答案。感谢Ceres的推荐。
@client.event
async def on_message(message):
    if message.content.startswith('^index'):
        with BytesIO() as image_binary:
            create_image().save(image_binary, 'PNG')
            image_binary.seek(0)
            await message.channel.send(file=discord.File(fp=image_binary, filename='image.png'))

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