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

Function convert_to_bytes

DemoPrograms/Demo_PNG_Thumbnail_Viewer.py:38–68  ·  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)

Source from the content-addressed store, hash-verified

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

Callers 1

Calls 1

saveMethod · 0.80

Tested by

no test coverage detected