包是pillow. 限制图片的短边像素数,长边等比缩小。所有图片放入一个目录,运行,输入该目录即可。
from PIL import Image
import os
import pathlib
Image.MAX_IMAGE_PIXELS = 2800000000 #增大pillow的像素限制
path = input('请输入路径:')
if not os.path.exists(path):
print('路径不存在!')
else:
leng = input('请输入最小边宽度:')
dirlist = os.walk(path)
new_path = os.path.dirname(path) + "/new/" # new文件夹存放转换后的图片,保留原图。
if not os.path.exists(new_path):
os.makedirs(new_path)
for root,dirs,files in dirlist:
for f in files:
full_path = os.path.join(root,f)
p = pathlib.Path(full_path)
image = Image.open(full_path)
width = image.width
height = image.height
if width < height:
if width > int(leng):
t_height = int(image.height*(int(leng)/image.width))
resized_image = image.resize((int(leng), t_height))
else:
resized_image = image #未缩放的图片也放入新目录
#continue
elif width > height:
if height > int(leng):
t_width = int(image.width * (int(leng)/image.height))
resized_image = image.resize((t_width, int(leng)))
else:
resized_image = image
#continue
resized_image.save(new_path + p.name)