diff options
author | Philipp Hörist <forenjunkie@chello.at> | 2017-11-26 15:38:18 +0300 |
---|---|---|
committer | Philipp Hörist <forenjunkie@chello.at> | 2017-11-26 15:38:18 +0300 |
commit | 1d17a08659329a3033d4d70a882d865bb9d7ee9e (patch) | |
tree | ccc2a57773230ce5280d2d5a22b3db3ccfbb3147 | |
parent | 887d278d0a4d330d4724a6cdd1649c7d430c8c2b (diff) |
[preview] Preserve aspect ratio while scaling
-rw-r--r-- | url_image_preview/resize_gif.py | 1 | ||||
-rw-r--r-- | 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( @@ -304,6 +303,23 @@ class Base(object): 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] if ext == '.gif': |