Spaces:
Sleeping
Sleeping
File size: 1,448 Bytes
e76ee44 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
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 |