|
| 1 | +from PIL import Image |
| 2 | +import os |
| 3 | + |
| 4 | +def get_size_format(b, factor=1024, suffix="B"): |
| 5 | + """ |
| 6 | + Scale bytes to its proper byte format. |
| 7 | + e.g: 1253656 => '1.20MB', 1253656678 => '1.17GB' |
| 8 | + """ |
| 9 | + for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]: |
| 10 | + if b < factor: |
| 11 | + return f"{b:.2f}{unit}{suffix}" |
| 12 | + b /= factor |
| 13 | + return f"{b:.2f}Y{suffix}" |
| 14 | + |
| 15 | +def compress_img(image_name, new_size_ratio=0.9, quality=90, width=None, height=None, to_jpg=True): |
| 16 | + try: |
| 17 | + # Load the image into memory |
| 18 | + img = Image.open(image_name) |
| 19 | + |
| 20 | + # Print the original image shape |
| 21 | + print("[*] Image shape:", img.size) |
| 22 | + |
| 23 | + # Get the original image size in bytes |
| 24 | + image_size = os.path.getsize(image_name) |
| 25 | + print("[*] Size before compression:", get_size_format(image_size)) |
| 26 | + |
| 27 | + if width and height: |
| 28 | + # If width and height are set, resize with them instead |
| 29 | + img = img.resize((width, height), Image.LANCZOS) |
| 30 | + elif new_size_ratio < 1.0: |
| 31 | + # If resizing ratio is below 1.0, multiply width & height with this ratio to reduce image size |
| 32 | + img = img.resize((int(img.size[0] * new_size_ratio), int(img.size[1] * new_size_ratio)), Image.LANCZOS) |
| 33 | + |
| 34 | + # Split the filename and extension |
| 35 | + filename, ext = os.path.splitext(image_name) |
| 36 | + |
| 37 | + # Make a new filename appending "_compressed" to the original file name |
| 38 | + if to_jpg: |
| 39 | + # Change the extension to JPEG |
| 40 | + new_filename = f"{filename}_compressed.jpg" |
| 41 | + # Ensure image is in RGB mode for JPEG |
| 42 | + if img.mode in ("RGBA", "LA"): |
| 43 | + img = img.convert("RGB") |
| 44 | + else: |
| 45 | + # Retain the same extension of the original image |
| 46 | + new_filename = f"{filename}_compressed{ext}" |
| 47 | + |
| 48 | + # Save the compressed image |
| 49 | + img.save(new_filename, optimize=True, quality=quality) |
| 50 | + |
| 51 | + # Print the new image shape |
| 52 | + print("[+] New Image shape:", img.size) |
| 53 | + |
| 54 | + # Get the new image size in bytes |
| 55 | + new_image_size = os.path.getsize(new_filename) |
| 56 | + print("[*] Size after compression:", get_size_format(new_image_size)) |
| 57 | + print(f"[*] Compressed image saved as: {new_filename}") |
| 58 | + |
| 59 | + except FileNotFoundError: |
| 60 | + print("Error: The file was not found.") |
| 61 | + except OSError as e: |
| 62 | + print(f"Error: {e}") |
| 63 | + |
| 64 | +# Example usage: |
| 65 | +input_image = input("Enter the path to the image: ") |
| 66 | +compress_img(input_image, new_size_ratio=0.8, quality=80, width=800, height=600) |
0 commit comments