如何在Python中调整文件夹中的图像大小并将其保存到另一个文件夹?

问题描述 投票:0回答:2

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

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
2个回答
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()

`


0
投票
from PIL import Image
resized_path = r'path/to/new_folder'
ones_path =  r'path\from\folder\*'
for file in glob.glob(ones_path):
   img = io.imread(file)
   img = tf.image.resize(img,size = [255,255])/255.
   tf.keras.utils.save_img(resized_path+file[13:],img)
© www.soinside.com 2019 - 2024. All rights reserved.