From 4792d8756cb7803e7eaf7c8f7420bd380dd8a000 Mon Sep 17 00:00:00 2001 From: Michael Tremer Date: Thu, 11 Oct 2018 12:18:51 +0100 Subject: [PATCH] accounts: Refactor avatar generation Signed-off-by: Michael Tremer --- src/backend/accounts.py | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/src/backend/accounts.py b/src/backend/accounts.py index e1401f16..b35874c9 100644 --- a/src/backend/accounts.py +++ b/src/backend/accounts.py @@ -349,22 +349,19 @@ class Account(Object): return self._resize_avatar(avatar, size) def _resize_avatar(self, image, size): - image = io.BytesIO(image) - image = PIL.Image.open(image) - - # Resize the image to the desired resolution - image.thumbnail((size, size), PIL.Image.ANTIALIAS) - - f = io.BytesIO() - - # If writing out the image does not work with optimization, - # we try to write it out without any optimization. - try: - image.save(f, "JPEG", optimize=True, quality=98) - except: - image.save(f, "JPEG", quality=98) - - return f.getvalue() + with PIL.Image.open(io.BytesIO(image)) as image: + # 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, "JPEG", optimize=True, quality=98) + except: + image.save(f, "JPEG", quality=98) + + return f.getvalue() if __name__ == "__main__": -- 2.47.3