Coverage for src/blob_dict/blob/image.py: 0%

32 statements  

« prev     ^ index     » next       coverage.py v7.8.1, created at 2025-05-21 20:53 -0700

1from __future__ import annotations 

2 

3from pathlib import Path 

4from typing import Self, override 

5 

6from extratools_image import bytes_to_image, image_to_bytes 

7from PIL.Image import Image 

8 

9from . import BytesBlob 

10 

11 

12class ImageBlob(BytesBlob): 

13 def __init__(self, blob: bytes | Image) -> None: 

14 if isinstance(blob, Image): 

15 blob = image_to_bytes(blob) 

16 

17 super().__init__(blob) 

18 

19 def as_image(self) -> Image: 

20 return bytes_to_image(self._blob_bytes) 

21 

22 @override 

23 def __repr__(self) -> str: 

24 return f"{self.__class__.__name__}(...)" 

25 

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() 

32 

33 if img_format == "png": 

34 return cls(img_bytes) 

35 

36 return cls(bytes_to_image(img_bytes, _format=img_format)) 

37 

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) 

44 

45 f.write_bytes(self.as_bytes())