Will convert into bytes and optionally resize an image that is a file or a base64 bytes object. :param file_or_bytes: either a string filename or a bytes base64 image object :type file_or_bytes: (str | bytes) :param resize: optional new size :type resize: ((int, int) | None)
(file_or_bytes, resize=None)
| 28 | |
| 29 | |
| 30 | def convert_to_bytes(file_or_bytes, resize=None): |
| 31 | ''' |
| 32 | Will convert into bytes and optionally resize an image that is a file or a base64 bytes object. |
| 33 | :param file_or_bytes: either a string filename or a bytes base64 image object |
| 34 | :type file_or_bytes: (str | bytes) |
| 35 | :param resize: optional new size |
| 36 | :type resize: ((int, int) | None) |
| 37 | :return: (bytes) a byte-string object |
| 38 | :rtype: (bytes) |
| 39 | ''' |
| 40 | if isinstance(file_or_bytes, str): |
| 41 | img = PIL.Image.open(file_or_bytes) |
| 42 | else: |
| 43 | img = PIL.Image.open(io.BytesIO(base64.b64decode(file_or_bytes))) |
| 44 | |
| 45 | cur_width, cur_height = img.size |
| 46 | if resize: |
| 47 | new_width, new_height = resize |
| 48 | scale = min(new_height/cur_height, new_width/cur_width) |
| 49 | img = img.resize((int(cur_width*scale), int(cur_height*scale)), PIL.Image.LANCZOS) |
| 50 | bio = io.BytesIO() |
| 51 | img.save(bio, format="PNG") |
| 52 | del img |
| 53 | return bio.getvalue() |
| 54 | |
| 55 | folder = sg.popup_get_folder('Where are your images?') |
| 56 | if not folder: |
no test coverage detected