add custom thumbnail backend to store .webp variants
authorFrédéric Péters <fpeters@0d.be>
Wed, 20 Apr 2022 16:16:11 +0000 (18:16 +0200)
committerFrédéric Péters <fpeters@0d.be>
Wed, 20 Apr 2022 16:16:11 +0000 (18:16 +0200)
panikweb/settings.py
panikweb/utils.py

index de64a1c7989cb4c2bc6aba88107bf2e854d0bd17..6e0b6416f0c745b2c6ff895bc2c435abd5599586 100644 (file)
@@ -264,6 +264,7 @@ PROGRAM_PREFIX = 'programme/'
 EMISSIONS_PREFIX = 'emissions/'
 NEWSITEMS_PREFIX = 'actus/'
 
+THUMBNAIL_BACKEND = 'panikweb.utils.ThumbnailBackend'
 
 COMBO_INITIAL_LOGIN_PAGE_PATH = '/'
 COMBO_WELCOME_PAGE_PATH = None
index b36714f8fa2762bdecf6061f5410a79868c96cb8..2fef9374b2ba8d709b5eb853b26ed8f7691e3a86 100644 (file)
@@ -1,5 +1,10 @@
 from datetime import datetime, timedelta
 
+import sorl.thumbnail.base
+from sorl.thumbnail import default
+from sorl.thumbnail.images import ImageFile
+from sorl.thumbnail.parsers import parse_geometry
+
 
 def tofirstdayinisoweek(year, week):
     # from http://stackoverflow.com/questions/5882405/get-date-from-iso-week-number-in-python
@@ -7,3 +12,19 @@ def tofirstdayinisoweek(year, week):
     if datetime(year, 1, 4).isoweekday() > 4:
         ret -= timedelta(days=7)
     return ret
+
+
+class ThumbnailBackend(sorl.thumbnail.base.ThumbnailBackend):
+    def _create_alternative_resolutions(self, source_image, geometry_string, options, name):
+        super()._create_alternative_resolutions(source_image, geometry_string, options, name)
+        # create .webp alternative, to be served to appropriate browsers
+        ratio = default.engine.get_image_ratio(source_image, options)
+        geometry = parse_geometry(geometry_string, ratio)
+        options = options.copy()
+        options['format'] = 'WEBP'
+        image = default.engine.create(source_image, geometry, options)
+        thumbnail_name = '%(file_name)s.webp' % {'file_name': name}
+        thumbnail = ImageFile(thumbnail_name, default.storage)
+        default.engine.write(image, options, thumbnail)
+        size = default.engine.get_image_size(image)
+        thumbnail.set_size(size)