import os
from PIL import Image
def compress_image(input_path):
if os.path.getsize(input_path) <= 300*1024:
return None
else:
with Image.open(input_path) as img:
w, h = img.size
if w > 1024:
h = round(h * 1024 / w)
w = 1024
img = img.resize((w, h), Image.LANCZOS)
img.save(input_path, optimize=True, quality=80)
else:
img.save(input_path, optimize=True, quality=80)
print(input_path, "图片压缩完成")
def compress_images_in_directory(directory):
for root, dirs, files in os.walk(directory):
for file in files:
if file.lower().endswith(('.jpg', '.jpeg', '.png')):
file_path = os.path.join(root, file)
compress_image(file_path)
# 调用函数压缩指定目录下的所有图片文件
图片路径 =r"beiJingTu"
compress_images_in_directory(图片路径)
这个代码,对于超过300KB的文件,第一次可以压缩,但是如果再跑一次,同样的目录和文件名,就不再进行压缩了,是怎么回事?另外,我想把文件压缩到300KB以下,写了个循环,但是执行起来,成了死循环了,跳不出循环。有人遇到过吗?谢谢
--
FROM 120.242.240.*