Compresses an image by reducing its quality. Args: image_path (str): Path to the image file. quality (int): Quality of the output image (1-100). Default is 60.
(image_path, quality=60)
| 3 | from PIL import Image |
| 4 | |
| 5 | def compress_image(image_path, quality=60): |
| 6 | """ |
| 7 | Compresses an image by reducing its quality. |
| 8 | |
| 9 | Args: |
| 10 | image_path (str): Path to the image file. |
| 11 | quality (int): Quality of the output image (1-100). Default is 60. |
| 12 | """ |
| 13 | try: |
| 14 | # Open the image |
| 15 | with Image.open(image_path) as img: |
| 16 | # Check if file is an image |
| 17 | if img.format not in ["JPEG", "PNG", "JPG"]: |
| 18 | print(f"Skipping {image_path}: Not a standard image format.") |
| 19 | return |
| 20 | |
| 21 | # Create output filename |
| 22 | filename, ext = os.path.splitext(image_path) |
| 23 | output_path = f"{filename}_compressed{ext}" |
| 24 | |
| 25 | # Save with reduced quality |
| 26 | # Optimize=True ensures the encoder does extra work to minimize size |
| 27 | img.save(output_path, quality=quality, optimize=True) |
| 28 | |
| 29 | # Calculate savings |
| 30 | original_size = os.path.getsize(image_path) |
| 31 | new_size = os.path.getsize(output_path) |
| 32 | savings = ((original_size - new_size) / original_size) * 100 |
| 33 | |
| 34 | print(f"[+] Compressed: {output_path}") |
| 35 | print(f" Original: {original_size/1024:.2f} KB") |
| 36 | print(f" New: {new_size/1024:.2f} KB") |
| 37 | print(f" Saved: {savings:.2f}%") |
| 38 | |
| 39 | except Exception as e: |
| 40 | print(f"[-] Error compressing {image_path}: {e}") |
| 41 | |
| 42 | if __name__ == "__main__": |
| 43 | if len(sys.argv) < 2: |