Merge pull request #3187 from PySimpleGUI/Dev-latest

changed convert_to_bytes function to use a context manager for better…
This commit is contained in:
PySimpleGUI 2020-07-25 17:45:38 -04:00 committed by GitHub
commit 1678576eb3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 9 deletions

View File

@ -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,19 +35,24 @@ def convert_to_bytes(file_or_bytes, resize=None):
if isinstance(file_or_bytes, str):
img = PIL.Image.open(file_or_bytes)
else:
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()
with io.BytesIO() as bio:
img.save(bio, format="PNG")
del img
return bio.getvalue()
# --------------------------------- Define Layout ---------------------------------
# First the window layout...2 columns

View File

@ -891,7 +891,7 @@ 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()
with io.BytesIO() as bio:
img.save(bio, format="PNG")
del img
return bio.getvalue()