我正在尝试创建一个程序,它将目录中的任何图像调整为 299x299。然后,我想重命名该图像并将其转换为 jpeg,以便将所有图像命名为 0.jpg、1.jpg、2.jpg 等。我还想将转换后的文件移动到自己的目录.
我已经解决了它的调整大小部分。但是,当我添加重命名代码时,即 (index = 0, new_image.save)file_name, str(index), + ".jpg"和 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
关于python - 在 python 中重命名、调整大小和移动图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45286315/