MCPcopy Index your code
hub / github.com/PySimpleGUI/PySimpleGUI / convert_to_bytes

Function convert_to_bytes

DemoPrograms/Demo_Image_Viewer_Thumbnails.py:37–67  ·  view source on GitHub ↗

Will convert into bytes and optionally resize an image that is a file or a base64 bytes object. Turns into PNG format in the process so that can be displayed by tkinter :param file_or_bytes: either a string filename or a bytes base64 image object :type file_or_bytes: (Union[str, b

(file_or_bytes, resize=None, fill=False)

Source from the content-addressed store, hash-verified

35
36
37def convert_to_bytes(file_or_bytes, resize=None, fill=False):
38 '''
39 Will convert into bytes and optionally resize an image that is a file or a base64 bytes object.
40 Turns into PNG format in the process so that can be displayed by tkinter
41 :param file_or_bytes: either a string filename or a bytes base64 image object
42 :type file_or_bytes: (Union[str, bytes])
43 :param resize: optional new size
44 :type resize: (Tuple[int, int] or None)
45 :return: (bytes) a byte-string object
46 :rtype: (bytes)
47 '''
48 if isinstance(file_or_bytes, str):
49 img = PIL.Image.open(file_or_bytes)
50 else:
51 try:
52 img = PIL.Image.open(io.BytesIO(base64.b64decode(file_or_bytes)))
53 except Exception as e:
54 dataBytesIO = io.BytesIO(file_or_bytes)
55 img = PIL.Image.open(dataBytesIO)
56
57 cur_width, cur_height = img.size
58 if resize:
59 new_width, new_height = resize
60 scale = min(new_height / cur_height, new_width / cur_width)
61 img = img.resize((int(cur_width * scale), int(cur_height * scale)), PIL.Image.LANCZOS)
62 if fill:
63 img = make_square(img, THUMBNAIL_SIZE[0])
64 with io.BytesIO() as bio:
65 img.save(bio, format="PNG")
66 del img
67 return bio.getvalue()
68
69
70

Callers 2

display_image_windowFunction · 0.70
display_imagesFunction · 0.70

Calls 2

saveMethod · 0.80
make_squareFunction · 0.70

Tested by

no test coverage detected