python - 如何在不保存图像的情况下将 PIL Image 对象上传到 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'))
推荐阅读
- c# - 如何使用 TelemetryClient 将 HostInstanceId 从 Azure Function 记录到 Azure Application Insights?
- haskell - 如何通过 Haskell Stack 包管理器使用 Hackage 和 Stackage 的清华镜像
- python - pyparsing:无法从 ParseResults 对象获取结果
- xml - 查询以获取嵌入在 XML 文件文本中的单词的排名
- asp.net-core - .Net Core 2.2,Ioc容器——构建对象后设置属性
- java - 如何使用 Spring Boot 在 Flowable 中启动事件后返回响应
- node.js - 通过容器 Web 应用程序或生产中的普通 Web 应用程序在 azure 中运行 NodeJS 应用程序
- docker - 在 docker 容器中运行带有音频的 pygame
- haskell - 实例头中的重复 tyvar:绑定还是引用?
- jquery - 用于区分单个和动态 id 输入类型的 jquery 选择器?