【问题标题】:How to resize images in a folder and save it to another folder in Python?如何调整文件夹中的图像大小并将其保存到 Python 中的另一个文件夹?
【发布时间】:2022-11-30 05:18:51
【问题描述】:

我有一个图像文件夹。我调整了此文件夹中每个图像的大小,并想将调整后的图像保存到不同的文件夹中。以下是我的代码:

import glob
import os

new_folder = '/new/folder/of/images/'
for file in [x for x in glob.glob('/existing/folder/of/images/*.jpg')]:
        im = Image.open(file)
        img = im.convert('RGB')
        new_img = img.resize((500,500))
        new_img.save(os.path.join(new_folder, file +'_resized'+'.jpg'), 'JPEG', optimize=True)

图像会调整大小。但是,调整大小后的图像保存在与原始图像相同的文件夹中,而不是我想要的 new_folder 中。我的代码有问题吗?

【问题讨论】:

    标签: image resize


    【解决方案1】:

    这是我的代码 `

    from PIL import Image
    import os
    
    
    def scale(naziv,h,w):
        image = Image.open(naziv)
        resized = image.resize((w, h))
        i=naziv.split('\')
        name=i[-1].split('.')
        print(name[0])
        resized.save('C:\Path\Of\New\File\'+name[0]+'-copy.jpg')# Add to new file image u wont to save
    
    
    def main():
    
        dir_path = "C:\Put\File\Path\Here" #file u want o take pictures from
        res = []
    
        os.mkdir("C:\Make\new\File\Here",0o666)#write the full path of new file(with name of file)
    
        for path in os.listdir(dir_path):
            # check if the current path is a file
            if os.path.isfile(os.path.join(dir_path, path)):
                res.append(path)
                scale(dir_path+"\"+path,321,208) 
       
        
    
    main()
    

    `

    【讨论】:

      猜你喜欢
      • 2015-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-10
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      相关资源
      最近更新 更多