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.

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