Python批量压缩图片

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)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值