|
| 1 | +""" |
| 2 | +Comprass images using ImageMagick |
| 3 | +
|
| 4 | +Command used to compress images: |
| 5 | +python compress_images.py --quality 30 --replace_original --pattern "../assets/images/author_images/*" |
| 6 | +""" |
| 7 | + |
| 8 | + |
| 9 | +import argparse |
| 10 | +import glob |
| 11 | +import os |
| 12 | +import subprocess |
| 13 | + |
| 14 | + |
| 15 | +SIZE_THRESHOLD = 25 |
| 16 | +# Version: ImageMagick 6.9.7-4 Q16 x86_64 20170114 http://www.imagemagick.org |
| 17 | +IMAGEMAGICK_COMMAND = r'convert -sampling-factor 4:2:0 -strip -interlace JPEG -colorspace RGB' |
| 18 | + |
| 19 | + |
| 20 | +def compress_image(image_path, quality, replace_original=False): |
| 21 | + # Image size in Kilobytes |
| 22 | + image_size = os.path.getsize(image_path) / 1000 |
| 23 | + if image_size > SIZE_THRESHOLD: |
| 24 | + print(f"Compressing image '{image_path}' ({image_size}K)") |
| 25 | + if replace_original: |
| 26 | + new_path = image_path |
| 27 | + else: |
| 28 | + file_name, extension = os.path.basename(image_path).split(".") |
| 29 | + new_file_name = file_name + "_reduced." + extension |
| 30 | + new_path = os.path.join(os.path.dirname(image_path), new_file_name) |
| 31 | + subprocess.run(f"{IMAGEMAGICK_COMMAND} -quality {quality}% {image_path} {new_path}", shell=True) |
| 32 | + print(f">>> New file created: '{new_path}'") |
| 33 | + else: |
| 34 | + print(f"The image '{image_path}' ({image_size}K) does not need compression.") |
| 35 | + |
| 36 | + |
| 37 | +if __name__ == "__main__": |
| 38 | + parser = argparse.ArgumentParser(description="Script to compress images using ImageMagick.") |
| 39 | + parser.add_argument("--quality", help="compression level", type=int, default=50) |
| 40 | + parser.add_argument("--replace_original", help="replace original image with compressed one", action='store_true') |
| 41 | + group = parser.add_mutually_exclusive_group(required=True) |
| 42 | + group.add_argument("--file_path", help="image file path", action="append", type=str) |
| 43 | + group.add_argument("--pattern", help="glob pattern for images", type=str) |
| 44 | + args = parser.parse_args() |
| 45 | + print(f"Compressing images with size greater than {SIZE_THRESHOLD}K.") |
| 46 | + |
| 47 | + if args.file_path: |
| 48 | + print(args.file_path) |
| 49 | + for p in args.file_path: |
| 50 | + if os.path.exists(p): |
| 51 | + compress_image(p, args.quality, args.replace_original) |
| 52 | + else: |
| 53 | + print(f"ERROR: The file '{p}' does not exists.") |
| 54 | + else: |
| 55 | + paths = glob.glob(args.pattern) |
| 56 | + for p in paths: |
| 57 | + compress_image(p, args.quality, args.replace_original) |
0 commit comments