From f5ceb8927f2e7f2a9e29d62c8e4cef876f917249 Mon Sep 17 00:00:00 2001 From: Kyomotoi <1172294279@qq.com> Date: Sat, 6 Feb 2021 00:32:26 +0800 Subject: =?UTF-8?q?=F0=9F=8F=97=20=F0=9F=92=A9=20=E6=9B=B4=E6=94=B9?= =?UTF-8?q?=E9=A1=B9=E7=9B=AE=E7=BB=93=E6=9E=84=EF=BC=8C=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E5=95=A5b=20BUG?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ATRI/utils/img.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 ATRI/utils/img.py (limited to 'ATRI/utils/img.py') diff --git a/ATRI/utils/img.py b/ATRI/utils/img.py new file mode 100644 index 0000000..68a44fc --- /dev/null +++ b/ATRI/utils/img.py @@ -0,0 +1,23 @@ +import os +from PIL import ImageFile, Image + +from ATRI.exceptions import WriteError + + +def compress_image(out_file, kb=500, quality=85, k=0.9) -> str: + """将目标图片进行压缩""" + o_size = os.path.getsize(out_file) // 1024 + if o_size <= kb: + return out_file + + ImageFile.LOAD_TRUNCATED_IMAGES = True # type: ignore + while o_size > kb: + img = Image.open(out_file) + x, y = img.size + out = img.resize((int(x * k), int(y * k)), Image.ANTIALIAS) + try: + out.save(out_file, quality=quality) + except WriteError: + raise WriteError('Writing file failed!') + o_size = os.path.getsize(out_file) // 1024 + return out_file -- cgit v1.2.3