|
| 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 | + # Load the image into memory |
| 17 | + img = Image.open(image_name) |
| 18 | + |
| 19 | + # Print the original image shape |
| 20 | + print("[*] Image shape:", img.size) |
| 21 | + |
| 22 | + # Get the original image size in bytes |
| 23 | + image_size = os.path.getsize(image_name) |
| 24 | + print("[*] Size before compression:", get_size_format(image_size)) |
| 25 | + |
| 26 | + if new_size_ratio < 1.0: |
| 27 | + # If resizing ratio is below 1.0, multiply width & height with this ratio to reduce image size |
| 28 | + img = img.resize((int(img.size[0] * new_size_ratio), int(img.size[1] * new_size_ratio)), Image.ANTIALIAS) |
| 29 | + elif width and height: |
| 30 | + # If width and height are set, resize with them instead |
| 31 | + img = img.resize((width, height), Image.ANTIALIAS) |
| 32 | + |
| 33 | + # Split the filename and extension |
| 34 | + filename, ext = os.path.splitext(image_name) |
| 35 | + |
| 36 | + # Make a new filename appending "_compressed" to the original file name |
| 37 | + if to_jpg: |
| 38 | + # Change the extension to JPEG |
| 39 | + new_filename = f"{filename}_compressed.jpg" |
| 40 | + else: |
| 41 | + # Retain the same extension of the original image |
| 42 | + new_filename = f"{filename}_compressed{ext}" |
| 43 | + |
| 44 | + # Save the compressed image |
| 45 | + img.save(new_filename, optimize=True, quality=quality) |
| 46 | + |
| 47 | + # Print the new image shape |
| 48 | + print("[+] New Image shape:", img.size) |
| 49 | + print(f"[*] Compressed image saved as: {new_filename}") |
| 50 | + |
| 51 | +# Example usage: |
| 52 | +compress_img("wp1966881.jpg", new_size_ratio=0.8, quality=80, width=800, height=600) |
0 commit comments