From 0b8884cc2a9c4f7e179f30f0290229e09a225ecb Mon Sep 17 00:00:00 2001 From: caoqianming Date: Mon, 13 Feb 2023 15:18:54 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9B=BE=E7=89=87=E5=8E=8B=E7=BC=A9=E5=8A=9F?= =?UTF-8?q?=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/utils/img.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 apps/utils/img.py diff --git a/apps/utils/img.py b/apps/utils/img.py new file mode 100644 index 00000000..4e104f28 --- /dev/null +++ b/apps/utils/img.py @@ -0,0 +1,25 @@ +import os +from PIL import Image + +def compress_image(infile, outfile='', kb=80, step=10, quality=80): + """不改变图片尺寸压缩到指定大小 + :param infile: 压缩源文件 + :param outfile: 压缩文件保存地址 + :param kb: 压缩目标, KB + :param step: 每次调整的压缩比率 + :param quality: 初始压缩比率 + :return: 压缩文件地址,压缩文件大小 + """ + o_size = os.path.getsize(infile)/1024 + if o_size <= kb: + return infile + if outfile == '': + outfile = infile + while o_size > kb: + im = Image.open(infile) + im.save(outfile, quality=quality) + if quality - step < 0: + break + quality -= step + o_size = os.path.getsize(outfile)/1024 + return outfile, o_size \ No newline at end of file