|
| 1 | +""" |
| 2 | +
|
| 3 | +Convert images in folder to thumbnails using concurrent futures |
| 4 | +
|
| 5 | +""" |
| 6 | + |
| 7 | +import os |
| 8 | +import sys |
| 9 | +from PIL import Image |
| 10 | +from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed |
| 11 | +import mimetypes |
| 12 | + |
| 13 | +def thumbnail_image(filename, size=(64,64), format='.png'): |
| 14 | + """ Convert image thumbnails, given a filename """ |
| 15 | + |
| 16 | + try: |
| 17 | + im=Image.open(filename) |
| 18 | + im.thumbnail(size, Image.ANTIALIAS) |
| 19 | + |
| 20 | + basename = os.path.basename(filename) |
| 21 | + thumb_filename = os.path.join('thumbs', |
| 22 | + basename.rsplit('.')[0] + '_thumb.png') |
| 23 | + im.save(thumb_filename) |
| 24 | + print('Saved',thumb_filename) |
| 25 | + return True |
| 26 | + |
| 27 | + except Exception as e: |
| 28 | + print('Error converting file',filename) |
| 29 | + print(e) |
| 30 | + return False |
| 31 | + |
| 32 | +def directory_walker(start_dir): |
| 33 | + """ Walk a directory and generate list of valid images """ |
| 34 | + |
| 35 | + for root,dirs,files in os.walk(os.path.expanduser(start_dir)): |
| 36 | + for f in files: |
| 37 | + filename = os.path.join(root,f) |
| 38 | + # Only process if its a type of image |
| 39 | + file_type = mimetypes.guess_type(filename.lower())[0] |
| 40 | + if file_type != None and file_type.startswith('image/'): |
| 41 | + yield filename |
| 42 | + |
| 43 | +if __name__ == '__main__': |
| 44 | + root_dir = os.path.expanduser('~/Pictures/') |
| 45 | + if '--process' in sys.argv: |
| 46 | + executor = ProcessPoolExecutor(max_workers=10) |
| 47 | + else: |
| 48 | + executor = ThreadPoolExecutor(max_workers=10) |
| 49 | + |
| 50 | + with executor: |
| 51 | + future_map = {executor.submit(thumbnail_image, filename): filename for filename in directory_walker(root_dir)} |
| 52 | + for future in as_completed(future_map): |
| 53 | + num = future_map[future] |
| 54 | + status = future.result() |
| 55 | + if status: |
| 56 | + print('Thumbnail of',future_map[future],'saved') |
| 57 | + |
| 58 | + |
| 59 | + |
| 60 | + |
0 commit comments