?????????将某个目录下的所有图片文件压缩至另一文件夹,指定压缩后的最大文件大小,指定宽度,自适应高度进行压缩,压缩失败的文件提示后直接拷贝原始图片至压缩文件夹。
import os
import shutil
from PIL import Image
def get_size(file):
# 获取大小KB
size = os.path.getsize(file)
return int(size / 1024)
def get_outfile(infile, outfile):
if outfile:
return outfile
dir, suffix = os.path.splitext(infile)
outfile = '{}-out{}'.format(dir, suffix)
return outfile
#mb输出图片最大大小KB,x_s输出图片的宽度,高自适应
def compress_image(infile, outfile='', mb=300, step=10, quality=85,x_s=900):
o_size = get_size(infile)
# print("imageSize",o_size)
outfile = get_outfile(infile, outfile)
if o_size <= mb:
im = Image.open(infile)
im.save(outfile, quality=100)
return infile,get_size(infile)
while o_size > mb:
im = Image.open(infile)
width, height = im.size
y_s = int(height*x_s/width)
# width, height = round(width * 0.8), round(height * 0.8)
im = im.resize((x_s, y_s), Image.ANTIALIAS)
im.save(outfile, optimize=True, quality=quality)
if quality - step < 0:
break
quality -= step
o_size = get_size(outfile)
return outfile, get_size(outfile)
def compressImage(srcpath, dstpath):
for filename in os.listdir(srcpath):
if not os.path.exists(dstpath):
os.makedirs(dstpath)
srcfile = os.path.join(srcpath, filename)
dstfile = os.path.join(dstpath, filename)
# 筛选图片文件
if (os.path.isfile(srcfile) and (
filename.upper().endswith('.JPG') or filename.upper().endswith('.BMP')
or filename.upper().endswith('.PNG')
or filename.upper().endswith('.GIF')
or filename.upper().endswith('.JPEG')
)):
try:
outfile,size = compress_image(srcfile, dstfile)
# print(dstfile + " success! ",size)
except Exception as re:
print(dstfile + " error!")
print(re)
try:
shutil.copyfile(srcfile, dstfile) # 压缩失败将原始文件复制过来
except Exception as r:
print("copy error: ",re)
if os.path.isdir(srcfile):
compressImage(srcfile, dstfile)
pwd = os.getcwd() #获取脚本所在目录
print("pwd:", pwd)
srcPath = os.path.join(pwd, "pic\\2022") # 图片所在目录
print("srcPath:", srcPath)
dstPath = os.path.join(pwd, "pic\\2022"+"_copy") # 压缩后的图片存放目录
print("target:", dstPath)
compressImage(srcPath, dstPath) # 运行压缩
|