批量图片压缩脚本

代码脚本 · 其他

Python+Pillow编写的图片批量压缩工具,支持JPG/PNG/WebP格式,可设置压缩质量,批量处理文件夹中的所有图片,保持画质的同时大幅减小体积,是网站优化和图片管理的必备工具。

详细内容

from PIL import Image import os, glob input_dir = 'images'; output_dir = 'compressed' quality = 80; max_width = 1920 os.makedirs(output_dir, exist_ok=True) for f in glob.glob(os.path.join(input_dir, '*.{jpg,jpeg,png}')): img = Image.open(f) # 等比缩放 if img.width > max_width: ratio = max_width / img.width img = img.resize((max_width, int(img.height * ratio)), Image.LANCZOS) name = os.path.splitext(os.path.basename(f))[0] out = os.path.join(output_dir, name + '.jpg') img.convert('RGB').save(out, 'JPEG', quality=quality, optimize=True) orig_size = os.path.getsize(f) new_size = os.path.getsize(out) print(f'{name}: {orig_size//1024}KB -> {new_size//1024}KB ({(1-new_size/orig_size)*100:.0f}%减少)')

适配环境

依赖环境:Python 3.7+,需安装Pillow

使用说明

1.安装Python 3.7+
2.pip install Pillow
3.保存为compress_images.py
4.将图片放在images文件夹
5.python compress_images.py 运行
JPG质量设75-85平衡画质和体积
PNG建议转WebP减小体积
可以设置最大宽度自动缩放
保留原图,压缩后输出到新文件夹
支持递归子文件夹

常见问题

问:压缩后画质损失大吗?
答:质量85以上肉眼几乎看不出差异,体积可减少50%

问:支持WebP吗?
答:支持,可以直接输出WebP格式

Python图片压缩批量PillowWebP网站优化免费

更多其他