Search code examples
imageresize

How to resize images in a folder and save it to another folder in Python?


I have a folder of images. I resize each image in this folder and want to save the resized image to a different folder. The following is my code:

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)

The images get resized. However, the resized images are being saved in the same folder as the original images, and not in the new_folder as I want. Is there something wrong in my code?


Solution

  • this worked for me :) i used it to resize and rescale the images

    import glob
    from skimage import io
    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)