You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
2.4 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. #!/usr/bin/python2.7
  2. from __future__ import division
  3. import os, sys
  4. from PIL import Image
  5. from PIL import ImageEnhance
  6. import argparse
  7. CROP_DEFAULT = 'default'
  8. CROP_WHITESPACE = 'whitespace'
  9. parser = argparse.ArgumentParser()
  10. parser.add_argument("--width", type=int)
  11. parser.add_argument("--height", type=int)
  12. parser.add_argument("--crop", choices=[CROP_WHITESPACE, CROP_DEFAULT])
  13. parser.add_argument("--enhance", action="store_true")
  14. parser.add_argument("source", type=str)
  15. parser.add_argument("destination", type=str)
  16. args = parser.parse_args()
  17. infile = args.source
  18. outfile = args.destination
  19. try:
  20. im = Image.open(infile)
  21. format = im.format
  22. im = im.convert()
  23. if args.width is not None or args.height is not None:
  24. if args.width is None:
  25. if args.crop and args.crop == CROP_WHITESPACE:
  26. size = (int(im.size[0]), args.height)
  27. else:
  28. size = (int(im.size[0] * args.height / im.size[1]), args.height)
  29. elif args.height is None:
  30. if args.crop and args.crop == CROP_WHITESPACE:
  31. size = (args.width, int(im.size[1]))
  32. else:
  33. size = (args.width, int(im.size[1] * args.width / im.size[0]))
  34. else:
  35. size = (args.width, args.height)
  36. if args.crop:
  37. if args.crop == CROP_DEFAULT:
  38. width_crop = im.size[0]
  39. height_crop = int(im.size[0]/(size[0]/size[1]))
  40. x = 0
  41. y = int((im.size[1]-height_crop)/2)
  42. if height_crop > im.size[1]:
  43. width_crop = int(im.size[1]/(size[1]/size[0]))
  44. height_crop = im.size[1]
  45. x = int((im.size[0]-width_crop)/2)
  46. y = 0
  47. im = im.crop((x, y, width_crop+x, height_crop+y))
  48. im.thumbnail(size, Image.ANTIALIAS)
  49. if args.crop == CROP_WHITESPACE:
  50. im_whitespace = Image.new('RGB', (size[0], size[1]), (255, 255, 255))
  51. im_whitespace.paste(im, ((size[0] - im.size[0]) // 2, (size[1] - im.size[1]) // 2))
  52. im = im_whitespace
  53. else:
  54. im.thumbnail(size, Image.ANTIALIAS)
  55. if args.enhance:
  56. enhancer = ImageEnhance.Contrast(im)
  57. im = enhancer.enhance(1.05)
  58. im.save(outfile, format, quality=100)
  59. except IOError as e:
  60. print("cannot create thumbnail for '%s'" % infile)
  61. print "I/O error({0}): {1}".format(e.errno, e.strerror)
  62. sys.exit(os.EX_DATAERR)