【python】图片批量压缩脚本

# -*- coding: utf-8 -*-

'''
图片批量压缩脚本
将脚本放入待压缩文件夹下,并运行
自动生成压缩文件夹compress
'''

from PIL import Image
import os
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')


def compress_image(input_image_path, output_image_path, size):
    try:
        original_image = Image.open(input_image_path)
        width, height = original_image.size
        new_width, new_height = size

        if width > height:
            new_height = int(height * (new_width / width))
        else:
            new_width = int(width * (new_height / height))

        resized_image = original_image.resize((new_width, new_height), Image.ANTIALIAS)
        resized_image.save(output_image_path)
    except OSError as e:
        print(f"无法打开图片文件:{e}")
    
def read_file():
    input_file_path = input("请输入需要压缩的文件夹路径:")
    
    if not os.path.exists(input_file_path):
        print('待压缩文件夹不存在!')
        return 0;
      
    output_root_path = './compress/';
    if not os.path.exists(output_root_path):
        os.mkdir(output_root_path)
    
    input_last_path = input_file_path.split('/')[-1];
    output_file_path = output_root_path+input_last_path+'/';
    if os.path.exists(output_file_path):
        print('压缩文件夹'+output_file_path+'已存在!')
        return 0;
    else:
        os.mkdir(output_file_path)
    
    files = os.listdir(input_file_path)
    
    image_exts = ['.jpg', '.jpeg', '.png']
    compress_size = (400, 400)
    for index,file in enumerate(files):
        ext = os.path.splitext(file)[1].lower()
        if ext in image_exts:
            output_image_path = output_file_path+file
            input_image_path = input_file_path+'/'+file
            
            print(f"{index}"+':'+file)
            #print(input_image_path)                   
            #print(output_image_path)              
            compress_image(input_image_path,output_image_path,compress_size);
    print(input_last_path+'总文件:'+f"{len(files)}")
read_file();



  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值