python脚本使用mozjpeg批量压缩图片
安装mozjpeg
npm install mozjpeg -g
压缩单个文件
命令
mozjpeg -quality 75 -outfile C:\\Users\\xxx\\Downloads\\img\\press\\pump1_1.jpg C:\\Users\\xxx\\Downloads\\img\\origin\\pump1_1.jpg
mozjpeg -quality 压缩质量 -outfile 输出路径 输入路径
批量压缩文件
编写python脚本
compress_images.py
import os
import subprocess
def compress_images(input_dir, output_dir, quality=75):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
if filename.lower().endswith('.jpg') or filename.lower().endswith('.jpeg'):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
print(output_path)
command = ['mozjpeg', '-quality', f'{quality}', '-outfile', output_path, input_path]
subprocess.run(command, check=True)
if __name__ == "__main__":
input_directory = r'C:\Users\xxx\Downloads\img\origin' # 替换为你的输入目录路径
output_directory = r'C:\Users\xxx\Downloads\img\press' # 替换为你的输出目录路径
compression_quality = 75 # 压缩质量(0-100)
compress_images(input_directory, output_directory, compression_quality)
运行 compress_images.py 即可
python compress_images.py