from PIL import Image
def compress_image(image_path, output_path, max_size): """Compresses an image file to a specified max size in bytes.""" # Open the image with Image.open(image_path) as image: # Get the original image size original_size = image.size # Calculate the compression ratio compression_ratio = max_size / (original_size[0] * original_size[1]) # Resize the image based on the compression ratio image.thumbnail((original_size[0] * compression_ratio, original_size[1] * compression_ratio)) # Save the compressed image image.save(output_path) print(f"Image compressed successfully! Output image saved at {output_path}") # Example usage: image_path = "example.jpg" # Path to the input image output_path = "example_compressed.jpg" # Path to save the compressed image max_size = 1024 * 1024 # Maximum size in bytes (1 MB) compress_image(image_path, output_path, max_size)