import base64, io, os, randomfrom PIL import Image, ImageFile# 压缩图片文件def compress_image(index): """不改变图片尺寸压缩到指定大小 :param outfile: 压缩文件保存地址 :param mb: 压缩目标,KB :param step: 每次调整的压缩比率 :param quality: 初始压缩比率 :return: 压缩文件地址,压缩文件大小 """ outfile = os.getcwd() + f'\\{index}.png' mb = 190 quality = 85 k = 0.9 o_size = os.path.getsize(outfile) // 1024 print('压缩前得图片大小------' + str(o_size)) if o_size <= mb: return reanme(index) ImageFile.LOAD_TRUNCATED_IMAGES = True while o_size > mb: im = Image.open(outfile) x, y = im.size out = im.resize((int(x * k), int(y * k)), Image.ANTIALIAS) try: out.save(outfile, quality=quality) except Exception as e: print(e) break o_size = os.path.getsize(outfile) // 1024 print('压缩后得图片大小------' + str(o_size)) reanme(index) return outfiledef reanme(index): ran_name = 'img_' + str(random.random()).replace('.', '') + '_' + str(random.randint(1, 100000)) img_path = os.getcwd() img_list = os.listdir(img_path) for img in img_list: if img.endswith('.png') & img.startswith(f'{index}'): src = os.path.join(os.path.abspath(img_path), img) # 原先的图片名字 dst = os.path.join(os.path.abspath(img_path), ran_name + img) # 根据自己的需要重新命名,可以把'E_' + img改成你想要的名字 os.rename(src, dst) # 重命名,覆盖原先的名字# 压缩base64的图片def compress_image_bs4(b64, mb=190, k=0.9): """不改变图片尺寸压缩到指定大小 :param outfile: 压缩文件保存地址 :param mb: 压缩目标,KB :param step: 每次调整的压缩比率 :param quality: 初始压缩比率 :return: 压缩文件地址,压缩文件大小 """ f = base64.b64decode(b64) with io.BytesIO(f) as im: o_size = len(im.getvalue()) // 1024 if o_size <= mb: return b64 im_out = im while o_size > mb: img = Image.open(im_out) x, y = img.size out = img.resize((int(x * k), int(y * k)), Image.ANTIALIAS) im_out.close() im_out = io.BytesIO() out.save(im_out, 'jpeg') o_size = len(im_out.getvalue()) // 1024 b64 = base64.b64encode(im_out.getvalue()) im_out.close() return str(b64, encoding='utf8')if __name__ == "__main__": # 获取图片路径 for i in range(0, 6): compress_image(i) print('----------------') print(f'第{i}张压缩成功!!')