From 1d17a08659329a3033d4d70a882d865bb9d7ee9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philipp=20H=C3=B6rist?= Date: Sun, 26 Nov 2017 13:38:18 +0100 Subject: [PATCH] [preview] Preserve aspect ratio while scaling --- url_image_preview/resize_gif.py | 1 + url_image_preview/url_image_preview.py | 26 +++++++++++++++++++++----- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/url_image_preview/resize_gif.py b/url_image_preview/resize_gif.py index 0f04535..c5f0abd 100644 --- a/url_image_preview/resize_gif.py +++ b/url_image_preview/resize_gif.py @@ -74,6 +74,7 @@ def extract_and_resize_frames(mem, resize_to): new_frame.paste(image, (0, 0), image.convert('RGBA')) + # This method preservs aspect ratio new_frame.thumbnail(resize_to, Image.ANTIALIAS) frames.append(new_frame) diff --git a/url_image_preview/url_image_preview.py b/url_image_preview/url_image_preview.py index 4434d6c..068cfa0 100644 --- a/url_image_preview/url_image_preview.py +++ b/url_image_preview/url_image_preview.py @@ -279,18 +279,17 @@ class Base(object): try: self._create_path(os.path.dirname(thumbpath)) - height, width = pixbuf.get_height(), pixbuf.get_width() thumbnail = pixbuf if isinstance(pixbuf, GdkPixbuf.PixbufAnimation): - if size <= height and size <= width: + if size < pixbuf.get_width() or size < pixbuf.get_height(): resize_gif(mem, thumbpath, (size, size)) thumbnail = self._load_thumbnail(thumbpath) else: self._write_file(thumbpath, mem) else: - if size <= height and size <= width: - thumbnail = pixbuf.scale_simple( - size, size, GdkPixbuf.InterpType.BILINEAR) + width, height = self._get_thumbnail_size(pixbuf, size) + thumbnail = pixbuf.scale_simple( + width, height, GdkPixbuf.InterpType.BILINEAR) thumbnail.savev(thumbpath, 'png', [], []) except Exception as error: dialogs.ErrorDialog( @@ -303,6 +302,23 @@ class Base(object): return return thumbnail + @staticmethod + def _get_thumbnail_size(pixbuf, size): + # Calculates the new thumbnail size while preserving the aspect ratio + image_width = pixbuf.get_width() + image_height = pixbuf.get_height() + + if image_width > image_height: + if image_width > size: + image_height = int(size / float(image_width) * image_height) + image_width = int(size) + else: + if image_height > size: + image_width = int(size / float(image_height) * image_width) + image_height = int(size) + + return image_width, image_height + @staticmethod def _load_thumbnail(thumbpath): ext = os.path.splitext(thumbpath)[1]