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

Function convert_to_bytes

DemoPrograms/Demo_PIL_Use.py:30–73  ·  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 source: either a string filename or a bytes base64 image object :type source: (Union[str, bytes]) :pa

(source, size=(None, None), subsample=None, zoom=None, fill=False)

Source from the content-addressed store, hash-verified

28
29
30def convert_to_bytes(source, size=(None, None), subsample=None, zoom=None, fill=False):
31 """
32 Will convert into bytes and optionally resize an image that is a file or a base64 bytes object.
33 Turns into PNG format in the process so that can be displayed by tkinter
34 :param source: either a string filename or a bytes base64 image object
35 :type source: (Union[str, bytes])
36 :param size: optional new size (width, height)
37 :type size: (Tuple[int, int] or None)
38 :param subsample: change the size by multiplying width and height by 1/subsample
39 :type subsample: (int)
40 :param zoom: change the size by multiplying width and height by zoom
41 :type zoom: (int)
42 :param fill: If True then the image is filled/padded so that the image is square
43 :type fill: (bool)
44 :return: (bytes) a byte-string object
45 :rtype: (bytes)
46 """
47 if isinstance(source, str):
48 image = Image.open(source)
49 elif isinstance(source, bytes):
50 image = Image.open(io.BytesIO(base64.b64decode(source)))
51 else:
52 image = PIL.Image.open(io.BytesIO(source))
53
54 width, height = image.size
55
56 scale = None
57 if size != (None, None):
58 new_width, new_height = size
59 scale = min(new_height/height, new_width/width)
60 elif subsample is not None:
61 scale = 1/subsample
62 elif zoom is not None:
63 scale = zoom
64
65 resized_image = image.resize((int(width * scale), int(height * scale)), Image.LANCZOS) if scale is not None else image
66 if fill and scale is not None:
67 resized_image = make_square(resized_image)
68 # encode a PNG formatted version of image into BASE64
69 with io.BytesIO() as bio:
70 resized_image.save(bio, format="PNG")
71 contents = bio.getvalue()
72 encoded = base64.b64encode(contents)
73 return encoded
74
75
76

Callers 2

make_toolbarFunction · 0.70
mainFunction · 0.70

Calls 2

saveMethod · 0.80
make_squareFunction · 0.70

Tested by

no test coverage detected