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