python批量压缩图片到指定大小

作者 :
免费
  • 正文
  • 有些系统设定不允许超过200KB图片上传,本例将图片压缩到200KB(大小可以自行设定),使用了python pillow包,如果没有的话需要先安装pip install pillow(执行报错则卸载在重新安装)。如果一个图片已经压缩到指定大小了,那就停止压缩,如果没有达到指定大小,那就对压缩后的图片再进行压缩,直到压缩到自定范围内。做了10个进程处理,速度飞快。

    使用方法:保存代码si.py,执行python si.py 图片文件夹,会生成output压缩好的图片,error文件夹是压缩失败的,template文件夹

    注:将所有要压缩的图片都放在一个文件夹下,然后每个图片的格式只能是下面三种:png,jpg, jpeg。如果是PNG也不行。因为PNG是png的大写。

    python批量压缩图片到指定大小-完美源码

    from PIL import Image
    from glob import glob
    import os
    from tqdm import tqdm
    import shutil
    import sys
    from itertools import chain
    from multiprocessing import Pool
    # image_dir = "image_dir"
    template_dir = 'template'
    output_dir = 'output'
    error_dir = 'error'
    def clean_dir(dir_name):
    if os.path.exists(dir_name):
    shutil.rmtree(dir_name)
    os.makedirs(dir_name)
    else:
    os.makedirs(dir_name)
    # image_file_list = glob(f"{image_dir}/*")
    # image_file_list
    def imagesize(filepath):
    """
    获得文件的磁盘大小
    :param filepath:
    :return:
    """
    return os.path.getsize(filepath) / 1024
    def compress_image(image_path):
    raw_image = Image.open(image_path)
    temp_image_name = image_path.split(os.sep)[-1]
    template_image = os.path.join(template_dir, temp_image_name)
    output_image = os.path.join(output_dir, temp_image_name)
    error_image = os.path.join(error_dir, temp_image_name)
    target_size = 200# kb
    try:
    if imagesize(image_path) < target_size:
    shutil.copyfile(image_path, output_image)
    else:
    width, height = raw_image.size
    raw_image.resize((int(width * 0.9), int(height * 0.9)),
    Image.ANTIALIAS).save(template_image)
    while imagesize(template_image) > target_size:
    template_iamge2 = Image.open(template_image)
    width_2, height_2 = template_iamge2.size
    template_iamge2.resize(
    (int(width_2 * 0.9), int(height_2 * 0.9)), Image.ANTIALIAS).save(template_image)
    shutil.copyfile(template_image, output_image)
    except Exception as e:
    shutil.copyfile(image_path, error_image)
    print(f'文件保存失败: {image_path}')
    # print(e)
    if __name__ == '__main__':
    # 批量创建文件夹
    [clean_dir(i) for i in [template_dir, output_dir, error_dir]]
    image_dir = sys.argv[1]
    image_file_list = list(
    chain(*[glob(os.path.join(image_dir, i)) for i in ['*.png', '*.jpg', '*.jpeg']]))
    # for temp_image_path in tqdm(image_file_list):
    # compress_image(temp_image_path)
    print(f'\n\n文件保存父目录: {os.getcwd()}\n'
    f'输出文件位置:{os.path.join(os.getcwd(), output_dir)}\n\n')
    # parallel
    P = Pool(processes=10)
    pbar = tqdm(total=len(image_file_list))
    res_temp = [P.apply_async(func=compress_image, args=(i,), callback=lambda _: pbar.update(1)) for i in
    image_file_list]

    _ = [res.get() for res in res_temp]

    微信登录 下载 是编译好的exe 独立环境 可以直接使用。

    END
    如本资源侵犯了您的权益,请联系投诉邮箱admin@wmphp.com进行举报!我们将在收到邮件的1个小时内处理完毕。 本站仅为平台,发布的资源均为用户投稿或转载!所有资源仅供参考学习使用,请在下载后的24小时内删除,禁止商用! Wmphp.com(完美源码)助力正版,如您有自己的原创产品,可以联系客服投稿,代理出售! Wmphp.com(完美源码)客服QQ:136882447 Wmphp.com(完美源码)商务电话(仅对企业客户/个人用户):15120086569 (微信同步) 请注意:本站不提供任何免费的技术咨询服务,为了节约时间,下载前 请确认自己会技术
    完美源码 » python批量压缩图片到指定大小
    3493+

    本站勉强运行

    3673+

    用户总数

    690+

    资源总数

    0+

    今日更新

    2024-4-8

    最后更新时间