Advertisement
Guest User

Untitled

a guest
Oct 13th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import os
  3. import sys
  4. import argparse
  5. from PIL import Image
  6.  
  7. """
  8. Reduce images size
  9. Images are resized keeping the aspect ratio
  10. Usage: python image_resize.py -d /home/images -o /home/output_dir -s 1024 768
  11. """
  12.  
  13. def resizeImage(infile, output_dir, size):
  14. outfile = os.path.splitext(os.path.basename(infile))[0]
  15. extension = os.path.splitext(infile)[1]
  16.  
  17. if (cmp(extension, ".jpg")):
  18. return
  19.  
  20. if infile != outfile:
  21. try:
  22. im = Image.open(infile)
  23. im.thumbnail(size, Image.ANTIALIAS)
  24. im.save(os.path.join(output_dir, outfile+extension),"JPEG")
  25. except IOError:
  26. print "cannot reduce image for ", infile
  27.  
  28.  
  29. if __name__=="__main__":
  30.  
  31. parser = argparse.ArgumentParser()
  32. parser.add_argument("-d", help="Directory to look up for images")
  33. parser.add_argument("-o", help="Output directory")
  34. parser.add_argument("-s", nargs=2, type=int, help="Output size")
  35. args = parser.parse_args()
  36.  
  37. input_dir = os.path.normpath(args.d) if args.d else os.getcwd()
  38. output_dir = os.path.normpath(args.o) if args.o else os.path.join(os.getcwd(), 'resized')
  39. output_size = tuple(args.s) if args.s else (1024,768)
  40.  
  41. if not os.path.exists(output_dir):
  42. os.mkdir(output_dir)
  43.  
  44. for file in os.listdir(input_dir):
  45. resizeImage(os.path.join(input_dir, file), output_dir, output_size)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement