]> git.ipfire.org Git - ipfire.org.git/commitdiff
wiki: Automatically resize images
authorMichael Tremer <michael.tremer@ipfire.org>
Sun, 18 Nov 2018 18:19:06 +0000 (18:19 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Sun, 18 Nov 2018 18:19:06 +0000 (18:19 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/backend/wiki.py
src/web/wiki.py

index 2b65d017bb67fdd35083b0397d629f3050e9c4a4..c963b9a1ca85b644dd1d2a16fbf1708603576ed7 100644 (file)
@@ -1,5 +1,7 @@
 #!/usr/bin/python3
 
+import PIL
+import io
 import logging
 import os.path
 import re
@@ -290,3 +292,19 @@ class File(misc.Object):
 
                if res:
                        return bytes(res.data)
+
+       def get_thumbnail(self, size):
+               image = PIL.Image.open(io.BytesIO(self.blob))
+
+               # Resize the image to the desired resolution
+               image.thumbnail((size, size), PIL.Image.ANTIALIAS)
+
+               with io.BytesIO() as f:
+                       # If writing out the image does not work with optimization,
+                       # we try to write it out without any optimization.
+                       try:
+                               image.save(f, image.format, optimize=True, quality=98)
+                       except:
+                               image.save(f, image.format, quality=98)
+
+                       return f.getvalue()
index 2afe1ea7c3db502aedc1ec6347bc3b527174ba96..b8058427d6302c277ac4b4a676d58a11131e21e2 100644 (file)
@@ -41,11 +41,20 @@ class FileHandler(auth.CacheMixin, base.BaseHandler):
                if not file:
                        raise tornado.web.HTTPError(404, "Could not find %s" % path)
 
+               size = self.get_argument_int("s", None)
+
+               # Check if image should be resized
+               if file.is_image() and size:
+                       blob = file.get_thumbnail(size)
+               else:
+                       blob = file.blob
+
                # Set headers
                self.set_header("Content-Type", file.mimetype or "application/octet-stream")
-               self.set_header("Content-Length", file.size)
+               self.set_header("Content-Length", len(blob))
 
-               self.finish(file.blob)
+               # Deliver content
+               self.finish(blob)
 
 
 class PageHandler(auth.CacheMixin, base.BaseHandler):