optimize_images.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # -*- coding: utf-8 -*-
  2. """
  3. Optimized images (jpg and png)
  4. Assumes that jpegtran and optipng are isntalled on path.
  5. http://jpegclub.org/jpegtran/
  6. http://optipng.sourceforge.net/
  7. Copyright (c) 2012 Irfan Ahmad (http://i.com.pk)
  8. """
  9. import logging
  10. import os
  11. from subprocess import call
  12. from pelican import signals
  13. logger = logging.getLogger(__name__)
  14. # Display command output on DEBUG and TRACE
  15. SHOW_OUTPUT = logger.getEffectiveLevel() <= logging.DEBUG
  16. # A list of file types with their respective commands
  17. COMMANDS = {
  18. # '.ext': ('command {flags} {filename', 'silent_flag', 'verbose_flag')
  19. '.jpg': ('jpegtran {flags} -copy none -optimize -outfile "{filename}" "{filename}"', '', '-v'),
  20. '.png': ('optipng {flags} "{filename}"', '--quiet', ''),
  21. }
  22. def optimize_images(pelican):
  23. """
  24. Optimized jpg and png images
  25. :param pelican: The Pelican instance
  26. """
  27. for dirpath, _, filenames in os.walk(pelican.settings['OUTPUT_PATH']):
  28. for name in filenames:
  29. if os.path.splitext(name)[1] in COMMANDS.keys():
  30. optimize(dirpath, name)
  31. def optimize(dirpath, filename):
  32. """
  33. Check if the name is a type of file that should be optimized.
  34. And optimizes it if required.
  35. :param dirpath: Path of the file to be optimzed
  36. :param name: A file name to be optimized
  37. """
  38. filepath = os.path.join(dirpath, filename)
  39. logger.info('optimizing %s', filepath)
  40. ext = os.path.splitext(filename)[1]
  41. command, silent, verbose = COMMANDS[ext]
  42. flags = verbose if SHOW_OUTPUT else silent
  43. command = command.format(filename=filepath, flags=flags)
  44. call(command, shell=True)
  45. def register():
  46. signals.finalized.connect(optimize_images)