import os
from PIL import Image

def optimize_images(directory):
    # Define the folder for optimized images
    optimized_dir = os.path.join(directory, "otimizados")
    os.makedirs(optimized_dir, exist_ok=True)

    # Iterate through all files in the directory
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)

        # Check if the file is a .png image
        if filename.lower().endswith(".png") and os.path.isfile(file_path):
            try:
                # Open the image
                with Image.open(file_path) as img:
                    # Reduce dimensions and optimize compression
                    img = img.convert("RGBA")  # Ensure compatibility with PNG transparency

                    # Reduce image size by resizing (e.g., 50% of original dimensions)
                    width, height = img.size
                    img = img.resize((width // 2, height // 2))

                    # Save the optimized image with maximum compression
                    optimized_path = os.path.join(optimized_dir, filename)
                    img.save(optimized_path, format="PNG", optimize=True)
                    print(f"Optimized: {filename}")
            except Exception as e:
                print(f"Failed to optimize {filename}: {e}")

if __name__ == "__main__":
    # Get the directory from the user
    directory = input("Enter the directory containing .png images: ").strip()

    if os.path.isdir(directory):
        optimize_images(directory)
        print("Optimization complete. Check the 'otimizados' folder.")
    else:
        print("Invalid directory. Please enter a valid path.")
