From 1a226c83e57a1856fabb76c49a43e51e9857872c Mon Sep 17 00:00:00 2001 From: Michael Tremer Date: Thu, 11 Oct 2018 12:25:45 +0100 Subject: [PATCH] accounts: Convert images into RGB when they use an alpha channel Signed-off-by: Michael Tremer --- src/backend/accounts.py | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/src/backend/accounts.py b/src/backend/accounts.py index b35874c9..1b06d662 100644 --- a/src/backend/accounts.py +++ b/src/backend/accounts.py @@ -349,19 +349,24 @@ class Account(Object): return self._resize_avatar(avatar, size) def _resize_avatar(self, image, size): - 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() + image = PIL.Image.open(io.BytesIO(image)) + + # Convert RGBA images into RGB because JPEG doesn't support alpha-channels + if image.mode == "RGBA": + image = image.convert("RGB") + + # 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