Skip to content

encoding

encoding

Module for encoding files, data or arrays

Functions

base64_to_bytesio

base64_to_bytesio(encoded_data)

Returns a BytesIO stream of the decoded data

Source code in niceml/utilities/encoding.py
def base64_to_bytesio(encoded_data: Union[bytes, str]) -> BytesIO:
    """Returns a BytesIO stream of the decoded data"""
    # can be used with PIL.Image.open to get an image
    return BytesIO(base64.b64decode(encoded_data))

get_base64_from_file

get_base64_from_file(filepath, filesystem=None)

Returns a file encoded as base64

Source code in niceml/utilities/encoding.py
def get_base64_from_file(
    filepath: str, filesystem: Optional[AbstractFileSystem] = None
) -> bytes:
    """Returns a file encoded as base64"""
    if filesystem is None:
        filesystem = LocalFileSystem()

    with filesystem.open(filepath, "rb") as target_file:
        encoded_string = base64.b64encode(target_file.read())

    return encoded_string

numpy_to_base64

numpy_to_base64(array, format='png')

Stores a numpy array as base 64. Only works with correct format restrictions.

Source code in niceml/utilities/encoding.py
def numpy_to_base64(
    array: np.ndarray, format: str = "png"
) -> str:  # pylint: disable=redefined-builtin
    """Stores a numpy array as base 64. Only works with correct format restrictions."""
    pil_img = Image.fromarray(array)
    buff = BytesIO()
    pil_img.save(buff, format=format)
    return base64.b64encode(buff.getvalue()).decode("utf-8")