[英]Resize all images in all sub-directories of directory
我有一个结构如下的目录:
├── 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)
将调整大小的图像保存在源图像的同一目录中时要小心。 如果你运行你的代码两次,它会创建很多额外调整大小的图像。
我拼凑了@Tu Bui 和其他人关于堆栈溢出的答案来生成这个,它还保持纵横比
from PIL import Image
import os, sys
dir_path = "/Users/tawanda/Downloads/images"
def resize_im(path):
if os.path.isfile(path):
parent_dir = os.path.dirname(path)
img_name = os.path.basename(path).split('.')[0]
img_extension = os.path.basename(path).split('.')[1]
if img_extension.upper() not in ['PNG', 'JPG', 'JPEG']:
print('invalid extension >>', img_extension)
return
img = Image.open(path);
width, height = img.size;
asp_rat = width/height;
# Enter new width (in pixels)
new_width = 900;
# Enter new height (in pixels)
new_height = 900;
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 detected')
img.save(os.path.join(parent_dir, img_name + '_resized.png'), 'PNG', quality=90)
else:
img.save(os.path.join(parent_dir, img_name + '_resized.jpg'), 'JPEG', quality=90)
print(f'resized {img_name}.{img_extension}')
os.remove(path)
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.