import os
import shutil
import time
from time import sleep
from PIL import Image
from tqdm import tqdm
def makeDirs(path):
# 创建新的输出子目录,若存在输出该目录则删除该目录及其子文件夹和文件
if os.path.exists(path):
shutil.rmtree(path)
os.mkdir(path)
def resizePics(size):
# default_path=os.getcwd()##设置默认打开目录,即当前目录
# default_path = "/pics"
inpath = os.getcwd()
outdir = os.path.basename(inpath)+‘-resize‘
outpath = os.path.join(os.path.dirname(inpath), outdir)
makeDirs(outpath)
# 列出所在目录下的所有目录和文件
lists = os.listdir(inpath)
starttime = time.time()
for i in tqdm(range(0, len(lists))):
subdir = lists[i]
subpath = inpath+"/"+subdir # 子目录路径
if os.path.isdir(subpath):
outsubdir = subdir+‘-resize‘
outsubpath = os.path.join(outpath, outsubdir)
makeDirs(outsubpath)
# 对文件夹下的照片文件调整大小
# 列出某个子目录下的所有文件和目录
flists = os.listdir(subpath)
for j in tqdm(range(0, len(flists))):
sleep(0.01)
fname = flists[j]
fpath = subpath+"/"+fname
if os.path.isfile(fpath):
resizeSinglePic(fname, fpath, outsubpath)
passtime = time.time()-starttime
print(‘照片压缩完毕,总共花费了 %f s‘ % (passtime))
def resizeSinglePic(fname, fpath, outsubpath):
fbasename = os.path.basename(fpath)
fext = os.path.splitext(fpath)[-1]
if fext in img_ext:
img = Image.open(fpath)
img.thumbnail(size)
outfile = outsubpath+"/"+fbasename
img.save(outfile)
img_ext = [‘.bmp‘, ‘.jpeg‘, ‘.JPEG‘,‘.gif‘, ‘.psd‘, ‘.png‘, ‘.JPG‘, ‘.jpg‘]
size = (800, 600)
resizePics(size)