I am trying to create a program that will resize any image in a directory to 299x299. Then, I want to rename that image and convert it to a jpeg, so that all of the images will be named 0.jpg, 1.jpg, 2.jpg, etc. I also want to move the converted files to their own directory.
I have already solved the resizing portion of it. However, when I added the code for renaming, i.e. (index = 0, new_image.save)file_name, str(index), + ".jpg", and index += 1), the resizing portion no longer works. Does anyone have any suggestions?
This is what I have so far:
from PIL import Image
import os, sys
directory = sys.argv
for file_name in os.listdir(directory):
print ("Converting %s" % file_name + "...")
image = Image.open(os.path.join(directory, file_name))
size = 299, 299
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.")
From the 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.
The correct syntax for
To move a file, you can use
import shutil shutil.move(file_name, 'full/path/to/dst/') # the second argument can be a directory