import os
from PIL import Image
def compress_image(infile, outfile):
try:
with Image.open(infile) as im:
im.save(outfile, 'JPEG', quality=70)
except OSError:
print("Cannot convert", infile)
def batch_compress_image(input_dir, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
files = os.listdir(input_dir)
valid_images = [".jpg", ".jpeg", ".png", ".gif"]
for file in files:
extension = os.path.splitext(file)[1]
if extension.lower() in valid_images:
infile = os.path.join(input_dir, file)
outfile = os.path.join(output_dir, file)
compress_image(infile, outfile)
source = "//ShareFolderE/"
files_list = os.listdir(source)
for files in files_list:
input_dir="//ShareFolderE/"+files
print(input_dir)
batch_compress_image(input_dir, input_dir)
文章评论