from PIL import Image
import os
def convert_images_to_jpeg(input_folder, output_folder, max_size=(1200, 1200), quality=80):
# Create the output folder if it does not exist
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Iterate over all files in the input folder
for filename in os.listdir(input_folder):
# Construct the full file path
file_path = os.path.join(input_folder, filename)
# Check if it is a file
if os.path.isfile(file_path):
try:
# Open the image file
with Image.open(file_path) as img:
# Maintain aspect ratio while resizing
img.thumbnail(max_size)
# Create the output file path with .jpeg extension
output_file_path = os.path.join(output_folder, os.path.splitext(filename)[0] + '.jpeg')
# Save the image in JPEG format with specified quality
img.save(output_file_path, 'JPEG', quality=quality)
print(f"Converted {filename} to {output_file_path}")
except Exception as e:
print(f"Failed to convert {filename}: {e}")
# Specify the input and output folders
input_folder = 'path/to/your/input_folder'
output_folder = 'path/to/your/output_folder'
# Convert all images in the input folder
convert_images_to_jpeg(input_folder, output_folder)