#!/usr/bin/python3
+import PIL
+import io
import logging
import os.path
import re
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()
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):