From 7731b07f1f1ede74d73cd413c81be415da8ff4a7 Mon Sep 17 00:00:00 2001 From: PySimpleGUI Date: Sat, 25 Jul 2020 17:45:19 -0400 Subject: [PATCH] changed convert_to_bytes function to use a context manager for better memory management --- .../Demo_Image_Elem_Image_Viewer_PIL_Based.py | 16 +++++++++++----- .../Demo_Matplotlib_Grid_of_Graphs_Using_PIL.py | 8 ++++---- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/DemoPrograms/Demo_Image_Elem_Image_Viewer_PIL_Based.py b/DemoPrograms/Demo_Image_Elem_Image_Viewer_PIL_Based.py index 686ac6c3..715bb351 100644 --- a/DemoPrograms/Demo_Image_Elem_Image_Viewer_PIL_Based.py +++ b/DemoPrograms/Demo_Image_Elem_Image_Viewer_PIL_Based.py @@ -20,6 +20,7 @@ import base64 """ + def convert_to_bytes(file_or_bytes, resize=None): ''' Will convert into bytes and optionally resize an image that is a file or a base64 bytes object. @@ -34,17 +35,22 @@ def convert_to_bytes(file_or_bytes, resize=None): if isinstance(file_or_bytes, str): img = PIL.Image.open(file_or_bytes) else: - img = PIL.Image.open(io.BytesIO(base64.b64decode(file_or_bytes))) + try: + img = PIL.Image.open(io.BytesIO(base64.b64decode(file_or_bytes))) + except Exception as e: + dataBytesIO = io.BytesIO(file_or_bytes) + img = PIL.Image.open(dataBytesIO) cur_width, cur_height = img.size if resize: new_width, new_height = resize scale = min(new_height/cur_height, new_width/cur_width) img = img.resize((int(cur_width*scale), int(cur_height*scale)), PIL.Image.ANTIALIAS) - bio = io.BytesIO() - img.save(bio, format="PNG") - del img - return bio.getvalue() + with io.BytesIO() as bio: + img.save(bio, format="PNG") + del img + return bio.getvalue() + # --------------------------------- Define Layout --------------------------------- diff --git a/DemoPrograms/Demo_Matplotlib_Grid_of_Graphs_Using_PIL.py b/DemoPrograms/Demo_Matplotlib_Grid_of_Graphs_Using_PIL.py index c26a8650..f42f26ee 100644 --- a/DemoPrograms/Demo_Matplotlib_Grid_of_Graphs_Using_PIL.py +++ b/DemoPrograms/Demo_Matplotlib_Grid_of_Graphs_Using_PIL.py @@ -891,10 +891,10 @@ def convert_to_bytes(file_or_bytes, resize=None): new_width, new_height = resize scale = min(new_height/cur_height, new_width/cur_width) img = img.resize((int(cur_width*scale), int(cur_height*scale)), PIL.Image.ANTIALIAS) - bio = io.BytesIO() - img.save(bio, format="PNG") - del img - return bio.getvalue() + with io.BytesIO() as bio: + img.save(bio, format="PNG") + del img + return bio.getvalue()