gifduration 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. """
  4. This script takes one or more animated GIF files as input and calculates their
  5. total durations, returning zero for non-animated GIF files.
  6. Requires Pillow, formerly known as the Python Imaging Library (PIL).
  7. Code by Markus Amalthea Magnuson <markus@polyscopic.works>
  8. """
  9. from __future__ import print_function
  10. import getopt
  11. import os.path
  12. import sys
  13. from PIL import Image, ImageSequence
  14. help_message = """
  15. Supply one or more animated GIF files as input to get their total durations.
  16. """
  17. class Usage(Exception):
  18. def __init__(self, msg):
  19. self.msg = msg
  20. def main(argv=None):
  21. if argv is None:
  22. argv = sys.argv
  23. try:
  24. try:
  25. opts, args = getopt.getopt(argv[1:], "h:v", ["help", "verbose"])
  26. except getopt.error as err:
  27. raise Usage(err.msg)
  28. # Option processing.
  29. verbose = False
  30. for option, value in opts:
  31. if option in ("-v", "--verbose"):
  32. verbose = True
  33. if option in ("-h", "--help"):
  34. raise Usage(help_message)
  35. except Usage as err:
  36. print(sys.argv[0].split("/")[-1] + ": " + str(err.msg), file=sys.stderr)
  37. print("\t for help use --help", file=sys.stderr)
  38. return 2
  39. # Start processing the images.
  40. for path in args:
  41. try:
  42. im = Image.open(path)
  43. except IOError as err:
  44. print("%s:" % os.path.basename(path), file=sys.stderr)
  45. print(err, file=sys.stderr)
  46. print("---", file=sys.stderr)
  47. continue
  48. durations = []
  49. for frame in ImageSequence.Iterator(im):
  50. try:
  51. durations.append(frame.info["duration"])
  52. except KeyError:
  53. # Ignore if there was no duration, we will not count that frame.
  54. pass
  55. if not durations:
  56. print("Not an animated GIF image")
  57. else:
  58. if verbose:
  59. for index, duration in enumerate(durations):
  60. print(
  61. "Frame %d: %d ms (%0.2f seconds)"
  62. % (index + 1, duration, duration / 1000.0)
  63. )
  64. total_duration = sum(durations)
  65. print(
  66. "Total duration: %d ms (%0.2f seconds)"
  67. % (total_duration, total_duration / 1000.0)
  68. )
  69. print("---")
  70. if __name__ == "__main__":
  71. sys.exit(main())