按原始名称保存调整大小的图片列表

我有我在python中调整过的图片列表。有什么方法可以将原尺寸重新调整尺寸的图片保存到新文件夹中?我已经尝试过,但是现在将它们重命名为“ filename1,filename2 ....”

from PIL import Image
import glob 
from natsort import natsorted 

new_width = 300 
new_height = 300

images = [] 
resized = [] 



for filename in natsorted(glob.glob('Pictures/*.jpg')):
    print(filename) 

    img = Image.open(filename) 

    images.append(img)

for image in images: 

    image=image.resize((new_height,new_width)) 

    resized.append(image)  



for(i,new) in enumerate(resized):

    new.save('{}{}{}'.format('resize/filename', i + 1, '.jpg'))  
评论
  • 若弱C
    若弱C 回复

    You need to save the filenames somewhere. I save them in a list of tuples (filename, resized_image) This code example does what you want:

    from PIL import Image
    import glob 
    from natsort import natsorted 
    
    new_width = 300 
    new_height = 300
    
    resized = [] 
    
    for filename in natsorted(glob.glob('Pictures/*.jpg')):
        print(filename) 
    
        img = Image.open(filename) 
        img_resized = img.resize((new_height, new_width)) 
    
        resized.append((filename, img_resized))  
    
    for (filename, new) in resized:
    
        new.save(filename)