production-taskbar / backend / config / utils / pillow.py
pillow.py
Raw
import base64
from io import BytesIO

from PIL import Image


def concat_images(img1: bytes, img2: bytes) -> BytesIO:

    im1 = Image.open(BytesIO(img1))
    im2 = Image.open(BytesIO(img2))

    dst = Image.new('RGB', (
        im1.width if im1.width > im2.width else im2.width,
        im1.height + im2.height,
    ))
    dst.paste(im1, (0, 0))
    dst.paste(im2, (0, im1.height))
    image_content = BytesIO()
    dst.seek(0)
    dst.save(image_content, format='JPEG')
    image_content.seek(0)
    return image_content


def image_data_to_data_url(data: bytes, ext: str | None = None) -> str | None:
    buffered = BytesIO()
    try:
        image = Image.open(BytesIO(data))
        _ext = ext or image.format
        image.save(buffered, format=_ext)
        base64_data = base64.b64encode(buffered.getvalue()).decode('utf-8')
        return f'data:image/{_ext.lower()};base64,{base64_data}'
    except Exception:
        return None