-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathio_tools.py
More file actions
38 lines (28 loc) · 1016 Bytes
/
io_tools.py
File metadata and controls
38 lines (28 loc) · 1016 Bytes
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
35
36
37
38
from __future__ import annotations
import io
import logging
import numpy as np
from PIL import Image, UnidentifiedImageError
log = logging.getLogger(__name__)
MAX_IMAGE_BYTES = 50 * 1024 * 1024
MIN_IMAGE_DIMENSION = 16
MAX_IMAGE_DIMENSION = 10000
def load_image_from_bytes(data: bytes) -> np.ndarray:
if not data:
raise ValueError("Image payload is empty")
if len(data) > MAX_IMAGE_BYTES:
raise ValueError("Image payload is too large")
try:
with Image.open(io.BytesIO(data)) as img:
img.load()
image = np.asarray(img.convert("RGB"))
except UnidentifiedImageError:
log.warning("Unidentified image. len=%s first16=%r", len(data), data[:16])
raise
height, width = image.shape[:2]
if min(height, width) < MIN_IMAGE_DIMENSION:
raise ValueError("Image is too small")
if max(height, width) > MAX_IMAGE_DIMENSION:
raise ValueError("Image is too large")
return image
__all__ = ["load_image_from_bytes"]