Python批量压缩图片
代码如下
可支持压缩指定单张图片,单个文件夹,多个文件夹,可根据自己实际场景的需求扩展丰富。话不多说,上代码。
# @Time : 2021/10/14 9:16
import os
import sys
from PIL import Image
import glob
class CompressImage(object):
def __init__(self, width=120, height=160):
self.width = width
self.height = height
self.errors = {}
def run_compress_image(self, image_path):
"""压缩图片"""
try:
# 打开原图片压缩
sImg = Image.open(image_path)
dImg = sImg.resize((self.width, self.height), Image.ANTIALIAS) # 设置压缩尺寸和选项,注意尺寸要用括号
dImg.save(image_path)
print("Compress success: {}".format(image_path))
except Exception as e:
self.errors[os.path.basename(image_path)] = {
"file": image_path,
"message": str(e),
}
def run_compress_image_from_dir(self, dir):
if not os.path.exists(dir):
raise Exception("Error image directory")
for file in glob.glob(os.path.join(dir, '*.png')):
self.run_compress_image(file)
def run(self, file=None, dir=None, dirs=None, img_format=None):
"""
压缩图片
:param file: 图片地址
:param dir: 图片所在目录
:param dirs: 图片所在目录,多个目录
:param img_format: 图片格式,默认.png
:return:
"""
img_format = img_format or ".png"
if file is not None:
if not os.path.isfile(file) or os.path.splitext(file)[1] != img_format:
raise Exception("Error image file")
self.run_compress_image(file)
elif dir is not None:
self.run_compress_image_from_dir(dir)
elif dirs is not None:
if not isinstance(dirs, list):
raise Exception("Error image directories")
for idir in dirs:
self.run_compress_image_from_dir(idir)
else:
# 参数均无,默认是当前的文件夹下操作
self.run_compress_image_from_dir(os.path.abspath(os.path.dirname(__file__)))
if self.errors:
for file, msg in self.errors.items():
print("File:{} compress failed: {}".format(file, msg))
else:
print("Compress success")
if __name__ == "__main__":
try:
# CompressImage().run_compress_image(sys.argv[1])
CompressImage().run(dir=sys.argv[1])
# CompressImage().run()
# CompressImage().run(file=r"D:\Desktop\interactive_contract_review\utils\test.png")
# CompressImage().run(dir=r"D:\Desktop\interactive_contract_review\utils")
# CompressImage().run(dirs=[r"D:\Desktop\interactive_contract_review\utils"])
except IndexError as e:
raise Exception("Missing script parameter: folder path needed")
except BaseException as e:
raise Exception(e)