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)
| 35 | |
| 36 | |
| 37 | def 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 |
no test coverage detected