thumbnailer.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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, keep_filename=False):
  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. if keep_filename:
  83. filename = path.join(out_path, path.basename(in_path))
  84. else:
  85. filename = path.join(out_path, self.get_thumbnail_name(in_path))
  86. if not path.exists(out_path):
  87. os.makedirs(out_path)
  88. if not path.exists(filename):
  89. try:
  90. image = Image.open(in_path)
  91. thumbnail = self.resize(image)
  92. thumbnail.save(filename)
  93. logger.info("Generated Thumbnail {0}".format(path.basename(filename)))
  94. except IOError:
  95. logger.info("Generating Thumbnail for {0} skipped".format(path.basename(filename)))
  96. def resize_thumbnails(pelican):
  97. """ Resize a directory tree full of images into thumbnails
  98. :param pelican: The pelican instance
  99. :return: None
  100. """
  101. global enabled
  102. if not enabled:
  103. return
  104. in_path = _image_path(pelican)
  105. out_path = path.join(pelican.settings['OUTPUT_PATH'],
  106. pelican.settings.get('THUMBNAIL_DIR', DEFAULT_THUMBNAIL_DIR))
  107. sizes = pelican.settings.get('THUMBNAIL_SIZES', DEFAULT_THUMBNAIL_SIZES)
  108. resizers = dict((k, _resizer(k, v)) for k,v in sizes.items())
  109. logger.debug("Thumbnailer Started")
  110. for dirpath, _, filenames in os.walk(in_path):
  111. for filename in filenames:
  112. for name, resizer in resizers.items():
  113. in_filename = path.join(dirpath, filename)
  114. logger.debug("Processing thumbnail {0}=>{1}".format(filename, name))
  115. if pelican.settings.get('THUMBNAIL_KEEP_NAME', False):
  116. resizer.resize_file_to(in_filename, path.join(out_path, name), True)
  117. else:
  118. resizer.resize_file_to(in_filename, out_path)
  119. def _image_path(pelican):
  120. return path.join(pelican.settings['PATH'],
  121. pelican.settings.get("IMAGE_PATH", DEFAULT_IMAGE_DIR))
  122. def expand_gallery(generator, metadata):
  123. """ Expand a gallery tag to include all of the files in a specific directory under IMAGE_PATH
  124. :param pelican: The pelican instance
  125. :return: None
  126. """
  127. if "gallery" not in metadata or metadata['gallery'] is None:
  128. return # If no gallery specified, we do nothing
  129. lines = [ ]
  130. base_path = _image_path(generator)
  131. in_path = path.join(base_path, metadata['gallery'])
  132. template = generator.settings.get('GALLERY_TEMPLATE', DEFAULT_TEMPLATE)
  133. thumbnail_name = generator.settings.get("GALLERY_THUMBNAIL", DEFAULT_GALLERY_THUMB)
  134. thumbnail_prefix = generator.settings.get("")
  135. resizer = _resizer(thumbnail_name, '?x?')
  136. for dirpath, _, filenames in os.walk(in_path):
  137. for filename in filenames:
  138. url = path.join(dirpath, filename).replace(base_path, "")[1:]
  139. url = path.join('/static', generator.settings.get('IMAGE_PATH', DEFAULT_IMAGE_DIR), url).replace('\\', '/')
  140. logger.debug("GALLERY: {0}".format(url))
  141. thumbnail = resizer.get_thumbnail_name(filename)
  142. thumbnail = path.join('/', generator.settings.get('THUMBNAIL_DIR', DEFAULT_THUMBNAIL_DIR), thumbnail).replace('\\', '/')
  143. lines.append(template.format(
  144. filename=filename,
  145. url=url,
  146. thumbnail=thumbnail,
  147. ))
  148. metadata['gallery_content'] = "\n".join(lines)
  149. def register():
  150. signals.finalized.connect(resize_thumbnails)
  151. signals.article_generator_context.connect(expand_gallery)