Created
November 8, 2022 21:44
-
-
Save villares/b9749601848e4926124367c742f42494 to your computer and use it in GitHub Desktop.
for use with PySimpleGUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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