简体   繁体   中英

How can I upload a PIL Image object to a Discord chat without saving the image?

I'm trying to send a PIL Image object to a discord chat (I don't want to save the file though) I have a function that gathers images from the internet, joins them together vertically and then return a PIL Image object.

The code below creates a file image from the PIL Image object on my local machine and then sends it to a Discord chat. I don't want to constantly be recreating and saving the file image on my machine. How can I just send the PIL Image object instead of having to save the image every time I send a request?

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

SOLUTION:

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

Posting my solution as a separate answer. Thanks Ceres for the recommendation.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM