better use of BytesIO

This commit is contained in:
klemek
2020-04-30 09:12:05 +02:00
parent 59a8530cbe
commit 6f38686513
2 changed files with 11 additions and 13 deletions
+7 -9
View File
@@ -3,7 +3,7 @@ import traceback
import logging import logging
import discord import discord
import re import re
import tempfile from io import BytesIO
import sys import sys
from datetime import datetime from datetime import datetime
from dotenv import load_dotenv from dotenv import load_dotenv
@@ -134,8 +134,11 @@ async def on_message(message: discord.Message):
else: else:
await message.channel.send(response) await message.channel.send(response)
else: else:
with tempfile.NamedTemporaryFile(delete=False) as output: with BytesIO() as output_file:
img.save(output, format="JPEG") img.save(output_file, format="JPEG")
output_file.flush()
output_file.seek(0)
response = None response = None
meme_id = utils.sanitize_input(args[0]) meme_id = utils.sanitize_input(args[0])
if len(args) == 1 and meme_id not in ["image", "text"]: if len(args) == 1 and meme_id not in ["image", "text"]:
@@ -153,13 +156,8 @@ async def on_message(message: discord.Message):
response = f"A meme by {message.author.mention}:" response = f"A meme by {message.author.mention}:"
if message_id not in SENT: if message_id not in SENT:
SENT[message_id] = [] SENT[message_id] = []
response = await message.channel.send(response, response = await message.channel.send(response, file=discord.File(output_file, "meme.jpg"))
file=discord.File(filename="meme.jpg", fp=output.name))
SENT[message_id] += [response] SENT[message_id] += [response]
try:
os.remove(output.name)
except PermissionError:
pass
if not is_direct: if not is_direct:
await delete(message) await delete(message)
+2 -2
View File
@@ -59,8 +59,8 @@ def compute(*args: str, input_data: Optional[bytes] = None,
output_image = img_factory.apply_texts(output_image, watermarks, debug=debug) output_image = img_factory.apply_texts(output_image, watermarks, debug=debug)
if max_file_size is not None: if max_file_size is not None:
img_file = BytesIO() with BytesIO() as img_file:
output_image.save(img_file, 'jpg') output_image.save(img_file, 'JPEG')
if img_file.tell() > max_file_size: if img_file.tell() > max_file_size:
return None, ['Output image too big'] return None, ['Output image too big']