简体   繁体   中英

Python How to save image to different directory?

import os
import glob
from PIL import Image

files = glob.glob('/Users/mac/PycharmProjects/crop001/1/*.jpg')

for f in files:
    img = Image.open(f)
    img_resize = img.resize((int(img.width / 2), int(img.height / 2)))
    title, ext = os.path.splitext(f)
    img_resize.save(title + '_half' + ext)

I want to save new images to

"/Users/mac/PycharmProjects/crop001/1/11/*.jpg" 

Not

"/Users/mac/PycharmProjects/crop001/1/*.jpg"

Any help will be appreciated!

You can save your processed images to your preferred directory ( /Users/mac/PycharmProjects/crop001/1/11/*.jpg ) by changing the parameter for img_resize.save() there.

Assuming that you still want to save the processed image with _half suffix in its filename. So the final code goes here:

import os
import glob
from PIL import Image

files = glob.glob('/Users/mac/PycharmProjects/crop001/1/*.jpg')
DESTINATION_PATH = '/Users/mac/PycharmProjects/crop001/1/11/'  # The preferred path for saving the processed image

for f in files:
    img = Image.open(f)
    img_resize = img.resize((int(img.width / 2), int(img.height / 2)))

    base_filename = os.path.basename(f)
    title, ext = os.path.splitext(base_filename)
    final_filepath = os.path.join(DESTINATION_PATH, title + '_half' + ext)

    img_resize.save(final_filepath)

All of the function's docs I used here can be found here:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM