From: Michael Tremer Date: Sun, 18 Nov 2018 18:19:06 +0000 (+0000) Subject: wiki: Automatically resize images X-Git-Url: http://git.ipfire.org/?p=ipfire.org.git;a=commitdiff_plain;h=79dd9a0fb4d3c223b3bc55575692367832ea6be2 wiki: Automatically resize images Signed-off-by: Michael Tremer --- diff --git a/src/backend/wiki.py b/src/backend/wiki.py index 2b65d017..c963b9a1 100644 --- a/src/backend/wiki.py +++ b/src/backend/wiki.py @@ -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() diff --git a/src/web/wiki.py b/src/web/wiki.py index 2afe1ea7..b8058427 100644 --- a/src/web/wiki.py +++ b/src/web/wiki.py @@ -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):