python+pillow+Image实现图片压缩到指定大小

本次使用的是python 3.6

先安装 pip install pillow

from PIL import Image
import os
img_path = r"H:\pythonworkspace\test\a.jpg"
img_path_2 = r"H:\pythonworkspace\test\test.jpg"


# 下面这种写法也可以
# img_path = "H:\\pythonworkspace\\test\\a.jpg"
# img_path_2 = "H:\\pythonworkspace\\test\\test1.jpg"

# img = Image.open(img_path)
def compress_image(input_path, output_path, max_size_kb=200):
# 打开图片
img = Image.open(input_path)
# 初始质量(1-100,越高越清晰)
quality = 85
# 循环调整质量,直到文件小于目标大小
while True:
# 保存图片(JPEG格式支持质量参数)
img.save(output_path, "JPEG", quality=quality, optimize=True)
# 检查文件大小
file_size_kb = os.path.getsize(output_path) / 1024
if file_size_kb <= max_size_kb or quality <= 10:
break
# 每次质量降低5(可按需调整步长)
quality -= 5
print(f"压缩完成!最终大小:{file_size_kb:.1f}KB,使用质量:{quality}")
# 调用函数(替换为你的图片路径)
compress_image(img_path, img_path_2, max_size_kb=185)


posted @ 2025-09-25 22:28  范若若  阅读(29)  评论(0)    收藏  举报