File size: 813 Bytes
dd85fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import base64
from typing import Optional

import cv2
import numpy as np


def encode_png_base64(image: np.ndarray) -> str:
    bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
    success, buf = cv2.imencode('.png', bgr)
    if not success:
        raise RuntimeError('Failed to encode image to PNG.')
    return base64.b64encode(buf.tobytes()).decode('ascii')


def decode_base64_image(data: str) -> np.ndarray:
    # Support data URLs: data:image/png;base64,....
    if ',' in data and data.strip().startswith('data:'):
        data = data.split(',', 1)[1]
    binary = base64.b64decode(data)
    arr = np.frombuffer(binary, dtype=np.uint8)
    image = cv2.imdecode(arr, cv2.IMREAD_COLOR)
    if image is None:
        raise ValueError('Unable to decode image.')
    return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)