#!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
Author: be_loving@163.com
Date: 2023-06-26 20:13:21
LastEditors: be_loving@163.com
LastEditTime: 2023-06-26 21:28:50
Description:
Copyright (c) 2023 Jiulu LTD, All Rights Reserved.
'''
# pip install Pillow
import os
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
for root, dirs, files in os.walk(".", topdown=False):
for name in files:
if name.endswith(".jpg") or name.endswith(".jpeg") or name.endswith(".png") or name.endswith(".tif"):
img_path = os.path.join(root, name)
print(img_path)
if img_path.count('_144') > 1:
os.remove(img_path)
elif img_path.count('_144') == 0:
new_img_path = os.path.join(
root, f"{name}_144.jpg")
print(new_img_path)
if not os.path.isfile(new_img_path):
try:
with Image.open(img_path) as img:
img.save(new_img_path, dpi=(144, 144))
except(OSError, NameError):
print('OSError,Path:', img_path)
# for name in dirs:
# print(os.path.join(root, name))
具体压缩参数及文件命名方式请自己参照pillow的文档修改。
脚本运行时可执行
python ./resize.py
但需要当前的python环境支持pillow,可以直接安装,也可以用conda来定制环境,比如在conda create命令下安装pillow之后用conda activate pillow激活该环境。