Python 调整目录的所有子目录中的所有图像的大小
我有一个目录,其结构如下:Python 调整目录的所有子目录中的所有图像的大小,python,python-3.x,Python,Python 3.x,我有一个目录,其结构如下: ├── directory | ├── sub-directory_1 | | ├── img1.jpg | | └── img2.jpg | | | ├── sub-directory_2 | | ├── img1.jpg | | └── img2.jpg . . . . . . . | └── sub-directo
├── directory
| ├── sub-directory_1
| | ├── img1.jpg
| | └── img2.jpg
| |
| ├── sub-directory_2
| | ├── img1.jpg
| | └── img2.jpg
. .
. .
. .
.
| └── sub-directory_n
| | ├── img1.jpg
| | └── img2.jpg
我有以下代码可以调整目录中所有图像的大小:
from PIL import Image
import os, sys
path = "/directory"
dirs = os.listdir( path )
def resize():
for item in dirs:
if os.path.isfile(path+item):
im = Image.open(path+item)
f, e = os.path.splitext(path+item)
imResize = im.resize((64,64), Image.ANTIALIAS)
imResize.save(f + 'r.jpg', 'JPEG', quality=90)
resize()
是否有一种方法可以修改它,以便它迭代地调整子目录中所有图像的大小?这是否符合要求
from PIL import Image
import os, sys
dir_path = "/directory"
def resize_im(path):
if os.path.isfile(path):
im = Image.open(path).resize((64,64), Image.ANTIALIAS)
parent_dir = os.path.dirname(path)
img_name = os.path.basename(path).split('.')[0]
im.save(os.path.join(parent_dir, img_name + 'r.jpg'), 'JPEG', quality=90)
def resize_all(mydir):
for subdir , _ , fileList in os.walk(mydir):
for f in fileList:
try:
full_path = os.path.join(subdir,f)
resize_im(full_path)
except Exception as e:
print('Unable to resize %s. Skipping.' % full_path)
if __name__ == '__main__':
resize_all(dir_path)
将调整大小的图像保存在源图像的同一目录中时要小心。如果您运行代码两次,它将创建大量额外的大小调整图像。使用而不是。您也可以考虑只使用具有指定扩展名的文件。在任何一种情况下,在生成所有名称之前都要小心,以确保不会无限期地迭代新创建的文件。