1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| import os
from PIL import Image
def find_files(root = None, exts={".png", ".jpg"}):
if not root:
root = os.path.abspath(".")
for rootdir, dirs, files in os.walk(root):
for f in files:
if os.path.splitext(f)[1] in exts:
yield os.path.join(root, rootdir), f
def run_resize(path, f, new=False):
org_file = os.path.join(path, f)
if new:
new_file = "_thumb".join(os.path.splitext(org_file))
else:
new_file = org_file
print("Resizing", org_file, "to", new_file)
try:
im = Image.open(org_file)
width, height = im.size
size = width/4, height/4
im.thumbnail(size, Image.ANTIALIAS)
im.save(new_file)
except Exception as e:
print("Error while trying to resize", org_file, "!\n ", e)
def resize_all():
for path, f in find_files():
yield run_resize, (path, f)
if __name__ == "__main__":
for call, elem in resize_all():
call(*elem) |
Partager