2 # Copyright (C) 2018 rubenwardy
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <https://www.gnu.org/licenses/>.
18 from flask import abort, send_file, Blueprint, current_app
20 bp = Blueprint("thumbnails", __name__)
25 ALLOWED_RESOLUTIONS=[(100,67), (270,180), (350,233)]
28 assert path != "" and path is not None
30 if not os.path.isdir(path):
32 except FileExistsError:
36 def resize_and_crop(img_path, modified_path, size):
38 img = Image.open(img_path)
39 except FileNotFoundError:
42 # Get current and desired ratio for the images
43 img_ratio = img.size[0] / float(img.size[1])
44 ratio = size[0] / float(size[1])
46 # Is more portrait than target, scale and crop
48 img = img.resize((int(size[0]), int(size[0] * img.size[1] / img.size[0])),
50 box = (0, (img.size[1] - size[1]) / 2, img.size[0], (img.size[1] + size[1]) / 2)
53 # Is more landscape than target, scale and crop
54 elif ratio < img_ratio:
55 img = img.resize((int(size[1] * img.size[0] / img.size[1]), int(size[1])),
57 box = ((img.size[0] - size[0]) / 2, 0, (img.size[0] + size[0]) / 2, img.size[1])
60 # Is exactly the same ratio as target
62 img = img.resize(size, Image.BICUBIC)
64 img.save(modified_path)
67 @bp.route("/thumbnails/<int:level>/<img>")
68 def make_thumbnail(img, level):
69 if level > len(ALLOWED_RESOLUTIONS) or level <= 0:
72 w, h = ALLOWED_RESOLUTIONS[level - 1]
74 upload_dir = current_app.config["UPLOAD_DIR"]
75 thumbnail_dir = current_app.config["THUMBNAIL_DIR"]
78 output_dir = os.path.join(thumbnail_dir, str(level))
81 cache_filepath = os.path.join(output_dir, img)
82 source_filepath = os.path.join(upload_dir, img)
84 resize_and_crop(source_filepath, cache_filepath, (w, h))
85 return send_file(cache_filepath)