|
| 1 | +import fnmatch |
| 2 | +import os |
| 3 | + |
| 4 | +# sudo pip install Wand |
| 5 | +from wand.image import Image |
| 6 | +# sudo pip install http://pypi.python.org/packages/source/h/hurry.filesize/hurry.filesize-0.9.tar.gz |
| 7 | +from hurry.filesize import size |
| 8 | + |
| 9 | + |
| 10 | +# constants |
| 11 | +PATH = '/../../../..' |
| 12 | +PATTERN = '*.jpg' |
| 13 | + |
| 14 | + |
| 15 | +def get_image_file_names(filepath, pattern): |
| 16 | + matches = [] |
| 17 | + if os.path.exists(filepath): |
| 18 | + for root, dirnames, filenames in os.walk(filepath): |
| 19 | + for filename in fnmatch.filter(filenames, pattern): |
| 20 | + matches.append(os.path.join(root, filename)) # full path |
| 21 | + if matches: |
| 22 | + print "Found {} files, with a total file size of {}.".format(len(matches), get_total_size(matches)) |
| 23 | + return matches |
| 24 | + else: |
| 25 | + print "No files found." |
| 26 | + else: |
| 27 | + print "Sorry that path does not exist. Try again." |
| 28 | + |
| 29 | + |
| 30 | +def get_total_size(list_of_image_names): |
| 31 | + total_size = 0 |
| 32 | + for image_name in list_of_image_names: |
| 33 | + total_size += os.path.getsize(image_name) |
| 34 | + return size(total_size) |
| 35 | + |
| 36 | + |
| 37 | +def resize_images(list_of_image_names): |
| 38 | + print "Optimizing ... " |
| 39 | + for index, image_name in enumerate(list_of_image_names): |
| 40 | + with open(image_name) as f: |
| 41 | + image_binary = f.read() |
| 42 | + with Image(blob=image_binary) as img: |
| 43 | + if img.height >= 600: |
| 44 | + img.transform(resize='x600') |
| 45 | + img.save(filename=image_name) |
| 46 | + print "Optimization complete." |
| 47 | + |
| 48 | + |
| 49 | +if __name__ == '__main__': |
| 50 | + all_images = get_image_file_names(PATH, PATTERN) |
| 51 | + resize_images(all_images) |
| 52 | + get_image_file_names(PATH, PATTERN) |
0 commit comments