用python写一个图片质量压缩的脚本
时间: 2024-06-12 10:06:00 浏览: 146
以下是一个基于Pillow库的图片质量压缩脚本:
```python
from PIL import Image
import os
def compress_image(image_path, quality):
"""
压缩图片质量
:param image_path: 图片路径
:param quality: 压缩质量,取值范围0-100
"""
with Image.open(image_path) as img:
img.save(image_path, quality=quality)
def compress_images_in_folder(folder_path, quality):
"""
压缩文件夹中所有图片的质量
:param folder_path: 文件夹路径
:param quality: 压缩质量,取值范围0-100
"""
for filename in os.listdir(folder_path):
if filename.endswith(".jpg") or filename.endswith(".png"):
image_path = os.path.join(folder_path, filename)
compress_image(image_path, quality)
if __name__ == '__main__':
folder_path = "path/to/folder"
quality = 50
compress_images_in_folder(folder_path, quality)
```
使用时,将`path/to/folder`替换为要压缩图片的文件夹路径,将`quality`替换为要压缩到的质量值(取值范围为0-100),然后运行脚本即可。脚本会自动扫描指定文件夹中的所有图片,对它们的质量进行压缩。
阅读全文