File size: 1,207 Bytes
ef75ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import io
import numpy as np
import numpy.typing as npt
from PIL import Image
from PIL.Image import Image as pilImage
import base64
import re
from diffusers.utils import PIL_INTERPOLATION

def img_binary_data_to_pil(imgBinary: bytes) -> pilImage:
    image_data = re.sub('^data:image/.+;base64,', '', imgBinary.decode())
    decoded = base64.b64decode(image_data)
    img = Image.open(io.BytesIO(decoded))
    return img

def resizePilToMaxSide(img: pilImage, maxSideLength: int) -> pilImage:
    w, h = img.size
    maxSide = max(w, h, maxSideLength)
    scale = maxSideLength / maxSide
    targetSize = (int(scale * w), int(scale * h))
    img = img.resize(targetSize, resample=PIL_INTERPOLATION["lanczos"])
    return img

def pil_to_base64(img: pilImage | npt.NDArray[np.uint8]) -> str:
    if type(img) is pilImage:
        pass
    elif type(img) is np.ndarray:
        img = pilImage.fromarray(img.astype('uint8'))
    else:
        raise TypeError
    
    # https://stackoverflow.com/a/59583262/13797085
    file_object = io.BytesIO()
    img.save(file_object, 'PNG')
    base64img = "data:image/png;base64," \
        + base64.b64encode(file_object.getvalue()).decode('ascii')
    return base64img