DmitryPlant's picture
Deploy local
e04bbc2 verified
Raw History Blame Contribute Delete
1.13 kB
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