# -*- 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();
【python】图片批量压缩脚本
于 2023-12-10 16:19:15 首次发布