jmunsch

Python: Recursive Image Resize

Aug 6th, 2014
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.11 KB | None | 0 0
  1. import imghdr, os
  2. from PIL import Image
  3.  
  4. directory = 'C:/Users/UserBob/Desktop/RANDOM/pages'
  5.  
  6. # recursively resize images with python
  7. for root, dirs, files in os.walk(directory):
  8.     for image in files:
  9.         fp = os.path.join(root,image)
  10.         try:
  11.             # if file is image
  12.             if imghdr.what(fp) is not None:
  13.                 with open('fn','a+') as f:
  14.                     f.write(fp+'\n')
  15.                 im = Image.open(fp)
  16.                 if (im.size[0] < 500) or (im.size[1] < 500):
  17.                     #find the coeffecient to scale smallest edge to 550
  18.                     width = 550 / float(im.size[0])
  19.                     height = 550 / float(im.size[1])            
  20.                     ratio = max(width, height)
  21.                     width = int(float(im.size[0]) * ratio)
  22.                     height = int(float(im.size[1]) * ratio)
  23.                     #NEAREST for upsizing, antialias for downsizing
  24.                     resized_image = im.resize((width, height), Image.NEAREST)
  25.                     resized_image.save(fp, format='JPEG')
  26.         except Exception, e:
  27.             print(e)
Advertisement
Add Comment
Please, Sign In to add comment