From 642e17ee557cf7a9a3ef36592aa15ca837edbdda Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Fri, 17 Feb 2023 16:46:44 +0100 Subject: [PATCH] Image resize when too big --- modules/sender.py | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/modules/sender.py b/modules/sender.py index 2055c39..6783687 100644 --- a/modules/sender.py +++ b/modules/sender.py @@ -3,9 +3,10 @@ from os import makedirs, path from shutil import copyfileobj, rmtree from traceback import format_exc from uuid import uuid4 +from PIL import Image from bson import ObjectId -from pyrogram.client import Client +from classes.poster_client import PosterClient from requests import get from modules.api_client import authorize, move_pic, random_pic @@ -14,7 +15,7 @@ from modules.logger import logWrite from modules.utils import configGet, locale -async def send_content(app: Client): +async def send_content(app: PosterClient): try: @@ -52,6 +53,22 @@ async def send_content(app: Client): with open(path.join(configGet("tmp", "locations"), tmp_path), 'wb') as out_file: copyfileobj(response.raw, out_file) + logWrite(f'Candidate {pic[1]} ({pic[0]}) is {path.getsize(path.join(configGet("tmp", "locations"), tmp_path))} bytes big', debug=True) + + if path.getsize(path.join(configGet("tmp", "locations"), tmp_path)) > 5242880: + image = Image.open(path.join(configGet("tmp", "locations"), tmp_path)) + width, height = image.size + image = image.resize((int(width/2), int(height/2)), Image.ANTIALIAS) + if tmp_path.lower().endswith(".jpeg") or tmp_path.lower().endswith(".jpg"): + image.save(path.join(configGet("tmp", "locations"), tmp_path), "JPEG", optimize=True, quality=50) + elif tmp_path.lower().endswith(".png"): + image.save(path.join(configGet("tmp", "locations"), tmp_path), "PNG", optimize=True, compress_level=8) + image.close() + + if path.getsize(path.join(configGet("tmp", "locations"), tmp_path)) > 5242880: + rmtree(path.join(configGet("tmp", "locations"), tmp_dir), ignore_errors=True) + raise BytesWarning + del response submitted_caption = col_submitted.find_one( {"image": ObjectId(pic[0])} ) @@ -98,9 +115,13 @@ async def send_content(app: Client): logWrite(locale("post_exception", "console", locale=configGet("locale")).format(str(exp), format_exc())) if configGet("error", "reports"): await app.send_message(configGet("admin"), locale("post_exception", "message", locale=configGet("locale")).format(exp, format_exc())) + try: + rmtree(path.join(configGet("tmp", "locations"), tmp_dir), ignore_errors=True) + except: + pass -# async def send_content_old(app: Client): +# async def send_content_old(app: PosterClient): # # Send post to channel # try: