Coverage for src/blob_dict/blob/image.py: 0%
32 statements
« prev ^ index » next coverage.py v7.8.1, created at 2025-05-23 02:51 -0700
« prev ^ index » next coverage.py v7.8.1, created at 2025-05-23 02:51 -0700
1from __future__ import annotations
3from pathlib import Path
4from typing import Self, override
6from extratools_image import bytes_to_image, image_to_bytes
7from PIL.Image import Image
9from . import BytesBlob
12class ImageBlob(BytesBlob):
13 def __init__(self, blob: bytes | Image) -> None:
14 if isinstance(blob, Image):
15 blob = image_to_bytes(blob)
17 super().__init__(blob)
19 def as_image(self) -> Image:
20 return bytes_to_image(self._blob_bytes)
22 @override
23 def __repr__(self) -> str:
24 return f"{self.__class__.__name__}(...)"
26 @classmethod
27 @override
28 def load(cls: type[Self], f: Path | str) -> Self:
29 f = Path(f).expanduser()
30 img_format: str = f.suffix.lstrip('.').lower()
31 img_bytes: bytes = f.read_bytes()
33 if img_format == "png":
34 return cls(img_bytes)
36 return cls(bytes_to_image(img_bytes, _format=img_format))
38 @override
39 def dump(self, f: Path | str) -> None:
40 f = Path(f).expanduser()
41 if f.suffix.lower() != ".png":
42 msg = "Only PNG file is supported."
43 raise ValueError(msg)
45 f.write_bytes(self.as_bytes())