Advertisement
Guest User

recursive_resize.py

a guest
Jul 19th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.16 KB | None | 0 0
  1.  
  2. # Ryan Burnside, force resize all JPGs in directory
  3.  
  4. import multiprocessing as mp
  5. from glob import iglob
  6. import os
  7. from PIL import Image
  8. from time import time
  9. import argparse
  10. import logging
  11.  
  12.  
  13. #Args for commandline use
  14. MAX_WIDTH = 2048
  15. MAX_HEIGHT = 2048
  16. BYTES_PER_MB = 1048576
  17. BYTE_SKIP_THRESHOLD = BYTES_PER_MB * .2
  18. STARTING_PATH = "."
  19. NO_PROMPT = False
  20.  
  21. parser = argparse.ArgumentParser()
  22. parser.add_argument("--directory", type=str,
  23.                     help="Set start directory. No trailing slash.",
  24.                     default = ".")
  25. parser.add_argument("--width", type=int,
  26.                     help="Set max width.",
  27.                     default = MAX_WIDTH)
  28. parser.add_argument("--height", type=int,
  29.                     help="Set max height.",
  30.                     default = MAX_HEIGHT)
  31. parser.add_argument("--ignore-below", type=int,
  32.                     help="Set ignore byte threshold.",
  33.                     default=BYTE_SKIP_THRESHOLD)
  34. parser.add_argument("--no-prompt", help="Run without prompting.",
  35.                     action="store_true")
  36. args = parser.parse_args()
  37.  
  38. logging.basicConfig(filename='ConvertLog.txt',level=logging.WARNING)
  39.  
  40. def assign_args():
  41.     global STARTING_PATH
  42.     global BYTE_SKIP_THRESHOLD
  43.     global MAX_WIDTH
  44.     global MAX_HEIGHT
  45.     global NO_PROMPT
  46.    
  47.     BYTE_SKIP_THRESHOLD = args.ignore_below
  48.     MAX_WIDTH = args.width
  49.     MAX_HEIGHT = args.height
  50.     STARTING_PATH = args.directory
  51.     NO_PROMPT = args.no_prompt
  52.  
  53. def promptYN(question):
  54.     while True:
  55.         a = input(question)
  56.         if a.upper() in ("YES", "Y"):
  57.             return True
  58.         if a.upper() in ("NO", "N"):
  59.             return False
  60.    
  61. def resize_pic(name):
  62.     try:
  63.         if os.path.getsize(name) > BYTE_SKIP_THRESHOLD:
  64.             im = Image.open(name)
  65.             im.thumbnail((MAX_WIDTH, MAX_HEIGHT))
  66.             im.save(name, "JPEG")
  67.     except Exception as e:
  68.         logging.warning(e)
  69.         logging.warning(F"Error working with file {name}. Continuing on ...")
  70.         print(e)
  71.         print(F"Error working with file {name}. Continuing on ...")
  72.  
  73. def dummy(name):
  74.     print(name)
  75.  
  76.  
  77.  
  78. if __name__ == '__main__':
  79.     multiprocessing.freeze_support() # MUST BE CALLED HERE FOR WINDOWS
  80.     assign_args()
  81.  
  82.     # See if their path is even valid
  83.     if not os.path.isdir(STARTING_PATH):
  84.         print(F"Path: {STARTING_PATH} is not valid. " +
  85.               "(Did you need to strip trailing slashes?)")
  86.         exit()
  87.        
  88.     # start worker processes
  89.     CPUS = mp.cpu_count()
  90.     pool = mp.Pool(CPUS)
  91.     files = iglob(F"{STARTING_PATH}/**/*.JPG", recursive = True)
  92.    
  93.     print(F"Starting recursive conversions in {STARTING_PATH} .")
  94.     print(F"Will attempt to use {CPUS} concurrent processes.")
  95.     print(F"Image restraints: {MAX_WIDTH} x {MAX_HEIGHT}")
  96.     print(F"Size restraints: {BYTE_SKIP_THRESHOLD} bytes.")
  97.  
  98.     if not NO_PROMPT:
  99.         if not promptYN("Begin? Y/N: "):
  100.             exit()
  101.    
  102.     start_time = time()
  103.     pool.map(resize_pic, files)
  104.     pool.close()
  105.     end_time = time()
  106.    
  107.     print("Ending conversions")
  108.     print(F"Took {(end_time - start_time) / 60.0} Minutes")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement