thumbnailer.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import os
  2. import os.path as path
  3. import re
  4. from pelican import signals
  5. import logging
  6. logger = logging.getLogger(__name__)
  7. try:
  8. from PIL import Image, ImageOps
  9. enabled = True
  10. except ImportError:
  11. logging.warning("Unable to load PIL, disabling thumbnailer")
  12. enabled = False
  13. DEFAULT_IMAGE_DIR = "pictures"
  14. DEFAULT_THUMBNAIL_DIR = "thumbnails"
  15. DEFAULT_THUMBNAIL_SIZES = {
  16. 'thumbnail_square': '150',
  17. 'thumbnail_wide': '150x?',
  18. 'thumbnail_tall': '?x150',
  19. }
  20. DEFAULT_TEMPLATE = """<a href="{url}" rel="shadowbox" title="{filename}"><img src="{thumbnail}" alt="{filename}"></a>"""
  21. DEFAULT_GALLERY_THUMB = "thumbnail_square"
  22. class _resizer(object):
  23. """ Resizes based on a text specification, see readme """
  24. REGEX = re.compile(r'(\d+|\?)x(\d+|\?)')
  25. def __init__(self, name, spec):
  26. self._name = name
  27. self._spec = spec
  28. def _null_resize(self, w, h, image):
  29. return image
  30. def _exact_resize(self, w, h, image):
  31. retval = ImageOps.fit(image, (w,h), Image.BICUBIC)
  32. return retval
  33. def _aspect_resize(self, w, h, image):
  34. retval = image.copy()
  35. retval.thumbnail((w, h), Image.ANTIALIAS)
  36. return retval
  37. def resize(self, image):
  38. resizer = self._null_resize
  39. # Square resize and crop
  40. if 'x' not in self._spec:
  41. resizer = self._exact_resize
  42. targetw = int(self._spec)
  43. targeth = targetw
  44. else:
  45. matches = self.REGEX.search(self._spec)
  46. tmpw = matches.group(1)
  47. tmph = matches.group(2)
  48. # Full Size
  49. if tmpw == '?' and tmph == '?':
  50. targetw = image.size[0]
  51. targeth = image.size[1]
  52. resizer = self._null_resize
  53. # Set Height Size
  54. if tmpw == '?':
  55. targetw = image.size[0]
  56. targeth = int(tmph)
  57. resizer = self._aspect_resize
  58. # Set Width Size
  59. elif tmph == '?':
  60. targetw = int(tmpw)
  61. targeth = image.size[1]
  62. resizer = self._aspect_resize
  63. # Scale and Crop
  64. else:
  65. targetw = int(tmpw)
  66. targeth = int(tmph)
  67. resizer = self._exact_resize
  68. logging.debug("Using resizer {0}".format(resizer.__name__))
  69. return resizer(targetw, targeth, image)
  70. def get_thumbnail_name(self, in_path):
  71. new_filename = path.basename(in_path)
  72. (basename, ext) = path.splitext(new_filename)
  73. basename = "{0}_{1}".format(basename, self._name)
  74. new_filename = "{0}{1}".format(basename, ext)
  75. return new_filename
  76. def resize_file_to(self, in_path, out_path):
  77. """ Given a filename, resize and save the image per the specification into out_path
  78. :param in_path: path to image file to save. Must be supposed by PIL
  79. :param out_path: path to the directory root for the outputted thumbnails to be stored
  80. :return: None
  81. """
  82. filename = path.join(out_path, self.get_thumbnail_name(in_path))
  83. if not path.exists(out_path):
  84. os.makedirs(out_path)
  85. if not path.exists(filename):
  86. image = Image.open(in_path)
  87. thumbnail = self.resize(image)
  88. thumbnail.save(filename)
  89. logger.info("Generated Thumbnail {0}".format(path.basename(filename)))
  90. def resize_thumbnails(pelican):
  91. """ Resize a directory tree full of images into thumbnails
  92. :param pelican: The pelican instance
  93. :return: None
  94. """
  95. global enabled
  96. if not enabled:
  97. return
  98. in_path = _image_path(pelican)
  99. out_path = path.join(pelican.settings['OUTPUT_PATH'],
  100. pelican.settings.get('THUMBNAIL_DIR', DEFAULT_THUMBNAIL_DIR))
  101. sizes = pelican.settings.get('THUMBNAIL_SIZES', DEFAULT_THUMBNAIL_SIZES)
  102. resizers = dict((k, _resizer(k, v)) for k,v in sizes.items())
  103. logger.debug("Thumbnailer Started")
  104. for dirpath, _, filenames in os.walk(in_path):
  105. for filename in filenames:
  106. for name, resizer in resizers.items():
  107. in_filename = path.join(dirpath, filename)
  108. logger.debug("Processing thumbnail {0}=>{1}".format(filename, name))
  109. resizer.resize_file_to(in_filename, out_path)
  110. def _image_path(pelican):
  111. return path.join(pelican.settings['PATH'],
  112. pelican.settings.get("IMAGE_PATH", DEFAULT_IMAGE_DIR))
  113. def expand_gallery(generator, metadata):
  114. """ Expand a gallery tag to include all of the files in a specific directory under IMAGE_PATH
  115. :param pelican: The pelican instance
  116. :return: None
  117. """
  118. if "gallery" not in metadata or metadata['gallery'] is None:
  119. return # If no gallery specified, we do nothing
  120. lines = [ ]
  121. base_path = _image_path(generator)
  122. in_path = path.join(base_path, metadata['gallery'])
  123. template = generator.settings.get('GALLERY_TEMPLATE', DEFAULT_TEMPLATE)
  124. thumbnail_name = generator.settings.get("GALLERY_THUMBNAIL", DEFAULT_GALLERY_THUMB)
  125. thumbnail_prefix = generator.settings.get("")
  126. resizer = _resizer(thumbnail_name, '?x?')
  127. for dirpath, _, filenames in os.walk(in_path):
  128. for filename in filenames:
  129. url = path.join(dirpath, filename).replace(base_path, "")[1:]
  130. url = path.join('/static', generator.settings.get('IMAGE_PATH', DEFAULT_IMAGE_DIR), url).replace('\\', '/')
  131. logger.debug("GALLERY: {0}".format(url))
  132. thumbnail = resizer.get_thumbnail_name(filename)
  133. thumbnail = path.join('/', generator.settings.get('THUMBNAIL_DIR', DEFAULT_THUMBNAIL_DIR), thumbnail).replace('\\', '/')
  134. lines.append(template.format(
  135. filename=filename,
  136. url=url,
  137. thumbnail=thumbnail,
  138. ))
  139. metadata['gallery_content'] = "\n".join(lines)
  140. def register():
  141. signals.finalized.connect(resize_thumbnails)
  142. signals.article_generator_context.connect(expand_gallery)