在 python 中重命名、调整大小和移动图像文件

Renaming, resizing, and moving image files in python

我正在尝试创建一个程序,将目录中的任何图像调整为 299x299。然后,我想重命名该图像并将其转换为 jpeg,以便所有图像都被命名​​为 0.jpg、1.jpg、2.jpg 等。我还想移动将文件转换到自己的目录。

我已经解决了它的调整大小部分。但是,当我添加重命名代码时,即 (index = 0, new_image.save)file_name, str(index), + ".jpg", and index += 1),调整大小部分没有更长的作品。有人有什么建议吗?

这是我目前所拥有的:

#!usr/bin/python

from PIL import Image
import os, sys

directory = sys.argv[1]
for file_name in os.listdir(directory):
        print ("Converting %s" % file_name + "...")
        image = Image.open(os.path.join(directory, file_name))

        size = 299, 299
        image.thumbnail(size, Image.ANTIALIAS)

        w, h = image.size

        new_image = Image.new('RGBA', size, (255, 255, 255, 255))
        new_image.paste(image, ((299 - w) / 2, (299 - h) / 2))

        index = 0

        new_image_file_name = os.path.join(directory, file_name)
        new_image.save(file_name, str(index) + ".jpg")

        index += 1

print ("Conversion process complete.")

来自documentation

Image.save(fp, format=None, **params)

Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible.

image.save 的正确语法是:

new_image.save(file_name, 'JPG')

要移动文件,您可以使用shutil.move:

import shutil
shutil.move(file_name, 'full/path/to/dst/') # the second argument can be a directory