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.

61 lines
2.4 KiB

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. im = im.convert()
  22. if args.width is not None or args.height is not None:
  23. if args.width is None:
  24. if args.crop and args.crop == CROP_WHITESPACE:
  25. size = (int(im.size[0]), args.height)
  26. else:
  27. size = (int(im.size[0] * args.height / im.size[1]), args.height)
  28. elif args.height is None:
  29. if args.crop and args.crop == CROP_WHITESPACE:
  30. size = (args.width, int(im.size[1]))
  31. else:
  32. size = (args.width, int(im.size[1] * args.width / im.size[0]))
  33. else:
  34. size = (args.width, args.height)
  35. if args.crop:
  36. if args.crop == CROP_DEFAULT:
  37. width_crop = im.size[0]
  38. height_crop = int(im.size[0]/(size[0]/size[1]))
  39. x = 0
  40. y = int((im.size[1]-height_crop)/2)
  41. if height_crop > im.size[1]:
  42. width_crop = int(im.size[1]/(size[1]/size[0]))
  43. height_crop = im.size[1]
  44. x = int((im.size[0]-width_crop)/2)
  45. y = 0
  46. im = im.crop((x, y, width_crop+x, height_crop+y))
  47. im.thumbnail(size, Image.ANTIALIAS)
  48. if args.crop == CROP_WHITESPACE:
  49. im_whitespace = Image.new('RGB', (size[0], size[1]), (255, 255, 255))
  50. im_whitespace.paste(im, ((size[0] - im.size[0]) // 2, (size[1] - im.size[1]) // 2))
  51. im = im_whitespace
  52. else:
  53. im.thumbnail(size, Image.ANTIALIAS)
  54. if args.enhance:
  55. enhancer = ImageEnhance.Contrast(im)
  56. im = enhancer.enhance(1.05)
  57. im.save(outfile, "JPEG", quality=100)
  58. except IOError:
  59. print("cannot create thumbnail for '%s'" % infile)
  60. sys.exit(os.EX_DATAERR)