python批量压缩图片大小
时间: 2023-07-03 12:30:32 浏览: 52
可以使用Python的Pillow库来批量压缩图片大小。以下是一个简单的示例代码:
```python
from PIL import Image
import os
# 定义要压缩的图片路径
image_path = 'path/to/images'
# 定义压缩后的图片保存路径
output_path = 'path/to/compressed/images'
# 定义压缩后的图片质量(0-100),数值越小压缩比越大
quality = 50
# 获取图片路径下的所有图片文件
image_files = os.listdir(image_path)
# 遍历所有图片文件
for image_file in image_files:
# 拼接图片路径
image_file_path = os.path.join(image_path, image_file)
# 打开图片
with Image.open(image_file_path) as img:
# 获取图片文件名(不包含扩展名)
file_name = os.path.splitext(image_file)[0]
# 压缩图片
img.save(os.path.join(output_path, f'{file_name}_compressed.jpg'), optimize=True, quality=quality)
```
在上述代码中,我们首先定义了要压缩的图片路径、压缩后的图片保存路径和压缩后的图片质量。然后使用`os.listdir()`函数获取图片路径下的所有图片文件,遍历所有图片文件,使用Pillow库中的`Image.open()`函数打开图片文件,使用`Image.save()`函数将压缩后的图片保存到指定路径中。