From 5bc2bbdacbfd36fd7f06e6027cbcc9fe66e5fc94 Mon Sep 17 00:00:00 2001 From: Ethan Dalool Date: Sat, 28 Apr 2018 20:33:05 -0700 Subject: [PATCH] Move image thumbnailing code to helpers. --- etiquette/helpers.py | 27 +++++++++++++++++++++++++++ etiquette/objects.py | 33 +++++++-------------------------- 2 files changed, 34 insertions(+), 26 deletions(-) diff --git a/etiquette/helpers.py b/etiquette/helpers.py index 8d908a6..4a21b3b 100644 --- a/etiquette/helpers.py +++ b/etiquette/helpers.py @@ -151,6 +151,33 @@ def fit_into_bounds(image_width, image_height, frame_width, frame_height): return (new_width, new_height) +def generate_image_thumbnail(filepath, width, height): + image = PIL.Image.open(filepath) + (width, height) = image.size + (new_width, new_height) = fit_into_bounds( + image_width=width, + image_height=height, + frame_width=width, + frame_height=height, + ) + if new_width < width: + image = image.resize((new_width, new_height)) + + if image.mode == 'RGBA': + background = checkerboard_image( + color_1=(256, 256, 256), + color_2=(128, 128, 128), + image_size=image.size, + checker_size=8, + ) + # Thanks Yuji Tomita + # http://stackoverflow.com/a/9459208 + background.paste(image, mask=image.split()[3]) + image = background + + image = image.convert('RGB') + return image + def get_mimetype(filepath): ''' Extension to mimetypes.guess_type which uses my diff --git a/etiquette/objects.py b/etiquette/objects.py index 62a780e..0531416 100644 --- a/etiquette/objects.py +++ b/etiquette/objects.py @@ -790,33 +790,14 @@ class Photo(ObjectBase): if self.simple_mimetype == 'image': self.photodb.log.debug('Thumbnailing %s', self.real_path.absolute_path) try: - image = PIL.Image.open(self.real_path.absolute_path) - except (OSError, ValueError): - pass - else: - (width, height) = image.size - (new_width, new_height) = helpers.fit_into_bounds( - image_width=width, - image_height=height, - frame_width=self.photodb.config['thumbnail_width'], - frame_height=self.photodb.config['thumbnail_height'], + image = helpers.generate_image_thumbnail( + self.real_path.absolute_path, + width=self.photodb.config['thumbnail_width'], + height=self.photodb.config['thumbnail_height'], ) - if new_width < width: - image = image.resize((new_width, new_height)) - - if image.mode == 'RGBA': - background = helpers.checkerboard_image( - color_1=(256, 256, 256), - color_2=(128, 128, 128), - image_size=image.size, - checker_size=8, - ) - # Thanks Yuji Tomita - # http://stackoverflow.com/a/9459208 - background.paste(image, mask=image.split()[3]) - image = background - - image = image.convert('RGB') + except (OSError, ValueError): + traceback.print_exc() + else: image.save(hopeful_filepath.absolute_path, quality=50) return_filepath = hopeful_filepath