jmunsch

python: resize image to max

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