File size: 1,129 Bytes
e04bbc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import base64
import re

import cv2
import numpy as np


_PNG_DATA_URI_PREFIX = "data:image/png;base64,"
_DATA_URI_RE = re.compile(r"^data:image/[a-zA-Z0-9.+-]+;base64,")


def bgr_to_png_b64(img: np.ndarray) -> str:
    """Encode a BGR or grayscale uint8 image as a data: URI PNG."""
    ok, buf = cv2.imencode(".png", img)
    if not ok:
        raise ValueError("cv2.imencode failed")
    return _PNG_DATA_URI_PREFIX + base64.b64encode(buf.tobytes()).decode("ascii")


def img_b64_to_bgr(encoded: str) -> np.ndarray:
    """Decode any base64-encoded image (PNG, JPEG, ...) — with or without a

    ``data:image/<fmt>;base64,`` prefix — into a BGR/grayscale ndarray.



    cv2.imdecode auto-detects the format from the bytes' magic header, so

    the URI prefix (if present) is only used to strip non-base64 bytes.

    """
    stripped = _DATA_URI_RE.sub("", encoded, count=1)
    raw = base64.b64decode(stripped)
    arr = np.frombuffer(raw, dtype=np.uint8)
    img = cv2.imdecode(arr, cv2.IMREAD_UNCHANGED)
    if img is None:
        raise ValueError("cv2.imdecode failed")
    return img