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__":