optimize_images.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. '.svg': ('svgo {flags} --input="{filename}" --output="{filename}"', '--quiet', ''),
  20. '.jpg': ('jpegtran {flags} -copy none -optimize -outfile "{filename}" "{filename}"', '', '-v'),
  21. '.png': ('optipng {flags} "{filename}"', '--quiet', ''),
  22. }
  23. def optimize_images(pelican):
  24. """
  25. Optimized jpg and png images
  26. :param pelican: The Pelican instance
  27. """
  28. for dirpath, _, filenames in os.walk(pelican.settings['OUTPUT_PATH']):
  29. for name in filenames:
  30. if os.path.splitext(name)[1] in COMMANDS.keys():
  31. optimize(dirpath, name)
  32. def optimize(dirpath, filename):
  33. """
  34. Check if the name is a type of file that should be optimized.
  35. And optimizes it if required.
  36. :param dirpath: Path of the file to be optimzed
  37. :param name: A file name to be optimized
  38. """
  39. filepath = os.path.join(dirpath, filename)
  40. logger.info('optimizing %s', filepath)
  41. ext = os.path.splitext(filename)[1]
  42. command, silent, verbose = COMMANDS[ext]
  43. flags = verbose if SHOW_OUTPUT else silent
  44. command = command.format(filename=filepath, flags=flags)
  45. call(command, shell=True)
  46. def register():
  47. signals.finalized.connect(optimize_images)