File size: 619 Bytes
dda6bed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
core/image_utils.py — image encoding helpers.
"""

import base64
import io

from PIL import Image

from config import IMAGE_QUALITY


def pil_to_data_url(image: Image.Image) -> str:
    """
    Convert a PIL image to a JPEG base64 data URL suitable for the API.

    Args:
        image: Any PIL Image (RGB, RGBA, P, …).

    Returns:
        String of the form  'data:image/jpeg;base64,<b64>'
    """
    image = image.convert("RGB")
    buf = io.BytesIO()
    image.save(buf, format="JPEG", quality=IMAGE_QUALITY)
    b64 = base64.b64encode(buf.getvalue()).decode()
    return f"data:image/jpeg;base64,{b64}"