我正在设计一个Python脚本,调整大小大于10 MB的图像文件[.png、.jpeg、.jpg]的所有目录和子目录的大小。我参考了以下链接调整目录所有子目录中的所有图像大小进行设计。
但是,我得到的结果是“无法调整 C:\intersteller\StaticFileBasePath .jpg 的大小。正在跳过。”在 jupyter 笔记本中运行时。
我可以寻求您的帮助来确定我的脚本中的根本原因吗?
from PIL import Image
import os, sys
import PIL
import glob
dir_path = r'C:\intersteller\StaticFileBasePath'
def resize_im(path):
for foldername, subfolders, photos in os.walk(dir_path):
for filename in photos:
if filename.endswith(('jpeg', 'jpg', 'png')) and os.path.getsize(os.path.join(foldername, filename))>10000000:
print(foldername + '\\' + filename)
parent_dir = os.path.dirname(dir_path)
img_name = os.path.basename(dir_path).split('.')[0]
img_extension = os.path.basename(dir_path).split('.')[1]
if img_extension.upper() not in ['PNG', 'JPG', 'JPEG']:
print('invalid extension >>', img_extension)
return
img = Image.open(dir_path);
width, height = img.size;
asp_rat = width/height;
# Enter new width (in pixels)
new_width = 2775;
# Enter new height (in pixels)
new_height = 3700;
new_asp_rat = new_width/new_height;
if (new_asp_rat == asp_rat):
img = img.resize((new_width, new_height), Image.ANTIALIAS);
# adjusts the height to match the width
# NOTE: if you want to adjust the width to the height, instead ->
# uncomment the second line (new_width) and comment the first one (new_height)
else:
new_height = round(new_width / asp_rat);
#new_width = round(new_height * asp_rat);
img = img.resize((new_width, new_height), Image.ANTIALIAS);
if img_extension.upper() == 'PNG':
print('png deteced')
img.save(os.path.join(parent_dirm + 'new', img_name + 'resized.png'), 'PNG', quality=50)
else:
img.save(os.path.join(parent_dirm + 'new', img_name + 'resized.jpeg'), 'JPEG', quality=50)
def resize_all(mydir):
for foldername, subfolders, photos in os.walk(dir_path):
for filename in photos:
if filename.endswith(('jpeg', 'jpg', 'png')) and os.path.getsize(os.path.join(foldername, filename))>10000000:
try:
full_path = os.path.join(foldername, filename)
resize_im(full_path)
except Exception as e:
print('Unable to resize %s. Skipping.' % full_path)
if __name__ == '__main__':
resize_all(dir_path)
结果: C:\intersteller\StaticFileBasePath .jpg 无法调整 C:\intersteller\StaticFileBasePath .jpg 的大小。跳绳。 C:\intersteller\StaticFileBasePath .jpg 无法调整 C:\intersteller\StaticFileBasePath .jpg 的大小。跳过。
非常感谢
获取 dir_path 的大小调整
要在此代码中查找问题的根本原因,您可能需要打印
resize_all
函数中发生的异常。
将以下代码片段添加到您的代码中:
except Exception as e:
print('Unable to resize %s. Skipping.' % full_path)
print('Got error:', e)
这将使您能够看到错误到底是什么。这些附加信息可能会帮助您解决问题。