Python 如何将图片保存到不同的目录?

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)

我想保存新图片到

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

不是

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

任何帮助将不胜感激!

您可以通过更改 img_resize.save() 的参数将已处理的图像保存到您的首选目录 (/Users/mac/PycharmProjects/crop001/1/11/*.jpg)。

假设您仍想保存已处理的图像,并在其文件名中添加 _half 后缀。所以最后的代码在这里:

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)

我在这里使用的所有函数的文档都可以在这里找到: