Skip to content

Instantly share code, notes, and snippets.

@villares
Created November 8, 2022 21:44
Show Gist options
  • Save villares/b9749601848e4926124367c742f42494 to your computer and use it in GitHub Desktop.
Save villares/b9749601848e4926124367c742f42494 to your computer and use it in GitHub Desktop.
for use with PySimpleGUI
import PIL.Image
import io
def image_as_png_bytes(file_path, resize=None):
"""
Open an image file and convert it into PNG formated bytes, resize optional.
Return tuple (bytes, <dict from PIL.Image.info>)
"""
img = PIL.Image.open(file_path)
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.Resampling.LANCZOS,
)
with io.BytesIO() as bio:
img.save(bio, format='PNG')
return bio.getvalue(), img.info
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment