The goal is to convert any images in a given directory to png and then add them to a new directory. I can't seem to find a way to save the images to the directory I want using the PIL save function: var.save().
Here is the code
from PIL import Image
import sys
import os
file = sys.argv[1]
output_file = sys.argv[2]
if not os.path.exists(output_file):
os.makedirs(output_file)
i = 0
for _ in os.listdir(file):
img = Image.open(f'./{file}/{os.listdir(file)[i]}')
img.save(f"{os.listdir(file)[i]}.png", "png")
i +=1
I searched up this, looked all over stack overflow, yet for some stupid reason, I am unable to find a function or something like that to change where I save it to.
The issue with your code seems to be related to the file paths used in the save function. When you're saving the images, you're not specifying the output directory in the path. This causes the images to be saved in the current working directory instead of the desired output directory. Try something like this:
from PIL import Image
import sys
import os
input_directory = sys.argv[1]
output_directory = sys.argv[2]
if not os.path.exists(output_directory):
os.makedirs(output_directory)
for filename in os.listdir(input_directory):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
img = Image.open(os.path.join(input_directory, filename))
# Create a new filename for the PNG version
new_filename = os.path.splitext(filename)[0] + ".png"
# Save the image in the output directory
img.save(os.path.join(output_directory, new_filename), "PNG")