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

标签 python python-imaging-library discord

我正在尝试将 PIL Image 对象发送到不和谐聊天(虽然我不想保存文件)
我有一个函数可以从互联网上收集图像,将它们垂直连接在一起,然后返回一个 PIL Image 对象。

下面的代码从我本地机器上的 PIL Image 对象创建一个文件图像,然后将其发送到 Discord 聊天。我不想经常在我的机器上重新创建和保存文件图像。如何只发送 PIL Image 对象,而不必每次发送请求时都保存图像?

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

最佳答案

将我的解决方案作为单独的答案发布。感谢 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'))

关于python - 如何在不保存图像的情况下将 PIL Image 对象上传到 Discord 聊天?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59868527/

相关文章:

python - 生成小于 10KB 且不丢失比例的图像缩略图

python bot阻止对命令的访问

javascript -/n 不显示为换行符

python - 如何在 discord.py 上制作关于前缀的信息?

python - 将行添加到 csv 文件而不创建中间副本

python - 元组拆包顺序更改分配的值

python - PIL 1.1.6 保存 Photoshop CMYK 图片颜色错误

python - 测量透明图像与实际图像的距离

python - 用计数替换空白字符串

python - 如何在Odoo环境中写入数据库所有缓存?