-
Notifications
You must be signed in to change notification settings - Fork 128
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
53 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import base64 | ||
from io import BytesIO | ||
from pathlib import Path | ||
from typing import Union | ||
|
||
import numpy as np | ||
from PIL import Image | ||
|
||
|
||
def b64_to_pil(b64_str: str) -> Image: | ||
# , can't be encoded in b64 data so must be part of prefix | ||
if "," in b64_str: | ||
b64_str = b64_str.split(",")[1] | ||
return Image.open(BytesIO(base64.b64decode(b64_str))) | ||
|
||
|
||
def convert_to_b64(data: Union[str, Path, np.ndarray, Image.Image]) -> str: | ||
if data is None: | ||
raise ValueError(f"Invalid input image: {data}. Input image can't be None.") | ||
if isinstance(data, (str, Path)): | ||
data = Image.open(data) | ||
if isinstance(data, Image.Image): | ||
buffer = BytesIO() | ||
data.save(buffer, format="PNG") | ||
return base64.b64encode(buffer.getvalue()).decode("utf-8") | ||
else: | ||
arr_bytes = data.tobytes() | ||
return base64.b64encode(arr_bytes).decode("utf-8") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters