Spaces:
Sleeping
Sleeping
import base64 | |
from datetime import datetime | |
from io import BytesIO | |
import os | |
from typing import Union | |
from PIL import Image | |
class Common: | |
def __init__(self, is_debug=False) -> None: | |
self.is_debug = is_debug | |
self.image_color_mode = 'RGB' | |
self.image_format_png = 'PNG' | |
self.image_format_jpeg = 'JPEG' | |
def today(self): | |
return datetime.today().strftime('%Y%m%d%H%M%S') | |
def create_dir_not_exist(self, target_dir:str): | |
if not os.path.exists(target_dir): | |
os.mkdir(target_dir) | |
def base64str_to_image(self, content:Union[bytes, None]): | |
return Image.open(BytesIO(base64.b64decode(content))).convert(self.image_color_mode) | |
def base64str_to_bytes(self, content:str): | |
orig_image = Image.open(BytesIO(base64.b64decode(content))).convert('RGB') | |
img_bytes = BytesIO() | |
# image.save expects a file-like as a argument | |
orig_image.save(img_bytes, format=self.image_format_jpeg) | |
# Turn the BytesIO object back into a bytes object | |
img_bytes = img_bytes.getvalue() | |
return img_bytes | |
def imagearray_to_image(self, image_arr): | |
return Image.fromarray(image_arr) | |
def image_to_base64str(self, image:Image): | |
buffered = BytesIO() | |
image.save(buffered, format=self.image_format_png) | |
img_base64str = base64.b64encode(buffered.getvalue()) | |
return img_base64str |